function trySubmit() { global $wgOut, $wgUser; $errors = array(); $ip = $this->mUnblockIP; if (!IP::isIPAddress($ip) && strlen($ip)) { $errors[] = array('globalblocking-unblock-ipinvalid', $ip); $ip = ''; } if (0 == ($id = GlobalBlocking::getGlobalBlockId($ip))) { $errors[] = array('globalblocking-notblocked', $ip); } if (count($errors) > 0) { return $errors; } $dbw = GlobalBlocking::getGlobalBlockingMaster(); $dbw->delete('globalblocks', array('gb_id' => $id), __METHOD__); $page = new LogPage('gblblock'); $page->addEntry('gunblock', Title::makeTitleSafe(NS_USER, $ip), $this->mReason); $successmsg = wfMsgExt('globalblocking-unblock-unblocked', array('parse'), $ip, $id); $wgOut->addHTML($successmsg); $link = $wgUser->getSkin()->makeKnownLinkObj(SpecialPage::getTitleFor('GlobalBlockList'), wfMsg('globalblocking-return')); $wgOut->addHTML($link); $wgOut->setSubtitle(wfMsg('globalblocking-unblock-successsub')); return array(); }
/** * @param string|MWRestrictions $value The value the field was submitted with * @param array $alldata The data collected from the form * * @return bool|string True on success, or String error to display, or * false to fail validation without displaying an error. */ public function validate($value, $alldata) { if ($this->isHidden($alldata)) { return true; } if (isset($this->mParams['required']) && $this->mParams['required'] !== false && $value instanceof MWRestrictions && !$value->toArray()['IPAddresses']) { return $this->msg('htmlform-required')->parse(); } if (is_string($value)) { // MWRestrictions::newFromArray failed; one of the IP ranges must be invalid $status = Status::newGood(); foreach (explode(PHP_EOL, $value) as $range) { if (!\IP::isIPAddress($range)) { $status->fatal('restrictionsfield-badip', $range); } } if ($status->isOK()) { $status->fatal('unknown-error'); } return $status->getMessage()->parse(); } if (isset($this->mValidationCallback)) { return call_user_func($this->mValidationCallback, $value, $alldata, $this->mParent); } return true; }
public function execute($par) { global $wgLogRestrictions; $this->setHeaders(); $this->outputHeader(); $opts = new FormOptions(); $opts->add('type', ''); $opts->add('user', ''); $opts->add('page', ''); $opts->add('pattern', false); // $opts->add( 'year', null, FormOptions::INTNULL ); don't default to zero $opts->add('year', ''); $opts->add('month', null, FormOptions::INTNULL); $opts->add('tagfilter', ''); $opts->add('offset', ''); $opts->add('dir', ''); $opts->add('offender', ''); // Set values $opts->fetchValuesFromRequest($this->getRequest()); if ($par !== null) { $this->parseParams($opts, (string) $par); } # Don't let the user get stuck with a certain date if ($opts->getValue('offset') || $opts->getValue('dir') == 'prev') { $opts->setValue('year', ''); $opts->setValue('month', ''); } // If the user doesn't have the right permission to view the specific // log type, throw a PermissionsError // If the log type is invalid, just show all public logs $type = $opts->getValue('type'); if (!LogPage::isLogType($type)) { $opts->setValue('type', ''); } elseif (isset($wgLogRestrictions[$type]) && !$this->getUser()->isAllowed($wgLogRestrictions[$type])) { throw new PermissionsError($wgLogRestrictions[$type]); } # Handle type-specific inputs $qc = array(); if ($opts->getValue('type') == 'suppress') { $offender = User::newFromName($opts->getValue('offender'), false); if ($offender && $offender->getId() > 0) { $qc = array('ls_field' => 'target_author_id', 'ls_value' => $offender->getId()); } elseif ($offender && IP::isIPAddress($offender->getName())) { $qc = array('ls_field' => 'target_author_ip', 'ls_value' => $offender->getName()); } } # Some log types are only for a 'User:'******'User:username'. This part try # to lookup for a user by that name and eventually fix user input. See bug 1697. wfRunHooks('GetLogTypesOnUser', array(&$this->typeOnUser)); if (in_array($opts->getValue('type'), $this->typeOnUser)) { # ok we have a type of log which expect a user title. $target = Title::newFromText($opts->getValue('page')); if ($target && $target->getNamespace() === NS_MAIN) { # User forgot to add 'User:'******'page', Title::makeTitleSafe(NS_USER, $opts->getValue('page'))); } } $this->show($opts, $qc); }
/** * Gets wikis an IP address might have edits on * * @author Daniel Grunwell (Grunny) * @param String $ipAddress The IP address to lookup */ public static function lookupIPActivity($ipAddress) { global $wgDevelEnvironment, $wgSpecialsDB; wfProfileIn(__METHOD__); if (empty($ipAddress) || !IP::isIPAddress($ipAddress)) { wfProfileOut(__METHOD__); return false; } $result = []; $ipLong = ip2long($ipAddress); if (empty($wgDevelEnvironment)) { $dbr = wfGetDB(DB_SLAVE, [], $wgSpecialsDB); $res = $dbr->select(['multilookup'], ['ml_city_id'], ['ml_ip' => $ipLong], __METHOD__); foreach ($res as $row) { if (!in_array($row->ml_city_id, self::$excludedWikis)) { if (WikiFactory::isPublic($row->ml_city_id)) { $result[] = (int) $row->ml_city_id; } } } $dbr->freeResult($res); } else { // on devbox - set up the list manually $result = [165]; } wfProfileOut(__METHOD__); return $result; }
function showList() { global $wgOut, $wgScript; $errors = array(); // Validate search IP $ip = $this->mSearchIP; if (!IP::isIPAddress($ip) && strlen($ip)) { $errors[] = array('globalblocking-list-ipinvalid', $ip); $ip = ''; } $wgOut->addWikiMsg('globalblocking-list-intro'); // Build the search form $searchForm = ''; $searchForm .= Xml::openElement('fieldset') . Xml::element('legend', null, wfMsg('globalblocking-search-legend')); $searchForm .= Xml::openElement('form', array('method' => 'get', 'action' => $wgScript, 'name' => 'globalblocklist-search')); $searchForm .= Html::hidden('title', SpecialPage::getTitleFor('GlobalBlockList')->getPrefixedText()); if (is_array($errors) && count($errors) > 0) { $errorstr = ''; foreach ($errors as $error) { if (is_array($error)) { $msg = array_shift($error); } else { $msg = $error; $error = array(); } $errorstr .= Xml::tags('li', null, wfMsgExt($msg, array('parseinline'), $error)); } $wgOut->addWikiMsg('globalblocking-unblock-errors', count($errors)); $wgOut->addHTML(Xml::tags('ul', array('class' => 'error'), $errorstr)); } $fields = array(); $fields['globalblocking-search-ip'] = Xml::input('ip', 45, $ip); $searchForm .= Xml::buildForm($fields, 'globalblocking-search-submit'); $searchForm .= Xml::closeElement('form') . Xml::closeElement('fieldset'); $wgOut->addHTML($searchForm); // Build a list of blocks. $conds = array(); if (strlen($ip)) { list($range_start, $range_end) = IP::parseRange($ip); if ($range_start != $range_end) { // They searched for a range. Match that exact range only $conds = array('gb_address' => $ip); } else { // They searched for an IP. Match any range covering that IP $hex_ip = IP::toHex($ip); $ip_pattern = substr($hex_ip, 0, 4) . '%'; // Don't bother checking blocks out of this /16. $dbr = wfGetDB(DB_SLAVE); $conds = array('gb_range_end>=' . $dbr->addQuotes($hex_ip), 'gb_range_start<=' . $dbr->addQuotes($hex_ip), 'gb_range_start like ' . $dbr->addQuotes($ip_pattern), 'gb_expiry>' . $dbr->addQuotes($dbr->timestamp(wfTimestampNow()))); } } $pager = new GlobalBlockListPager($this, $conds); $body = $pager->getBody(); if ($body != '') { $wgOut->addHTML($pager->getNavigationBar() . Html::rawElement('ul', array(), $body) . $pager->getNavigationBar()); } else { $wgOut->wrapWikiMsg("<div class='mw-globalblocking-noresults'>\n\$1</div>\n", array('globalblocking-list-noresults')); } }
/** * constructor */ function wfSpecialLog($par = '') { global $wgRequest, $wgOut, $wgUser, $wgLogTypes; # Get parameters $parms = explode('/', $par = $par !== null ? $par : ''); $symsForAll = array('*', 'all'); if ($parms[0] != '' && (in_array($par, $wgLogTypes) || in_array($par, $symsForAll))) { $type = $par; $user = $wgRequest->getText('user'); } else { if (count($parms) == 2) { $type = $parms[0]; $user = $parms[1]; } else { $type = $wgRequest->getVal('type'); $user = $par != '' ? $par : $wgRequest->getText('user'); } } $title = $wgRequest->getText('page'); $pattern = $wgRequest->getBool('pattern'); $y = $wgRequest->getIntOrNull('year'); $m = $wgRequest->getIntOrNull('month'); $tagFilter = $wgRequest->getVal('tagfilter'); # Don't let the user get stuck with a certain date $skip = $wgRequest->getText('offset') || $wgRequest->getText('dir') == 'prev'; if ($skip) { $y = ''; $m = ''; } # Handle type-specific inputs $qc = array(); if ($type == 'suppress') { $offender = User::newFromName($wgRequest->getVal('offender'), false); if ($offender && $offender->getId() > 0) { $qc = array('ls_field' => 'target_author_id', 'ls_value' => $offender->getId()); } else { if ($offender && IP::isIPAddress($offender->getName())) { $qc = array('ls_field' => 'target_author_ip', 'ls_value' => $offender->getName()); } } } # Create a LogPager item to get the results and a LogEventsList item to format them... $loglist = new LogEventsList($wgUser->getSkin(), $wgOut, 0); $pager = new LogPager($loglist, $type, $user, $title, $pattern, $qc, $y, $m, $tagFilter); # Set title and add header $loglist->showHeader($pager->getType()); # Show form options $loglist->showOptions($pager->getType(), $pager->getUser(), $pager->getPage(), $pager->getPattern(), $pager->getYear(), $pager->getMonth(), $pager->getFilterParams(), $tagFilter); # Insert list $logBody = $pager->getBody(); if ($logBody) { $wgOut->addHTML($pager->getNavigationBar() . $loglist->beginLogEventsList() . $logBody . $loglist->endLogEventsList() . $pager->getNavigationBar()); } else { $wgOut->addWikiMsg('logempty'); } }
/** * @covers IP::isIPAddress */ public function testisIPAddress() { $this->assertTrue(IP::isIPAddress('::'), 'RFC 4291 IPv6 Unspecified Address'); $this->assertTrue(IP::isIPAddress('::1'), 'RFC 4291 IPv6 Loopback Address'); $this->assertTrue(IP::isIPAddress('74.24.52.13/20', 'IPv4 range')); $this->assertTrue(IP::isIPAddress('fc:100:a:d:1:e:ac:0/24'), 'IPv6 range'); $this->assertTrue(IP::isIPAddress('fc::100:a:d:1:e:ac/96'), 'IPv6 range with "::"'); $validIPs = array('fc:100::', 'fc:100:a:d:1:e:ac::', 'fc::100', '::fc:100:a:d:1:e:ac', '::fc', 'fc::100:a:d:1:e:ac', 'fc:100:a:d:1:e:ac:0', '124.24.52.13', '1.24.52.13'); foreach ($validIPs as $ip) { $this->assertTrue(IP::isIPAddress($ip), "{$ip} is a valid IP address"); } }
/** * Construct an IP address representation. * @param string $address The textual representation of an IP address or CIDR range. */ public function __construct($address) { // analyze address format $this->is_valid = IP::isIPAddress($address); if (!$this->is_valid) { return; } $this->is_ipv4 = IP::isIPv4($address); $this->is_ipv6 = !$this->is_ipv4 && IP::isIPv6($address); // analyze address range $this->is_range = IP::isValidBlock($address); $this->encoded_range = IP::parseRange($address); $this->range = array(IP::prettifyIP(IP::formatHex($this->encoded_range[self::START])), IP::prettifyIP(IP::formatHex($this->encoded_range[self::END]))); }
public function index() { wfProfileIn(__METHOD__); if (!$this->getUser()->isAllowed('coppatool')) { wfProfileOut(__METHOD__); $this->displayRestrictionError(); return false; } $this->specialPage->setHeaders(); $this->response->setTemplateEngine(WikiaResponse::TEMPLATE_ENGINE_MUSTACHE); $this->userName = trim($this->getVal('username', $this->getPar())); $this->isIP = false; $this->validUser = false; if (IP::isIPAddress($this->userName)) { $this->userName = IP::sanitizeIP($this->userName); $this->isIP = true; $this->validUser = true; } else { $userObj = User::newFromName($this->userName); if (!$userObj || $userObj->getId() === 0) { $this->validUser = false; } else { $this->userName = $userObj->getName(); $this->validUser = true; } } $this->userForm = $this->app->renderView('WikiaStyleGuideForm', 'index', ['form' => ['isInvalid' => $this->validUser || $this->userName === '' ? false : true, 'errorMsg' => $this->validUser || $this->userName === '' ? '' : $this->msg('coppatool-nosuchuser', $this->userName)->escaped(), 'inputs' => [['type' => 'text', 'name' => 'username', 'isRequired' => true, 'label' => $this->msg('coppatool-label-username')->escaped(), 'value' => Sanitizer::encodeAttribute($this->userName)], ['type' => 'submit', 'value' => $this->msg('coppatool-submit')->escaped()]], 'method' => 'GET', 'action' => $this->getTitle()->getLocalUrl()]]); if ($this->validUser) { $this->getOutput()->addModules('ext.coppaTool'); $this->buttons = []; $this->blankImgUrl = wfBlankImgUrl(); $this->formHeading = $this->msg('coppatool-form-header')->escaped(); if (!$this->isIP) { $this->buttons[] = ['buttonAction' => 'disable-account', 'buttonLink' => Html::element('a', ['href' => '#'], $this->msg('coppatool-disable')->escaped()), 'done' => $userObj->getGlobalFlag('disabled', false)]; $this->buttons[] = ['buttonAction' => 'blank-profile', 'buttonLink' => Html::element('a', ['href' => '#'], $this->msg('coppatool-blank-user-profile')->escaped())]; $this->buttons[] = ['buttonAction' => 'delete-userpages', 'buttonLink' => Html::element('a', ['href' => '#'], $this->msg('coppatool-delete-user-pages')->escaped())]; $this->buttons[] = ['buttonAction' => 'coppa-imagereview', 'buttonLink' => Linker::link(Title::newFromText('CoppaImageReview', NS_SPECIAL), $this->msg('coppatool-imagereview')->escaped(), ['target' => '_blank'], ['username' => $this->userName], ['known', 'noclasses'])]; } else { $this->buttons[] = ['buttonAction' => 'phalanx-ip', 'buttonLink' => Linker::link(Title::newFromText('Phalanx', NS_SPECIAL), $this->msg('coppatool-phalanx-ip')->escaped(), ['target' => '_blank'], ['type' => Phalanx::TYPE_USER, 'wpPhalanxCheckBlocker' => $this->userName, 'target' => $this->userName], ['known', 'noclasses'])]; $this->buttons[] = ['buttonAction' => 'rename-ip', 'buttonLink' => Html::element('a', ['href' => '#'], $this->msg('coppatool-rename-ip')->escaped())]; } } wfProfileOut(__METHOD__); }
public function execute($par) { global $wgRequest; $this->setHeaders(); $this->outputHeader(); $opts = new FormOptions(); $opts->add('type', ''); $opts->add('user', ''); $opts->add('page', ''); $opts->add('pattern', false); $opts->add('year', null, FormOptions::INTNULL); $opts->add('month', null, FormOptions::INTNULL); $opts->add('tagfilter', ''); $opts->add('offset', ''); $opts->add('dir', ''); $opts->add('offender', ''); // Set values $opts->fetchValuesFromRequest($wgRequest); if ($par) { $this->parseParams($opts, (string) $par); } # Don't let the user get stuck with a certain date if ($opts->getValue('offset') || $opts->getValue('dir') == 'prev') { $opts->setValue('year', ''); $opts->setValue('month', ''); } # Handle type-specific inputs $qc = array(); if ($opts->getValue('type') == 'suppress') { $offender = User::newFromName($opts->getValue('offender'), false); if ($offender && $offender->getId() > 0) { $qc = array('ls_field' => 'target_author_id', 'ls_value' => $offender->getId()); } elseif ($offender && IP::isIPAddress($offender->getName())) { $qc = array('ls_field' => 'target_author_ip', 'ls_value' => $offender->getName()); } } $this->show($opts, $qc); }
private function loadFromArray(array $restrictions) { static $validKeys = ['IPAddresses']; static $neededKeys = ['IPAddresses']; $keys = array_keys($restrictions); $invalidKeys = array_diff($keys, $validKeys); if ($invalidKeys) { throw new InvalidArgumentException('Array contains invalid keys: ' . implode(', ', $invalidKeys)); } $missingKeys = array_diff($neededKeys, $keys); if ($missingKeys) { throw new InvalidArgumentException('Array is missing required keys: ' . implode(', ', $missingKeys)); } if (!is_array($restrictions['IPAddresses'])) { throw new InvalidArgumentException('IPAddresses is not an array'); } foreach ($restrictions['IPAddresses'] as $ip) { if (!\IP::isIPAddress($ip)) { throw new InvalidArgumentException("Invalid IP address: {$ip}"); } } $this->ipAddresses = $restrictions['IPAddresses']; }
/** * not sure it should be tested with boolean false. hashar 20100924 * @covers IP::isIPAddress */ public function testisIPAddress() { $this->assertFalse(IP::isIPAddress(false), 'Boolean false is not an IP'); $this->assertFalse(IP::isIPAddress(true), 'Boolean true is not an IP'); $this->assertFalse(IP::isIPAddress(""), 'Empty string is not an IP'); $this->assertFalse(IP::isIPAddress('abc'), 'Garbage IP string'); $this->assertFalse(IP::isIPAddress(':'), 'Single ":" is not an IP'); $this->assertFalse(IP::isIPAddress('2001:0DB8::A:1::1'), 'IPv6 with a double :: occurence'); $this->assertFalse(IP::isIPAddress('2001:0DB8::A:1::'), 'IPv6 with a double :: occurence, last at end'); $this->assertFalse(IP::isIPAddress('::2001:0DB8::5:1'), 'IPv6 with a double :: occurence, firt at beginning'); $this->assertFalse(IP::isIPAddress('124.24.52'), 'IPv4 not enough quads'); $this->assertFalse(IP::isIPAddress('24.324.52.13'), 'IPv4 out of range'); $this->assertFalse(IP::isIPAddress('.24.52.13'), 'IPv4 starts with period'); $this->assertFalse(IP::isIPAddress('fc:100:300'), 'IPv6 with only 3 words'); $this->assertTrue(IP::isIPAddress('::'), 'RFC 4291 IPv6 Unspecified Address'); $this->assertTrue(IP::isIPAddress('::1'), 'RFC 4291 IPv6 Loopback Address'); $this->assertTrue(IP::isIPAddress('74.24.52.13/20', 'IPv4 range')); $this->assertTrue(IP::isIPAddress('fc:100:a:d:1:e:ac:0/24'), 'IPv6 range'); $this->assertTrue(IP::isIPAddress('fc::100:a:d:1:e:ac/96'), 'IPv6 range with "::"'); $validIPs = array('fc:100::', 'fc:100:a:d:1:e:ac::', 'fc::100', '::fc:100:a:d:1:e:ac', '::fc', 'fc::100:a:d:1:e:ac', 'fc:100:a:d:1:e:ac:0', '124.24.52.13', '1.24.52.13'); foreach ($validIPs as $ip) { $this->assertTrue(IP::isIPAddress($ip), "{$ip} is a valid IP address"); } }
function loadParameters() { global $wgAbuseFilterIsCentral; $request = $this->getRequest(); $this->mSearchUser = trim($request->getText('wpSearchUser')); if ($wgAbuseFilterIsCentral) { $this->mSearchWiki = $request->getText('wpSearchWiki'); } $u = User::newFromName($this->mSearchUser); if ($u) { $this->mSearchUser = $u->getName(); // Username normalisation } elseif (IP::isIPAddress($this->mSearchUser)) { // It's an IP $this->mSearchUser = IP::sanitizeIP($this->mSearchUser); } else { $this->mSearchUser = null; } $this->mSearchTitle = $request->getText('wpSearchTitle'); $this->mSearchFilter = null; if (self::canSeeDetails()) { $this->mSearchFilter = $request->getText('wpSearchFilter'); } }
/** * Locates the client IP within a given XFF string * @param string $xff * @return array( string, bool ) */ public static function getClientIPfromXFF($xff) { global $wgSquidServers, $wgSquidServersNoPurge; if (!$xff) { return array(null, false); } // Avoid annoyingly long xff hacks $xff = trim(substr($xff, 0, 255)); $client = null; $isSquidOnly = true; $trusted = true; // Check each IP, assuming they are separated by commas $ips = explode(',', $xff); foreach ($ips as $ip) { $ip = trim($ip); // If it is a valid IP, not a hash or such if (IP::isIPAddress($ip)) { # The first IP should be the client. # Start only from the first public IP. if (is_null($client)) { if (IP::isPublic($ip)) { $client = $ip; } } elseif (!in_array($ip, $wgSquidServers) && !in_array($ip, $wgSquidServersNoPurge)) { $isSquidOnly = false; break; } } } return array($client, $isSquidOnly); }
/** * Check if user is blocked on all wikis. * Do not use for actual edit permission checks! * This is intented for quick UI checks. * * @param $ip String IP address, uses current client if none given * @return Bool True if blocked, false otherwise */ public function isBlockedGlobally($ip = '') { if ($this->mBlockedGlobally !== null) { return $this->mBlockedGlobally; } // User is already an IP? if (IP::isIPAddress($this->getName())) { $ip = $this->getName(); } elseif (!$ip) { $ip = $this->getRequest()->getIP(); } $blocked = false; wfRunHooks('UserIsBlockedGlobally', array(&$this, $ip, &$blocked)); $this->mBlockedGlobally = (bool) $blocked; return $this->mBlockedGlobally; }
/** * Creates a message with the status * @param array $msg Message with the status * @param string $ip The IP address to be checked * @return boolean true */ public static function getTorBlockStatus( &$msg, $ip ) { // IP addresses can be blocked only // Fast return if IP is not an exit node if ( !IP::isIPAddress( $ip ) || !self::isExitNode( $ip ) ) { return true; } $msg[] = Html::rawElement( 'span', array( 'class' => 'mw-torblock-isexitnode' ), wfMsgExt( 'torblock-isexitnode', 'parseinline', $ip ) ); return true; }
function build_whitelist_srcdomain($gpid, $negation) { $ip = new IP(); $q = new mysql_squid_builder(); $sql = "SELECT pattern FROM webfilters_sqitems WHERE gpid={$gpid} AND enabled=1"; $results = $q->QUERY_SQL($sql); $exclam = null; if (!$q->ok) { writelogs("{$gpid} {$q->mysql_error}", __FUNCTION__, __FILE__, __LINE__); return false; } if (mysql_num_rows($results) == 0) { return false; } if ($negation == 1) { $exclam = "!"; } $f = array(); while ($ligne = mysql_fetch_assoc($results)) { $pattern = trim($ligne["pattern"]); if ($pattern == null) { return; } if ($ip->isIPAddress($pattern)) { $f[] = "\tif( hostIP {$exclam}== \"{$pattern}\") { return \"DIRECT\";}"; continue; } if (substr($pattern, 0, 1) == '.') { if (strpos($pattern, "*") > 0) { $f[] = "\tif( shExpMatch(host ,\"{$pattern}\") ) { return \"DIRECT\";}"; continue; } $f[] = "\tif( dnsDomainIs(host ,\"{$pattern}\") ){ return \"DIRECT\";}"; continue; } $f[] = "\tif( host {$exclam}== \"{$pattern}\") { return \"DIRECT\";}"; } return @implode("\n", $f); }
/** * Set the visibility for the revisions in this list. Logging and * transactions are done here. * * @param $params array Associative array of parameters. Members are: * value: The integer value to set the visibility to * comment: The log comment. * @return Status */ public function setVisibility($params) { $bitPars = $params['value']; $comment = $params['comment']; $this->res = false; $dbw = wfGetDB(DB_MASTER); $this->doQuery($dbw); $dbw->begin(__METHOD__); $status = Status::newGood(); $missing = array_flip($this->ids); $this->clearFileOps(); $idsForLog = array(); $authorIds = $authorIPs = array(); for ($this->reset(); $this->current(); $this->next()) { $item = $this->current(); unset($missing[$item->getId()]); $oldBits = $item->getBits(); // Build the actual new rev_deleted bitfield $newBits = SpecialRevisionDelete::extractBitfield($bitPars, $oldBits); if ($oldBits == $newBits) { $status->warning('revdelete-no-change', $item->formatDate(), $item->formatTime()); $status->failCount++; continue; } elseif ($oldBits == 0 && $newBits != 0) { $opType = 'hide'; } elseif ($oldBits != 0 && $newBits == 0) { $opType = 'show'; } else { $opType = 'modify'; } if ($item->isHideCurrentOp($newBits)) { // Cannot hide current version text $status->error('revdelete-hide-current', $item->formatDate(), $item->formatTime()); $status->failCount++; continue; } if (!$item->canView()) { // Cannot access this revision $msg = $opType == 'show' ? 'revdelete-show-no-access' : 'revdelete-modify-no-access'; $status->error($msg, $item->formatDate(), $item->formatTime()); $status->failCount++; continue; } // Cannot just "hide from Sysops" without hiding any fields if ($newBits == Revision::DELETED_RESTRICTED) { $status->warning('revdelete-only-restricted', $item->formatDate(), $item->formatTime()); $status->failCount++; continue; } // Update the revision $ok = $item->setBits($newBits); if ($ok) { $idsForLog[] = $item->getId(); $status->successCount++; if ($item->getAuthorId() > 0) { $authorIds[] = $item->getAuthorId(); } elseif (IP::isIPAddress($item->getAuthorName())) { $authorIPs[] = $item->getAuthorName(); } } else { $status->error('revdelete-concurrent-change', $item->formatDate(), $item->formatTime()); $status->failCount++; } } // Handle missing revisions foreach ($missing as $id => $unused) { $status->error('revdelete-modify-missing', $id); $status->failCount++; } if ($status->successCount == 0) { $status->ok = false; $dbw->rollback(__METHOD__); return $status; } // Save success count $successCount = $status->successCount; // Move files, if there are any $status->merge($this->doPreCommitUpdates()); if (!$status->isOK()) { // Fatal error, such as no configured archive directory $dbw->rollback(__METHOD__); return $status; } // Log it $this->updateLog(array('title' => $this->title, 'count' => $successCount, 'newBits' => $newBits, 'oldBits' => $oldBits, 'comment' => $comment, 'ids' => $idsForLog, 'authorIds' => $authorIds, 'authorIPs' => $authorIPs)); $dbw->commit(__METHOD__); // Clear caches $status->merge($this->doPostCommitUpdates()); return $status; }
private static function checkIPAddress($ip) { global $wgRequest; if ($ip) { if (!IP::isIPAddress($ip)) { throw new MWException("Attempt to write \"" . $ip . "\" as an IP address into recent changes"); } } else { $ip = $wgRequest->getIP(); if (!$ip) { $ip = ''; } } return $ip; }
/** * @param array $types * @return string */ private function getExtraInputs($types) { if (count($types) == 1) { if ($types[0] == 'suppress') { $offender = $this->getRequest()->getVal('offender'); $user = User::newFromName($offender, false); if (!$user || $user->getId() == 0 && !IP::isIPAddress($offender)) { $offender = ''; // Blank field if invalid } return Xml::inputLabel($this->msg('revdelete-offender')->text(), 'offender', 'mw-log-offender', 20, $offender); } else { // Allow extensions to add their own extra inputs $input = ''; Hooks::run('LogEventsListGetExtraInputs', array($types[0], $this, &$input)); return $input; } } return ''; }
public function execute() { $user = $this->getUser(); $errors = $this->getTitle()->getUserPermissionsErrors('abusefilter-log', $user); if (count($errors)) { $this->dieUsageMsg($errors[0]); return; } $params = $this->extractRequestParams(); $prop = array_flip($params['prop']); $fld_ids = isset($prop['ids']); $fld_filter = isset($prop['filter']); $fld_user = isset($prop['user']); $fld_ip = isset($prop['ip']); $fld_title = isset($prop['title']); $fld_action = isset($prop['action']); $fld_details = isset($prop['details']); $fld_result = isset($prop['result']); $fld_timestamp = isset($prop['timestamp']); $fld_hidden = isset($prop['hidden']); $fld_revid = isset($prop['revid']); if ($fld_ip && !$user->isAllowed('abusefilter-private')) { $this->dieUsage('You don\'t have permission to view IP addresses', 'permissiondenied'); } if ($fld_details && !$user->isAllowed('abusefilter-log-detail')) { $this->dieUsage('You don\'t have permission to view detailed abuse log entries', 'permissiondenied'); } // Match permissions for viewing events on private filters to SpecialAbuseLog (bug 42814) if ($params['filter'] && !(AbuseFilterView::canViewPrivate() || $user->isAllowed('abusefilter-log-private'))) { // A specific filter parameter is set but the user isn't allowed to view all filters if (!is_array($params['filter'])) { $params['filter'] = array($params['filter']); } foreach ($params['filter'] as $filter) { if (AbuseFilter::filterHidden($filter)) { $this->dieUsage('You don\'t have permission to view log entries for private filters', 'permissiondenied'); } } } $result = $this->getResult(); $this->addTables('abuse_filter_log'); $this->addFields('afl_timestamp'); $this->addFields('afl_rev_id'); $this->addFields('afl_deleted'); $this->addFields('afl_filter'); $this->addFieldsIf('afl_id', $fld_ids); $this->addFieldsIf('afl_user_text', $fld_user); $this->addFieldsIf('afl_ip', $fld_ip); $this->addFieldsIf(array('afl_namespace', 'afl_title'), $fld_title); $this->addFieldsIf('afl_action', $fld_action); $this->addFieldsIf('afl_var_dump', $fld_details); $this->addFieldsIf('afl_actions', $fld_result); if ($fld_filter) { $this->addTables('abuse_filter'); $this->addFields('af_public_comments'); $this->addJoinConds(array('abuse_filter' => array('LEFT JOIN', 'af_id=afl_filter'))); } $this->addOption('LIMIT', $params['limit'] + 1); $this->addWhereRange('afl_timestamp', $params['dir'], $params['start'], $params['end']); $db = $this->getDB(); $notDeletedCond = SpecialAbuseLog::getNotDeletedCond($db); if (isset($params['user'])) { $u = User::newFromName($params['user']); if ($u) { // Username normalisation $params['user'] = $u->getName(); $userId = $u->getId(); } elseif (IP::isIPAddress($params['user'])) { // It's an IP, sanitize it $params['user'] = IP::sanitizeIP($params['user']); $userId = 0; } if (isset($userId)) { // Only add the WHERE for user in case it's either a valid user (but not necessary an existing one) or an IP $this->addWhere(array('afl_user' => $userId, 'afl_user_text' => $params['user'])); } } $this->addWhereIf(array('afl_filter' => $params['filter']), isset($params['filter'])); $this->addWhereIf($notDeletedCond, !SpecialAbuseLog::canSeeHidden($user)); $title = $params['title']; if (!is_null($title)) { $titleObj = Title::newFromText($title); if (is_null($titleObj)) { $this->dieUsageMsg(array('invalidtitle', $title)); } $this->addWhereFld('afl_namespace', $titleObj->getNamespace()); $this->addWhereFld('afl_title', $titleObj->getDBkey()); } $res = $this->select(__METHOD__); $count = 0; foreach ($res as $row) { if (++$count > $params['limit']) { // We've had enough $ts = new MWTimestamp($row->afl_timestamp); $this->setContinueEnumParameter('start', $ts->getTimestamp(TS_ISO_8601)); break; } if (SpecialAbuseLog::isHidden($row) && !SpecialAbuseLog::canSeeHidden($user)) { continue; } $canSeeDetails = SpecialAbuseLog::canSeeDetails($row->afl_filter); $entry = array(); if ($fld_ids) { $entry['id'] = intval($row->afl_id); $entry['filter_id'] = ''; if ($canSeeDetails) { $entry['filter_id'] = $row->afl_filter; } } if ($fld_filter) { $entry['filter'] = $row->af_public_comments; } if ($fld_user) { $entry['user'] = $row->afl_user_text; } if ($fld_ip) { $entry['ip'] = $row->afl_ip; } if ($fld_title) { $title = Title::makeTitle($row->afl_namespace, $row->afl_title); ApiQueryBase::addTitleInfo($entry, $title); } if ($fld_action) { $entry['action'] = $row->afl_action; } if ($fld_result) { $entry['result'] = $row->afl_actions; } if ($fld_revid && !is_null($row->afl_rev_id)) { $entry['revid'] = ''; if ($canSeeDetails) { $entry['revid'] = $row->afl_rev_id; } } if ($fld_timestamp) { $ts = new MWTimestamp($row->afl_timestamp); $entry['timestamp'] = $ts->getTimestamp(TS_ISO_8601); } if ($fld_details) { $entry['details'] = array(); if ($canSeeDetails) { $vars = AbuseFilter::loadVarDump($row->afl_var_dump); if ($vars instanceof AbuseFilterVariableHolder) { $entry['details'] = $vars->exportAllVars(); } else { $entry['details'] = array_change_key_case($vars, CASE_LOWER); } } } if ($fld_hidden) { $val = SpecialAbuseLog::isHidden($row); if ($val) { $entry['hidden'] = $val; } } if ($entry) { $fit = $result->addValue(array('query', $this->getModuleName()), null, $entry); if (!$fit) { $ts = new MWTimestamp($row->afl_timestamp); $this->setContinueEnumParameter('start', $ts->getTimestamp(TS_ISO_8601)); break; } } } $result->setIndexedTagName_internal(array('query', $this->getModuleName()), 'item'); }
/** * @param $types * @return string */ private function getExtraInputs($types) { $offender = $this->getRequest()->getVal('offender'); $user = User::newFromName($offender, false); if (!$user || $user->getId() == 0 && !IP::isIPAddress($offender)) { $offender = ''; // Blank field if invalid } if (count($types) == 1 && $types[0] == 'suppress') { return Xml::inputLabel($this->msg('revdelete-offender')->text(), 'offender', 'mw-log-offender', 20, $offender); } return ''; }
/** * Processes specific local wiki database and makes all needed changes for an IP address * * Important: should only be run within maintenace script (bound to specified wiki) */ public function updateLocalIP() { global $wgCityId, $wgUser; wfProfileIn(__METHOD__); if ($this->mUserId !== 0 || !IP::isIPAddress($this->mOldUsername) || !IP::isIPAddress($this->mNewUsername)) { $this->addError(wfMessage('userrenametool-error-invalid-ip')->escaped()); wfProfileOut(__METHOD__); return; } $wgOldUser = $wgUser; $wgUser = User::newFromName('Wikia'); $cityDb = WikiFactory::IDtoDB($wgCityId); $this->addLog("Processing wiki database: {$cityDb}."); $dbw = wfGetDB(DB_MASTER); $dbw->begin(); $tasks = self::$mLocalIpDefaults; $hookName = 'UserRename::LocalIP'; $this->addLog("Broadcasting hook: {$hookName}"); wfRunHooks($hookName, [$dbw, $this->mUserId, $this->mOldUsername, $this->mNewUsername, $this, $wgCityId, &$tasks]); foreach ($tasks as $task) { $this->addLog("Updating wiki \"{$cityDb}\": {$task['table']}:{$task['username_column']}"); $this->renameInTable($dbw, $task['table'], $this->mUserId, $this->mOldUsername, $this->mNewUsername, $task); } $hookName = 'UserRename::AfterLocalIP'; $this->addLog("Broadcasting hook: {$hookName}"); wfRunHooks($hookName, [$dbw, $this->mUserId, $this->mOldUsername, $this->mNewUsername, $this, $wgCityId, &$tasks]); $dbw->commit(); $this->addLog("Finished updating wiki database: {$cityDb}"); $this->addMainLog("log", RenameUserLogFormatter::wiki($this->mRequestorName, $this->mOldUsername, $this->mNewUsername, $wgCityId, $this->mReason, !empty($this->warnings) || !empty($this->errors))); $wgUser = $wgOldUser; wfProfileOut(__METHOD__); }
function UFDGUARD_UNLOCKED($url) { if (trim($url) == null) { if ($GLOBALS["DEBUG_UNLOCK"]) { WLOG("UFDGUARD_UNLOCKED::URL is null"); return false; } } if (strpos(" {$url}", "127.0.0.1 00:00:00:00:00:00") > 0) { return false; } if ($GLOBALS["DEBUG_UNLOCK"]) { WLOG("UFDGUARD_UNLOCKED::Call api_mysql_COUNT_ROWS"); } if (api_mysql_COUNT_ROWS("ufdbunlock") == 0) { return false; } $values = explode(" ", $url); $IPADDR = $values[0]; $MAC = $values[1]; $XFORWARD = $values[2]; $WWW = $values[3]; $IPADDR = str_replace("%25", "-", $IPADDR); $MAC = str_replace("%25", "-", $MAC); $XFORWARD = str_replace("%25", "-", $XFORWARD); if ($XFORWARD == "-") { $XFORWARD = null; } if ($MAC == "00:00:00:00:00:00") { $MAC = null; } if ($MAC == "-") { $MAC = null; } if ($GLOBALS["DEBUG_UNLOCK"]) { WLOG("UFDGUARD_UNLOCKED::Call IPCalls"); } $IPCalls = new IP(); if ($IPCalls->isIPAddress($XFORWARD)) { $IPADDR = $XFORWARD; } if (preg_match("#(.+?):[0-9]+#", $WWW, $re)) { $WWW = $re[1]; } if (preg_match("#^www\\.(.+)#", $WWW, $re)) { $WWW = $re[1]; } if ($GLOBALS["DEBUG_UNLOCK"]) { WLOG("UFDGUARD_UNLOCKED::{$WWW}"); } $WWW = api_GetFamilySites($WWW); if ($GLOBALS["DEBUG_UNLOCK"]) { WLOG("api_GetFamilySites::{$WWW}"); } if (!isset($GLOBALS["ufdbunlock_c"])) { $GLOBALS["ufdbunlock_c"] = 0; } if ($GLOBALS["ufdbunlock_c"] > 90) { QUERY_MYSQL("DELETE FROM ufdbunlock WHERE `finaltime` <" . time()); //if(!$q->ok){WLOG("$q->mysql_error");} $GLOBALS["ufdbunlock_c"] = 0; } if ($MAC != null) { if ($GLOBALS["DEBUG_UNLOCK"]) { WLOG("SELECT md5,finaltime FROM ufdbunlock WHERE `www`='{$WWW}' AND MAC='{$MAC}'"); } $ligne = mysql_fetch_array(QUERY_MYSQL("SELECT md5,finaltime FROM ufdbunlock WHERE `www`='{$WWW}' AND MAC='{$MAC}'")); if ($ligne["md5"] != null) { if ($ligne["finaltime"] < time()) { return false; } if ($IPADDR != null) { QUERY_MYSQL("UPDATE ufdbunlock SET ipaddr='{$IPADDR}' WHERE MAC='{$MAC}'"); } return true; } } if ($IPADDR != null) { if ($GLOBALS["DEBUG_UNLOCK"]) { WLOG("SELECT md5,finaltime FROM ufdbunlock WHERE `www`='{$WWW}' AND ipaddr='{$IPADDR}'"); } $ligne = mysql_fetch_array(QUERY_MYSQL("SELECT md5,finaltime FROM ufdbunlock WHERE `www`='{$WWW}' AND ipaddr='{$IPADDR}'")); $time = time(); if ($ligne["md5"] != null) { if ($ligne["finaltime"] < time()) { WLOG("{$ligne["finaltime"]} < {$time} -> FALSE"); return false; } if ($MAC != null) { QUERY_MYSQL("UPDATE ufdbunlock SET MAC='{$MAC}' WHERE ipaddr='{$IPADDR}'"); } return true; } } }
/** * Block a list of selected users * @param array $users * @param string $reason * @param string $tag replaces user pages * @param string $talkTag replaces user talk pages * @returns array, list of html-safe usernames */ public static function doMassUserBlock($users, $reason = '', $tag = '', $talkTag = '') { global $wgUser; $counter = $blockSize = 0; $safeUsers = array(); $log = new LogPage('block'); foreach ($users as $name) { # Enforce limits $counter++; $blockSize++; # Lets not go *too* fast if ($blockSize >= 20) { $blockSize = 0; wfWaitForSlaves(5); } $u = User::newFromName($name, false); // If user doesn't exist, it ought to be an IP then if (is_null($u) || !$u->getId() && !IP::isIPAddress($u->getName())) { continue; } $userTitle = $u->getUserPage(); $userTalkTitle = $u->getTalkPage(); $userpage = new Article($userTitle); $usertalk = new Article($userTalkTitle); $safeUsers[] = '[[' . $userTitle->getPrefixedText() . '|' . $userTitle->getText() . ']]'; $expirestr = $u->getId() ? 'indefinite' : '1 week'; $expiry = Block::parseExpiryInput($expirestr); $anonOnly = IP::isIPAddress($u->getName()) ? 1 : 0; // Create the block $block = new Block($u->getName(), $u->getId(), $wgUser->getId(), $reason, wfTimestampNow(), 0, $expiry, $anonOnly, 1, 1, 0, 0); $oldblock = Block::newFromDB($u->getName(), $u->getId()); if (!$oldblock) { $block->insert(); # Prepare log parameters $logParams = array(); $logParams[] = $expirestr; if ($anonOnly) { $logParams[] = 'anononly'; } $logParams[] = 'nocreate'; # Add log entry $log->addEntry('block', $userTitle, $reason, $logParams); } # Tag userpage! (check length to avoid mistakes) if (strlen($tag) > 2) { $userpage->doEdit($tag, $reason, EDIT_MINOR); } if (strlen($talkTag) > 2) { $usertalk->doEdit($talkTag, $reason, EDIT_MINOR); } } return $safeUsers; }
protected function doDBUpdates() { $db = $this->getDB(DB_MASTER); if (!$db->tableExists('log_search')) { $this->error("log_search does not exist"); return false; } $start = $db->selectField('logging', 'MIN(log_id)', false, __FUNCTION__); if (!$start) { $this->output("Nothing to do.\n"); return true; } $end = $db->selectField('logging', 'MAX(log_id)', false, __FUNCTION__); # Do remaining chunk $end += $this->mBatchSize - 1; $blockStart = $start; $blockEnd = $start + $this->mBatchSize - 1; $delTypes = array('delete', 'suppress'); // revisiondelete types while ($blockEnd <= $end) { $this->output("...doing log_id from {$blockStart} to {$blockEnd}\n"); $cond = "log_id BETWEEN {$blockStart} AND {$blockEnd}"; $res = $db->select('logging', '*', $cond, __FUNCTION__); foreach ($res as $row) { // RevisionDelete logs - revisions if (LogEventsList::typeAction($row, $delTypes, 'revision')) { $params = LogPage::extractParams($row->log_params); // Param format: <urlparam> <item CSV> [<ofield> <nfield>] if (count($params) < 2) { continue; // bad row? } $field = RevisionDeleter::getRelationType($params[0]); // B/C, the params may start with a title key (<title> <urlparam> <CSV>) if ($field == null) { array_shift($params); // remove title param $field = RevisionDeleter::getRelationType($params[0]); if ($field == null) { $this->output("Invalid param type for {$row->log_id}\n"); continue; // skip this row } else { // Clean up the row... $db->update('logging', array('log_params' => implode(',', $params)), array('log_id' => $row->log_id)); } } $items = explode(',', $params[1]); $log = new LogPage($row->log_type); // Add item relations... $log->addRelations($field, $items, $row->log_id); // Determine what table to query... $prefix = substr($field, 0, strpos($field, '_')); // db prefix if (!isset(self::$tableMap[$prefix])) { continue; // bad row? } $table = self::$tableMap[$prefix]; $userField = $prefix . '_user'; $userTextField = $prefix . '_user_text'; // Add item author relations... $userIds = $userIPs = array(); $sres = $db->select($table, array($userField, $userTextField), array($field => $items)); foreach ($sres as $srow) { if ($srow->{$userField} > 0) { $userIds[] = intval($srow->{$userField}); } elseif ($srow->{$userTextField} != '') { $userIPs[] = $srow->{$userTextField}; } } // Add item author relations... $log->addRelations('target_author_id', $userIds, $row->log_id); $log->addRelations('target_author_ip', $userIPs, $row->log_id); } elseif (LogEventsList::typeAction($row, $delTypes, 'event')) { // RevisionDelete logs - log events $params = LogPage::extractParams($row->log_params); // Param format: <item CSV> [<ofield> <nfield>] if (count($params) < 1) { continue; // bad row } $items = explode(',', $params[0]); $log = new LogPage($row->log_type); // Add item relations... $log->addRelations('log_id', $items, $row->log_id); // Add item author relations... $userIds = $userIPs = array(); $sres = $db->select('logging', array('log_user', 'log_user_text'), array('log_id' => $items)); foreach ($sres as $srow) { if ($srow->log_user > 0) { $userIds[] = intval($srow->log_user); } elseif (IP::isIPAddress($srow->log_user_text)) { $userIPs[] = $srow->log_user_text; } } $log->addRelations('target_author_id', $userIds, $row->log_id); $log->addRelations('target_author_ip', $userIPs, $row->log_id); } } $blockStart += $this->mBatchSize; $blockEnd += $this->mBatchSize; wfWaitForSlaves(); } $this->output("Done populating log_search table.\n"); return true; }
/** * @param $thread Thread */ function threadInfoPanel($thread) { global $wgLang; $infoElements = array(); // Check for edited flag. $editedFlag = $thread->editedness(); $ebLookup = array(Threads::EDITED_BY_AUTHOR => 'author', Threads::EDITED_BY_OTHERS => 'others'); $lastEdit = $thread->root()->getTimestamp(); $lastEditTime = $wgLang->time($lastEdit, false, true, true); $lastEditDate = $wgLang->date($lastEdit, false, true, true); $lastEdit = $wgLang->timeanddate($lastEdit, true); $editors = ''; $editorCount = 0; if ($editedFlag > Threads::EDITED_BY_AUTHOR) { $editors = $thread->editors(); $editorCount = count($editors); $formattedEditors = array(); foreach ($editors as $ed) { $id = IP::isIPAddress($ed) ? 0 : 1; $fEditor = Linker::userLink($id, $ed) . Linker::userToolLinks($id, $ed); $formattedEditors[] = $fEditor; } $editors = $wgLang->commaList($formattedEditors); } if (isset($ebLookup[$editedFlag])) { $editedBy = $ebLookup[$editedFlag]; // Used messages: lqt-thread-edited-author, lqt-thread-edited-others $editedNotice = wfMessage("lqt-thread-edited-{$editedBy}")->params($lastEdit)->numParams($editorCount)->params($lastEditTime, $lastEditDate)->parse(); $editedNotice = str_replace('$3', $editors, $editedNotice); $infoElements[] = Xml::tags('div', array('class' => "lqt-thread-toolbar-edited-{$editedBy}"), $editedNotice); } Hooks::run('LiquidThreadsThreadInfoPanel', array($thread, &$infoElements)); if (!count($infoElements)) { return ''; } return Xml::tags('div', array('class' => 'lqt-thread-info-panel'), implode("\n", $infoElements)); }
/** * Links to different places. * @param $userpage Title: Target user page * @param $talkpage Title: Talk page * @param $target User: Target user object * @return array */ public function getUserLinks(Title $userpage, Title $talkpage, User $target) { $id = $target->getId(); $username = $target->getName(); $tools[] = Linker::link($talkpage, $this->msg('sp-contributions-talk')->escaped()); if ($id !== null || $id === null && IP::isIPAddress($username)) { if ($this->getUser()->isAllowed('block')) { # Block / Change block / Unblock links if ($target->isBlocked()) { $tools[] = Linker::linkKnown(SpecialPage::getTitleFor('Block', $username), $this->msg('change-blocklink')->escaped()); $tools[] = Linker::linkKnown(SpecialPage::getTitleFor('Unblock', $username), $this->msg('unblocklink')->escaped()); } else { # User is not blocked $tools[] = Linker::linkKnown(SpecialPage::getTitleFor('Block', $username), $this->msg('blocklink')->escaped()); } } # Block log link $tools[] = Linker::linkKnown(SpecialPage::getTitleFor('Log', 'block'), $this->msg('sp-contributions-blocklog')->escaped(), array(), array('page' => $userpage->getPrefixedText())); } # Uploads $tools[] = Linker::linkKnown(SpecialPage::getTitleFor('Listfiles', $username), $this->msg('sp-contributions-uploads')->escaped()); # Other logs link $tools[] = Linker::linkKnown(SpecialPage::getTitleFor('Log', $username), $this->msg('sp-contributions-logs')->escaped()); # Add link to deleted user contributions for priviledged users if ($this->getUser()->isAllowed('deletedhistory')) { $tools[] = Linker::linkKnown(SpecialPage::getTitleFor('DeletedContributions', $username), $this->msg('sp-contributions-deleted')->escaped()); } # Add a link to change user rights for privileged users $userrightsPage = new UserrightsPage(); $userrightsPage->setContext($this->getContext()); if ($userrightsPage->userCanChangeRights($target)) { $tools[] = Linker::linkKnown(SpecialPage::getTitleFor('Userrights', $username), $this->msg('sp-contributions-userrights')->escaped()); } wfRunHooks('ContributionsToolLinks', array($id, $userpage, &$tools)); return $tools; }
/** * For backwards compatibility: Get the user object belonging to a certain name * in case a user name is given as argument. Nowadays user objects are passed * directly but many old log entries rely on this. * * @param $user string|User * @return User */ static function getUserObject($user) { if ($user instanceof User) { $username = $user->getName(); } else { $username = $user; if (isset(self::$userCache[$username])) { return self::$userCache[$username]; } wfDebug("Couldn't find user {$username} in cache\n"); } if (count(self::$userCache) > 1000) { self::$userCache = array(); } if ($user instanceof User) { $userCache[$username] = $user; return $user; } if (IP::isIPAddress($username)) { $u = new User(); $u->setName($username); self::$userCache[$username] = $u; return $u; } $user = User::newFromName($username); $user->load(); self::$userCache[$username] = $user; return $user; }
public function renameIPAddress() { wfProfileIn(__METHOD__); if (!$this->checkRequest()) { wfProfileOut(__METHOD__); return; } $ipAddr = $this->request->getVal('user'); if (!IP::isIPAddress($ipAddr)) { $this->response->setVal('success', false); $this->response->setVal('errorMsg', wfMessage('coppatool-invalid-ip')->plain()); wfProfileOut(__METHOD__); return; } $ipAddr = IP::sanitizeIP($ipAddr); $newIpAddr = '0.0.0.0'; $wikiIDs = RenameUserHelper::lookupIPActivity($ipAddr); $taskParams = ['requestor_id' => $this->wg->User->getID(), 'requestor_name' => $this->wg->User->getName(), 'rename_user_id' => 0, 'rename_old_name' => $ipAddr, 'rename_new_name' => $newIpAddr, 'rename_ip' => true, 'notify_renamed' => false, 'reason' => wfMessage('coppatool-reason')->plain()]; $task = (new UserRenameTask())->setPriority(\Wikia\Tasks\Queues\PriorityQueue::NAME); $task->call('renameUser', $wikiIDs, $taskParams); $taskID = $task->queue(); $this->response->setVal('success', true); $this->response->setVal('resultMsg', wfMessage('coppatool-rename-ip-success', $taskID)->plain()); wfProfileOut(__METHOD__); }