function wfLinkOpenIDViewHeader($article) { global $wgOut; /* We only care about the main page of any user */ $nt = $article->getTitle(); if ($nt && $nt->getNamespace() == NS_USER && strpos($nt->getText(), '/') === false) { $user = User::newFromName($nt->getText()); if ($user && $user->getID() != 0) { $openid = $user->getOption('wflinkopenid_openid'); if ($openid != '') { $v1url = $user->getOption('wflinkopenid_v1url'); $v2url = $user->getOption('wflinkopenid_v2url'); $xrdsurl = $user->getOption('wflinkopenid_xrdsurl'); if ($v1url != '') { $wgOut->addLink(array('rel' => 'openid.server', 'href' => $v1url)); $wgOut->addLink(array('rel' => 'openid.delegate', 'href' => $openid)); } if ($v2url != '') { $wgOut->addLink(array('rel' => 'openid2.provider', 'href' => $v2url)); $wgOut->addLink(array('rel' => 'openid2.local_id', 'href' => $openid)); } if ($xrdsurl != '') { $wgOut->addMeta('X-XRDS-Location', $xrdsurl); } } } } return TRUE; }
public function execute() { global $wgUser; $wgUser = User::newFromName('Maintenance script'); RequestContext::getMain()->setUser($wgUser); $dbr = CentralAuthUser::getCentralSlaveDB(); if ($this->getOption('fix', false) !== false) { $this->fix = true; } if ($this->getOption('safe-migrate', false) !== false) { $this->safe = true; $this->migrate = true; } if ($this->getOption('migrate', false) !== false) { $this->migrate = true; } if ($this->getOption('suppressrc', false) !== false) { $this->suppressRC = true; } $end = $dbr->selectField('globaluser', 'MAX(gu_id)'); for ($cur = 0; $cur <= $end; $cur += $this->mBatchSize) { $this->output("PROGRESS: {$cur} / {$end}\n"); $result = $dbr->select(array('globaluser', 'localuser'), array('gu_name'), array('lu_name' => null, "gu_id >= {$cur}", 'gu_id < ' . ($cur + $this->mBatchSize)), __METHOD__, array('ORDER BY' => 'gu_id'), array('localuser' => array('LEFT JOIN', 'gu_name=lu_name'))); foreach ($result as $row) { $this->process($row->gu_name); } if ($this->fix) { CentralAuthUser::waitForSlaves(); } } $this->output("done.\n"); }
function addDBData() { $this->tablesUsed[] = 'logging'; $this->tablesUsed[] = 'user'; try { $user1 = User::newFromName('BackupDumperLogUserA'); $this->userId1 = $user1->getId(); if ($this->userId1 === 0) { $user1->addToDatabase(); $this->userId1 = $user1->getId(); } $this->assertGreaterThan(0, $this->userId1); $user2 = User::newFromName('BackupDumperLogUserB'); $this->userId2 = $user2->getId(); if ($this->userId2 === 0) { $user2->addToDatabase(); $this->userId2 = $user2->getId(); } $this->assertGreaterThan(0, $this->userId2); $this->logId1 = $this->addLogEntry('type', 'subtype', $user1, NS_MAIN, "PageA"); $this->assertGreaterThan(0, $this->logId1); $this->logId2 = $this->addLogEntry('supress', 'delete', $user2, NS_TALK, "PageB", "SomeComment"); $this->assertGreaterThan(0, $this->logId2); $this->logId3 = $this->addLogEntry('move', 'delete', $user2, NS_MAIN, "PageA", "SomeOtherComment", array('key1' => 1, 3 => 'value3')); $this->assertGreaterThan(0, $this->logId3); } catch (Exception $e) { // We'd love to pass $e directly. However, ... see // documentation of exceptionFromAddDBData in // DumpTestCase $this->exceptionFromAddDBData = $e; } }
protected function getMessageParameters() { $params = parent::getMessageParameters(); $title = $this->entry->getTarget(); if (substr($title->getText(), 0, 1) === '#') { // autoblock - no user link possible $params[2] = $title->getText(); $params[3] = ''; // no user name for gender use } else { // Create a user link for the blocked $username = $title->getText(); // @todo Store the user identifier in the parameters // to make this faster for future log entries $targetUser = User::newFromName($username, false); $params[2] = Message::rawParam($this->makeUserLink($targetUser, Linker::TOOL_LINKS_NOBLOCK)); $params[3] = $username; // plain user name for gender use } $subtype = $this->entry->getSubtype(); if ($subtype === 'block' || $subtype === 'reblock') { if (!isset($params[4])) { // Very old log entry without duration: means infinite $params[4] = 'infinite'; } // Localize the duration, and add a tooltip // in English to help visitors from other wikis. // The lrm is needed to make sure that the number // is shown on the correct side of the tooltip text. $durationTooltip = '‎' . htmlspecialchars($params[4]); $params[4] = Message::rawParam("<span class='blockExpiry' title='{$durationTooltip}'>" . $this->context->getLanguage()->translateBlockExpiry($params[4]) . '</span>'); $params[5] = isset($params[5]) ? self::formatBlockFlags($params[5], $this->context->getLanguage()) : ''; } return $params; }
/** * @covers RequestContext::importScopedSession */ public function testImportScopedSession() { $context = RequestContext::getMain(); $oInfo = $context->exportSession(); $this->assertEquals('127.0.0.1', $oInfo['ip'], "Correct initial IP address."); $this->assertEquals(0, $oInfo['userId'], "Correct initial user ID."); $user = User::newFromName('UnitTestContextUser'); $user->addToDatabase(); $sinfo = array('sessionId' => 'd612ee607c87e749ef14da4983a702cd', 'userId' => $user->getId(), 'ip' => '192.0.2.0', 'headers' => array('USER-AGENT' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0')); // importScopedSession() sets these variables $this->setMwGlobals(array('wgUser' => new User(), 'wgRequest' => new FauxRequest())); $sc = RequestContext::importScopedSession($sinfo); // load new context $info = $context->exportSession(); $this->assertEquals($sinfo['ip'], $info['ip'], "Correct IP address."); $this->assertEquals($sinfo['headers'], $info['headers'], "Correct headers."); $this->assertEquals($sinfo['sessionId'], $info['sessionId'], "Correct session ID."); $this->assertEquals($sinfo['userId'], $info['userId'], "Correct user ID."); $this->assertEquals($sinfo['ip'], $context->getRequest()->getIP(), "Correct context IP address."); $this->assertEquals($sinfo['headers'], $context->getRequest()->getAllHeaders(), "Correct context headers."); $this->assertEquals($sinfo['sessionId'], session_id(), "Correct context session ID."); $this->assertEquals(true, $context->getUser()->isLoggedIn(), "Correct context user."); $this->assertEquals($sinfo['userId'], $context->getUser()->getId(), "Correct context user ID."); $this->assertEquals('UnitTestContextUser', $context->getUser()->getName(), "Correct context user name."); unset($sc); // restore previous context $info = $context->exportSession(); $this->assertEquals($oInfo['ip'], $info['ip'], "Correct restored IP address."); $this->assertEquals($oInfo['headers'], $info['headers'], "Correct restored headers."); $this->assertEquals($oInfo['sessionId'], $info['sessionId'], "Correct restored session ID."); $this->assertEquals($oInfo['userId'], $info['userId'], "Correct restored user ID."); }
/** * Show the special page * * @param $subpage Mixed: parameter passed to the page or null */ public function execute($subpage) { global $wgRequest, $wgUser, $wgOut; $this->setHeaders(); $hash_key = $wgRequest->getText('key', null); $email = $token = $timestamp = null; if (!empty($hash_key)) { #$hask_key = urldecode ( $hash_key ); $data = Wikia::verifyUserSecretKey($hash_key, 'sha256'); error_log("data = " . print_r($data, true)); if (!empty($data)) { $username = isset($data['user']) ? $data['user'] : null; $token = isset($data['token']) ? $data['token'] : null; $timestamp = isset($data['signature1']) ? $data['signature1'] : null; $oUser = User::newFromName($username); $email = $oUser->getEmail(); } } else { $email = $wgRequest->getText('email', null); $token = $wgRequest->getText('token', null); $timestamp = $wgRequest->getText('timestamp', null); } if ($email == null || $token == null || $timestamp == null) { #give up now, abandon all hope. $wgOut->addWikiMsg('unsubscribe-badaccess'); return; } #validate timestamp isnt spoiled (you only have 7 days) $timeCutoff = strtotime("7 days ago"); if ($timestamp <= $timeCutoff) { $wgOut->addWikiMsg('unsubscribe-badtime'); // $wgOut->addHTML("timestamp={$timestamp}\n"); #DEVL (remove before release) // $wgOut->addHTML("timeCutoff={$timeCutoff}\n"); #DEVL (remove before release) return; } #generate what the token SHOULD be $shouldToken = wfGenerateUnsubToken($email, $timestamp); if ($token != $shouldToken) { $wgOut->addWikiMsg('unsubscribe-badtoken'); // $wgOut->addHTML("shouldtoken={$shouldToken}\n"); #DEVL (remove before release) return; } #does the non-blank email they gave us look like an email? if (Sanitizer::validateEmail($email) == false) { #email wasnt blank, but didnt look like any email $wgOut->addWikiMsg('unsubscribe-bademail'); // $wgOut->addHTML("email={$email}\n"); #DEVL (remove before release) return; } #at this point, the 3 params check out. #is this their 2nd pass at this? $confirmed = $wgRequest->getBool('confirm', null); if ($wgRequest->wasPosted() && $confirmed) { #this is the 2nd round, they pushed the button, so do it $this->procUnsub($email); } else { #this is 1st pass, give them a button to push $this->showInfo($email, $token, $timestamp); } }
public function execute($par) { global $wgUser, $wgCommandLineMode, $wgLang, $wgOut, $wrAdminUserName; if (wfReadOnly()) { $wgOut->readOnlyPage(); return; } if ($wgUser->isLoggedIn()) { if ($wgUser->getName() == $wrAdminUserName) { $user = User::newFromName($par); } else { $user = $wgUser; } $msg = ''; if ($user->getID() > 0) { $user->setOption('enotifwatchlistpages', 0); $user->setOption('enotifusertalkpages', 0); $user->setOption('enotifminoredits', 0); $user->setOption('disablemail', 1); $user->saveSettings(); } else { $msg = $user->getName() . ' not found'; } $this->show($msg); } else { if (!$wgCommandLineMode && !isset($_COOKIE[session_name()])) { User::SetupSession(); } $request = new FauxRequest(array('returnto' => $wgLang->specialPage('Unsubscribe'))); require_once 'includes/SpecialUserlogin.php'; $form = new LoginForm($request); $form->mainLoginForm("You need to log in to unsubscribe<br/><br/>", ''); } }
function wfSpecialFavoritelist($argv, $parser) { global $wgUser, $wgOut, $wgLang, $wgRequest; global $wgRCShowFavoritingUsers, $wgEnotifFavoritelist, $wgShowUpdatedMarker; $output = ''; $skin = $wgUser->getSkin(); $specialTitle = SpecialPage::getTitleFor('Favoritelist'); //$wgOut->setRobotPolicy( 'noindex,nofollow' ); $this->mTitle = $parser->getTitle(); if ($this->mTitle->getNamespace() == NS_USER && array_key_exists('userpage', $argv) && $argv['userpage']) { $parts = explode('/', $this->mTitle->getText()); $rootPart = $parts[0]; $user = User::newFromName($rootPart, true); //echo "Userpage: $user"; $output = $this->viewFavList($user, $output, $wgRequest, $argv); $output .= $this->editlink($argv, $skin); return $output; } else { $user = $wgUser; } # Anons don't get a favoritelist if ($wgUser->isAnon()) { //$wgOut->setPageTitle( wfMsg( 'favoritenologin' ) ); $llink = $skin->linkKnown(SpecialPage::getTitleFor('Userlogin'), wfMsg('loginreqlink'), array(), array('returnto' => $specialTitle->getPrefixedText())); $output = wfMsgHtml('favoritelistanontext', $llink); return $output; } $output = $this->viewFavList($user, $output, $wgRequest, $argv); $output .= $this->editlink($argv, $skin); return $output; }
/** * Run a refreshLinks job * @return boolean success */ function run() { global $wgTitle, $wgUser, $wgLang, $wrGedcomExportDirectory; $wgTitle = $this->title; // FakeTitle (the default) generates errors when accessed, and sometimes I log wgTitle, so set it to something else $wgUser = User::newFromName('WeRelate agent'); // set the user $treeId = $this->params['tree_id']; $treeName = $this->params['name']; $treeUser = $this->params['user']; $filename = "{$wrGedcomExportDirectory}/{$treeId}.ged"; $ge = new GedcomExporter(); $error = $ge->exportGedcom($treeId, $filename); if ($error) { $this->error = $error; return false; } // leave a message for the tree requester $userTalkTitle = Title::newFromText($treeUser, NS_USER_TALK); $article = new Article($userTalkTitle, 0); if ($article->getID() != 0) { $text = $article->getContent(); } else { $text = ''; } $title = Title::makeTitle(NS_SPECIAL, 'Trees'); $msg = wfMsg('GedcomExportReady', $wgLang->date(wfTimestampNow(), true, false), $treeName, $title->getFullURL(wfArrayToCGI(array('action' => 'downloadExport', 'user' => $treeUser, 'name' => $treeName)))); $text .= "\n\n" . $msg; $success = $article->doEdit($text, 'GEDCOM export ready'); if (!$success) { $this->error = 'Unable to edit user talk page: ' . $treeUser; return false; } return true; }
function createPost($info, $subject, $super = null) { $userName = $info['user']; if (strpos($userName, '#') !== false) { $pos = strpos($userName, '#'); $userName = substr($userName, 0, $pos); } $user = User::newFromName($userName, false); if (!$user) { throw new MWException("Username " . $info['user'] . " is invalid."); } global $article; if ($super) { $title = Threads::newReplyTitle($super, $user); } else { $title = Threads::newThreadTitle($subject, $article); } print "Creating thread {$title} as a subthread of " . ($super ? $super->title() : 'none') . "\n"; $root = new Article($title); $root->doEdit($info['content'], 'Imported from JSON', EDIT_NEW, false, $user); $t = LqtView::postEditUpdates($super ? 'reply' : 'new', $super, $root, $article, $subject, 'Imported from JSON', null); $t = Threads::withId($t->id()); // Some weirdness. return $t; }
function ipAuthUserLoadAfterLoadFromSession($user) { global $wgIPAuthUsers; if ($user->isLoggedIn()) { return true; } $ip = wfGetIP(); if (isset($wgIPAuthUsers[$ip])) { $name = $wgIPAuthUsers[$ip]; $xuser = User::newFromName($name); if ($xuser->getID() == 0) { wfDebug("User {$name} assigned to IP {$ip} does not exist!\n"); } else { # HACK: force user data reload by assigning members directly $user->mId = $xuser->mId; $user->mName = $xuser->mName; $user->loadFromId(); wfDebug("User {$name} assigned to IP {$ip} logged in.\n"); if (!isset($_SESSION['wsUserID'])) { wfDebug("Setting up a session for {$name} assigned to IP {$ip} logged in.\n"); wfSetupSession(); $_SESSION['wsToken'] = "IP:{$ip}"; $_SESSION['wsUserName'] = $name; $user->setCookies(); } } } return true; }
public function executeIndex($params) { $page_owner = User::newFromName($this->wg->Title->getText()); if (!is_object($page_owner) || $page_owner->getId() == 0) { // do not show module if page owner does not exist or is an anonymous user return false; } // add CSS for this module $this->wg->Out->addStyle(AssetsManager::getInstance()->getSassCommonURL("skins/oasis/css/modules/FollowedPages.scss")); $showDeletedPages = isset($params['showDeletedPages']) ? (bool) $params['showDeletedPages'] : true; // get 6 followed pages $watchlist = FollowModel::getWatchList($page_owner->getId(), 0, 6, null, $showDeletedPages); $data = array(); // weird. why is this an array of one element? foreach ($watchlist as $unused_id => $item) { $pagelist = $item['data']; foreach ($pagelist as $page) { $data[] = $page; } } // only display your own page if ($page_owner->getId() == $this->wg->User->getId()) { $this->follow_all_link = Wikia::specialPageLink('Following', 'oasis-wikiafollowedpages-special-seeall', 'more'); } $this->data = $data; $this->max_followed_pages = min(self::MAX_FOLLOWED_PAGES, count($this->data)); }
public function execute() { $username = $this->getArg(0); $password = $this->getArg(1); $this->output(wfWikiID() . ": Creating and promoting User:{$username}..."); $user = User::newFromName($username); if (!is_object($user)) { $this->error("invalid username.", true); } elseif (0 != $user->idForName()) { $this->error("account exists.", true); } # Try to set the password try { $user->setPassword($password); } catch (PasswordError $pwe) { $this->error($pwe->getText(), true); } # Insert the account into the database $user->addToDatabase(); $user->saveSettings(); # Promote user if ($this->hasOption('sysop')) { $user->addGroup('sysop'); } if ($this->hasOption('bureaucrat')) { $user->addGroup('bureaucrat'); } # Increment site_stats.ss_users $ssu = new SiteStatsUpdate(0, 0, 0, 0, 1); $ssu->doUpdate(); $this->output("done.\n"); }
public function execute() { $userName = $this->getOption('u', 'Maintenance script'); $reason = $this->getOption('r', ''); $cascade = $this->hasOption('cascade'); $protection = "sysop"; if ($this->hasOption('semiprotect')) { $protection = "autoconfirmed"; } elseif ($this->hasOption('unprotect')) { $protection = ""; } $user = User::newFromName($userName); if (!$user) { $this->error("Invalid username", true); } // @todo FIXME: This is reset 7 lines down. $restrictions = array('edit' => $protection, 'move' => $protection); $t = Title::newFromText($this->getArg()); if (!$t) { $this->error("Invalid title", true); } $restrictions = array(); foreach ($t->getRestrictionTypes() as $type) { $restrictions[$type] = $protection; } # un/protect the article $this->output("Updating protection status... "); $page = WikiPage::factory($t); $status = $page->doUpdateRestrictions($restrictions, array(), $cascade, $reason, $user); if ($status->isOK()) { $this->output("done\n"); } else { $this->output("failed\n"); } }
public function __construct($username, $realname = 'Real Name', $email = '*****@*****.**', $groups = array()) { $this->assertNotReal(); $this->username = $username; $this->password = '******'; $this->user = User::newFromName($this->username); $this->user->load(); // In an ideal world we'd have a new wiki (or mock data store) for every single test. // But for now, we just need to create or update the user with the desired properties. // we particularly need the new password, since we just generated it randomly. // In core MediaWiki, there is no functionality to delete users, so this is the best we can do. if (!$this->user->isLoggedIn()) { // create the user $this->user = User::createNew($this->username, array("email" => $email, "real_name" => $realname)); if (!$this->user) { throw new MWException("Error creating TestUser " . $username); } } // Update the user to use the password and other details $change = $this->setPassword($this->password) || $this->setEmail($email) || $this->setRealName($realname); // Adjust groups by adding any missing ones and removing any extras $currentGroups = $this->user->getGroups(); foreach (array_diff($groups, $currentGroups) as $group) { $this->user->addGroup($group); } foreach (array_diff($currentGroups, $groups) as $group) { $this->user->removeGroup($group); } if ($change) { $this->user->saveSettings(); } }
/** * * @param string $name * @param int $amount * @return boolean false if failed */ private function credit($name = null, $amount = 0) { $output = $this->getOutput(); $output->addWikiText("=== Credit (name, amount) ==="); $output->addWikiText("name = {$name}"); $output->addWikiText("amount = {$amount}"); $user = User::newFromName($name); if (!$user || $user->getId() == 0) { $output->addWikiText("=== ERROR: Invalid UserName ==="); return false; } $output->addWikiText("=== User ==="); $output->addWikiText("user_id = " . $user->getId()); $output->addWikiText("user_name = " . $user->getName()); $output->addWikiText("user_realname = " . $user->getRealName()); $output->addWikiText("user_email = " . $user->getEmail()); $output->addWikiText("=== Transaction ==="); $output->addWikiText("True balance before = " . TMRecord::getTrueBalanceFromDB($user->getId())); if (!is_int($amount) || $amount <= 0 || $amount > 1000) { $output->addWikiText("=== ERROR: Invalid Amount ==="); return false; } $tmr = array('tmr_type' => TM_REFUND_TYPE, 'tmr_user_id' => $user->getId(), 'tmr_mail' => $user->getEmail(), 'tmr_ip' => IP::sanitizeIP(wfGetIP()), 'tmr_amount' => $amount, 'tmr_currency' => 'EUR', 'tmr_desc' => 'tm-refund', 'tmr_status' => 'OK'); wfRunHooks('CreateTransaction', array(&$tmr)); $output->addWikiText("==== DONE ===="); $output->addWikiText("True balance after = " . TMRecord::getTrueBalanceFromDB($user->getId())); $output->addWikiText("== SUCCESS =="); }
public function execute() { global $wgUser, $wgTitle, $wgArticle; $userName = $this->getOption('u', 'Maintenance script'); $reason = $this->getOption('r', ''); $protection = "sysop"; if ($this->hasOption('semiprotect')) { $protection = "autoconfirmed"; } elseif ($this->hasOption('unprotect')) { $protection = ""; } $wgUser = User::newFromName($userName); $restrictions = array('edit' => $protection, 'move' => $protection); $wgTitle = Title::newFromText($this->getArg()); if (!$wgTitle) { $this->error("Invalid title", true); } $wgArticle = new Article($wgTitle); # un/protect the article $this->output("Updating protection status... "); $success = $wgArticle->updateRestrictions($restrictions, $reason); if ($success) { $this->output("done\n"); } else { $this->output("failed\n"); } }
/** * @param $context ResourceLoaderContext * @return array */ protected function getPages(ResourceLoaderContext $context) { global $wgUser, $wgUseSiteJs, $wgUseSiteCss; $userName = $context->getUser(); if ($userName === null) { return array(); } if (!$wgUseSiteJs && !$wgUseSiteCss) { return array(); } // Use $wgUser is possible; allows to skip a lot of code if (is_object($wgUser) && $wgUser->getName() == $userName) { $user = $wgUser; } else { $user = User::newFromName($userName); if (!$user instanceof User) { return array(); } } $pages = array(); foreach ($user->getEffectiveGroups() as $group) { if (in_array($group, array('*', 'user'))) { continue; } if ($wgUseSiteJs) { $pages["MediaWiki:Group-{$group}.js"] = array('type' => 'script'); } if ($wgUseSiteCss) { $pages["MediaWiki:Group-{$group}.css"] = array('type' => 'style'); } } return $pages; }
/** * Render the special page * @param string|null $par Username to get uploads from */ public function executeWhenAvailable($par = '') { if (($par === '' || $par === null) && $this->getUser()->isAnon()) { // Anons don't get to see Special:Uploads $this->requireLogin('mobile-frontend-donate-image-anon'); } else { // uploads by a particular user, i.e Special:Uploads/username, are shown even to anons $this->setHeaders(); $output = $this->getOutput(); $output->addJsConfigVars('wgMFPhotoUploadEndpoint', $this->getMFConfig()->get('MFPhotoUploadEndpoint')); if ($par !== '' && $par !== null) { $user = User::newFromName($par); if (!$user || $user->isAnon()) { $output->setPageTitle($this->msg('mobile-frontend-donate-image-title-username', $par)); $output->setStatusCode(404); $html = MobileUI::contentElement(MobileUI::errorBox($this->msg('mobile-frontend-photo-upload-invalid-user', $par))); } else { if ($user->equals($this->getUser())) { $output->setPageTitle($this->msg('mobile-frontend-donate-image-title-you')); } else { $output->setPageTitle($this->msg('mobile-frontend-donate-image-title-username', $par)); } $html = $this->getUserUploadsPageHtml($user); } } else { $user = $this->getUser(); $output->setPageTitle($this->msg('mobile-frontend-donate-image-title-you')); // TODO: what if the user cannot upload to the destination wiki in $wgMFPhotoUploadEndpoint? $html = $this->getUserUploadsPageHtml($user); } $output->addHTML($html); } }
/** * genderCache should work with user objects, too * * @dataProvider dataUserName */ function testUserObjects($username, $expectedGender) { $genderCache = GenderCache::singleton(); $user = User::newFromName($username); $gender = $genderCache->getGenderOf($user); $this->assertEquals($gender, $expectedGender, "GenderCache normal"); }
function setupMicroID() { global $wgOut, $wgRequest, $wgHooks; $wgHooks['UserToggles'][] = 'MicroIDUserToggle'; $action = $wgRequest->getText('action', 'view'); if ($action == 'view') { $title = $wgRequest->getText('title'); if (!isset($title) || strlen($title) == 0) { # If there's no title, and Cache404 is in use, check using its stuff if (defined('CACHE404_VERSION')) { if ($_SERVER['REDIRECT_STATUS'] == 404) { $url = getRedirectUrl($_SERVER); if (isset($url)) { $title = cacheUrlToTitle($url); } } } else { $title = wfMsg('mainpage'); } } $nt = Title::newFromText($title); // If the page being viewed is a user page... if ($nt && $nt->getNamespace() == NS_USER && strpos($nt->getText(), '/') === false) { // If the user qualifies... wfDebug("MicroID: on User page " . $nt->getText() . "\n"); $user = User::newFromName($nt->getText()); if ($user && $user->getID() != 0 && $user->getEmail() && $user->isEmailConfirmed() && $user->getOption('microid')) { wfDebug("MicroID: on User page " . $nt->getText() . "\n"); $wgOut->addMeta('microid', MakeMicroID($user->getEmail(), $nt->getFullURL())); } } } }
public function execute() { global $wgUser; # Change to current working directory $oldCwd = getcwd(); chdir($oldCwd); # Options processing $user = $this->getOption('u', 'Delete page script'); $reason = $this->getOption('r', ''); $interval = $this->getOption('i', 0); if ($this->hasArg()) { $file = fopen($this->getArg(), 'r'); } else { $file = $this->getStdin(); } # Setup if (!$file) { $this->error("Unable to read file, exiting", true); } $wgUser = User::newFromName($user); $dbw = wfGetDB(DB_MASTER); # Handle each entry for ($linenum = 1; !feof($file); $linenum++) { $line = trim(fgets($file)); if ($line == '') { continue; } $page = Title::newFromText($line); if (is_null($page)) { $this->output("Invalid title '{$line}' on line {$linenum}\n"); continue; } if (!$page->exists()) { $this->output("Skipping nonexistent page '{$line}'\n"); continue; } $this->output($page->getPrefixedText()); $dbw->begin(); if ($page->getNamespace() == NS_FILE) { $art = new ImagePage($page); $img = wfFindFile($art->mTitle); if (!$img || !$img->isLocal() || !$img->delete($reason)) { $this->output(" FAILED to delete image file... "); } } else { $art = new Article($page); } $success = $art->doDeleteArticle($reason); $dbw->commit(); if ($success) { $this->output(" Deleted!\n"); } else { $this->output(" FAILED to delete article\n"); } if ($interval) { sleep($interval); } wfWaitForSlaves(); } }
/** * Render the special page boddy * @param string $par The username */ public function executeWhenAvailable($par = '') { $this->offset = $this->getRequest()->getVal('offset', false); if ($par) { // enter article history view $this->user = User::newFromName($par, false); if ($this->user && ($this->user->idForName() || User::isIP($par))) { // set page title as on desktop site - bug 66656 $username = $this->user->getName(); $out = $this->getOutput(); $out->addModuleStyles(array('mobile.pagelist.styles', 'mobile.pagesummary.styles')); $out->setHTMLTitle($this->msg('pagetitle', $this->msg('contributions-title', $username)->plain())->inContentLanguage()); if (User::isIP($par)) { $this->renderHeaderBar($par); } else { $this->renderHeaderBar($this->user->getUserPage()); } $res = $this->doQuery(); $out->addHtml(Html::openElement('div', array('class' => 'content-unstyled'))); $this->showContributions($res); $out->addHtml(Html::closeElement('div')); return; } } $this->showPageNotFound(); }
/** * Function check if user is blocked, return true * user blocked status is passed to $ret * @param $parser Parser * @param $varCache ?? * @param $index ?? * @param $ret string? * @return bool */ public static function parserGetVariable(&$parser, &$varCache, &$index, &$ret) { if ($index != 'USERBLOCKED') { return true; } $title = $parser->getTitle(); if ($title->getNamespace() != NS_USER && $title->getNamespace() != NS_USER_TALK) { $ret = 'unknown'; return true; } $user = User::newFromName($title->getBaseText()); if ($user instanceof User) { if (!$user->isBlocked()) { $ret = 'false'; return true; } // if user is blocked it's pretty much possible they will be unblocked one day :) // so we enable cache for shorter time only so that we can recheck later // if they weren't already unblocked - if there is a better way to do that, fix me $expiry = $user->getBlock()->mExpiry; if (is_numeric($expiry)) { // sometimes this is 'infinityinfinity'. in that case, use the default cache expiry time. $expiry = wfTimestamp(TS_UNIX, $expiry) - wfTimestamp(TS_UNIX); if ($expiry > 0) { // just to make sure $parser->getOutput()->updateCacheExpiry($expiry); } } $ret = 'true'; return true; } $ret = 'unknown'; return true; }
public function deleteUserPages() { wfProfileIn(__METHOD__); if (!$this->checkRequest()) { wfProfileOut(__METHOD__); return; } $user = $this->request->getVal('user'); if (empty($user)) { $this->response->setVal('success', false); $this->response->setVal('errorMsg', wfMessage('coppatool-invalid-user')->plain()); wfProfileOut(__METHOD__); return; } $userObj = User::newFromName($user); if (!$userObj instanceof User || $userObj->getId() === 0) { $this->response->setVal('success', false); $this->response->setVal('errorMsg', wfMessage('coppatool-invalid-user')->plain()); wfProfileOut(__METHOD__); return; } $taskParams = ['mode' => 'you', 'page' => 'User:'******'wikis' => '', 'range' => 'all', 'reason' => wfMessage('coppatool-delete-user-pages-reason')->plain(), 'lang' => '', 'cat' => 0, 'selwikia' => 0, 'edittoken' => $this->wg->User->getEditToken(), 'user' => $this->wg->User->getName(), 'admin' => $this->wg->User->getName(), 'suppress' => true]; $task = new \Wikia\Tasks\Tasks\MultiTask(); $task->call('delete', $taskParams); $batchDeleteTaskId = $task->queue(); $this->response->setVal('success', true); $this->response->setVal('resultMsg', wfMessage('coppatool-delete-user-pages-success', $batchDeleteTaskId)->plain()); wfProfileOut(__METHOD__); }
function efNoBogusUserpagesUserCan($title, $user, $action, &$result) { // If we're not in the user namespace, // or we're not trying to edit, // or the page already exists, // or we are allowed to create bogus userpages // then just let MediaWiki continue. if ($title->getNamespace() != NS_USER || $action != 'create' || $user->isAllowed('createbogususerpage')) { return true; } $userTitle = explode('/', $title->getText(), 2); $userName = $userTitle[0]; // Don't block the creation of IP userpages if the page is for a IPv4 or IPv6 page. if (User::isIP($userName)) { return true; } // Check if the user exists, if it says the user is anon, // but we know we're not on an ip page, then the user does not exist. // And therefore, we block creation. $user = User::newFromName($userName); if ($user->isAnon()) { $result = 'badaccess-bogususerpage'; return false; } return true; }
function __construct(IContextSource $context, $userName = null, $search = '', $including = false, $showAll = false) { $this->setContext($context); $this->mIncluding = $including; $this->mShowAll = $showAll; if ($userName !== null && $userName !== '') { $nt = Title::newFromText($userName, NS_USER); $user = User::newFromName($userName, false); if (!is_null($nt)) { $this->mUserName = $nt->getText(); } if (!$user || $user->isAnon() && !User::isIP($user->getName())) { $this->getOutput()->wrapWikiMsg("<div class=\"mw-userpage-userdoesnotexist error\">\n\$1\n</div>", array('listfiles-userdoesnotexist', wfEscapeWikiText($userName))); } } if ($search !== '' && !$this->getConfig()->get('MiserMode')) { $this->mSearch = $search; $nt = Title::newFromURL($this->mSearch); if ($nt) { $dbr = wfGetDB(DB_SLAVE); $this->mQueryConds[] = 'LOWER(img_name)' . $dbr->buildLike($dbr->anyString(), strtolower($nt->getDBkey()), $dbr->anyString()); } } if (!$including) { if ($this->getRequest()->getText('sort', 'img_date') == 'img_date') { $this->mDefaultDirection = IndexPager::DIR_DESCENDING; } else { $this->mDefaultDirection = IndexPager::DIR_ASCENDING; } } else { $this->mDefaultDirection = IndexPager::DIR_DESCENDING; } parent::__construct($context); }
public function execute() { global $wgUser; $this->output("Checking existence of old default messages..."); $dbr = $this->getDB(DB_REPLICA); $res = $dbr->select(['page', 'revision'], ['page_namespace', 'page_title'], ['page_namespace' => NS_MEDIAWIKI, 'page_latest=rev_id', 'rev_user_text' => 'MediaWiki default']); if ($dbr->numRows($res) == 0) { # No more messages left $this->output("done.\n"); return; } # Deletions will be made by $user temporarly added to the bot group # in order to hide it in RecentChanges. $user = User::newFromName('MediaWiki default'); if (!$user) { $this->error("Invalid username", true); } $user->addGroup('bot'); $wgUser = $user; # Handle deletion $this->output("\n...deleting old default messages (this may take a long time!)...", 'msg'); $dbw = $this->getDB(DB_MASTER); foreach ($res as $row) { wfWaitForSlaves(); $dbw->ping(); $title = Title::makeTitle($row->page_namespace, $row->page_title); $page = WikiPage::factory($title); $error = ''; // Passed by ref // FIXME: Deletion failures should be reported, not silently ignored. $page->doDeleteArticle('No longer required', false, 0, true, $error, $user); } $this->output("done!\n", 'msg'); }
protected function setUp() { parent::setUp(); $langObj = Language::factory('en'); $localZone = 'UTC'; $localOffset = date('Z') / 60; $this->setMwGlobals(array('wgMemc' => new EmptyBagOStuff(), 'wgContLang' => $langObj, 'wgLanguageCode' => 'en', 'wgLang' => $langObj, 'wgLocaltimezone' => $localZone, 'wgLocalTZoffset' => $localOffset, 'wgNamespaceProtection' => array(NS_MEDIAWIKI => 'editinterface'))); // Without this testUserBlock will use a non-English context on non-English MediaWiki // installations (because of how Title::checkUserBlock is implemented) and fail. RequestContext::resetMain(); $this->userName = '******'; $this->altUserName = '******'; date_default_timezone_set($localZone); $this->title = Title::makeTitle(NS_MAIN, "Main Page"); if (!isset($this->userUser) || !$this->userUser instanceof User) { $this->userUser = User::newFromName($this->userName); if (!$this->userUser->getID()) { $this->userUser = User::createNew($this->userName, array("email" => "*****@*****.**", "real_name" => "Test User")); $this->userUser->load(); } $this->altUser = User::newFromName($this->altUserName); if (!$this->altUser->getID()) { $this->altUser = User::createNew($this->altUserName, array("email" => "*****@*****.**", "real_name" => "Test User Alt")); $this->altUser->load(); } $this->anonUser = User::newFromId(0); $this->user = $this->userUser; } }
/** Handle 'login error' events here. */ private function handleLoginError(&$tmpl) { // Probabilistic logging. if (!$this->shouldLog()) { return true; } // If WikiAgent user doesn't exist, just bail out. // We won't be able to add a coherent log message anyway. $waUser = User::newFromName('WikiAgent'); if ($waUser->getId() == 0) { return true; } global $wgUser; $cId = $wgUser->getId(); if ($cId == 0) { $name = 'IP: ' . wfGetIP(); } else { $name = '[[User:'******']]'; } $message = wfMsgForContent('usrloglog-loginerr-text', $name, $tmpl->data['message']); // File under a title that can be easily policed. $title = Title::makeTitle(NS_SPECIAL, 'log/usrloglog'); // Hack to create a meaningful log entry. $wgUser->mId = $waUser->getId(); $log = new LogPage('usrloglog', false); $log->addEntry('loginerr', $title, $message); // 'undo' hack. $wgUser->mId = $cId; }