Ejemplo n.º 1
0
function wfSpecialRestrictUser($par = null)
{
    global $wgOut, $wgRequest;
    $user = $userOrig = null;
    if ($par) {
        $userOrig = $par;
    } elseif ($wgRequest->getVal('user')) {
        $userOrig = $wgRequest->getVal('user');
    } else {
        $wgOut->addHTML(RestrictUserForm::selectUserForm());
        return;
    }
    $isIP = User::isIP($userOrig);
    $user = $isIP ? $userOrig : User::getCanonicalName($userOrig);
    $uid = User::idFromName($user);
    if (!$uid && !$isIP) {
        $err = '<strong class="error">' . wfMsgHtml('restrictuser-notfound') . '</strong>';
        $wgOut->addHTML(RestrictUserForm::selectUserForm($userOrig, $err));
        return;
    }
    $wgOut->addHTML(RestrictUserForm::selectUserForm($user));
    UserRestriction::purgeExpired();
    $old = UserRestriction::fetchForUser($user, true);
    RestrictUserForm::pageRestrictionForm($uid, $user, $old);
    RestrictUserForm::namespaceRestrictionForm($uid, $user, $old);
    // Renew it after possible changes in previous two functions
    $old = UserRestriction::fetchForUser($user, true);
    if ($old) {
        $wgOut->addHTML(RestrictUserForm::existingRestrictions($old));
    }
}
Ejemplo n.º 2
0
 public function execute()
 {
     $params = $this->extractRequestParams();
     $titleObj = null;
     if (!isset($params['title'])) {
         $this->dieUsageMsg(array('missingparam', 'title'));
     }
     if (!isset($params['user'])) {
         $this->dieUsageMsg(array('missingparam', 'user'));
     }
     $titleObj = Title::newFromText($params['title']);
     if (!$titleObj) {
         $this->dieUsageMsg(array('invalidtitle', $params['title']));
     }
     if (!$titleObj->exists()) {
         $this->dieUsageMsg(array('notanarticle'));
     }
     // We need to be able to revert IPs, but getCanonicalName rejects them
     $username = User::isIP($params['user']) ? $params['user'] : User::getCanonicalName($params['user']);
     if (!$username) {
         $this->dieUsageMsg(array('invaliduser', $params['user']));
     }
     $articleObj = new Article($titleObj);
     $summary = isset($params['summary']) ? $params['summary'] : "";
     $details = null;
     $retval = $articleObj->doRollback($username, $summary, $params['token'], $params['markbot'], $details);
     if ($retval) {
         // We don't care about multiple errors, just report one of them
         $this->dieUsageMsg(reset($retval));
     }
     $info = array('title' => $titleObj->getPrefixedText(), 'pageid' => intval($details['current']->getPage()), 'summary' => $details['summary'], 'revid' => intval($details['newid']), 'old_revid' => intval($details['current']->getID()), 'last_revid' => intval($details['target']->getID()));
     $this->getResult()->addValue(null, $this->getModuleName(), $info);
 }
 public function getUserDetails()
 {
     if (is_null($this->usersData)) {
         $users = preg_split("/[\r\n]+/", $this->users);
         foreach ($users as $k => $v) {
             if (trim($v) == '') {
                 unset($users[$k]);
             }
         }
         $users = array_values($users);
         foreach ($users as $k => $name) {
             $userName = User::isIP($name) ? $name : User::getCanonicalName($name);
             $user = null;
             if ($userName !== false) {
                 $user = F::build('User', array($userName), 'newFromName');
                 if (empty($user) || $user->getId() == 0) {
                     $user = null;
                 }
             }
             $users[$k] = array('id' => !empty($user) ? $user->getId() : 0, 'ip' => User::isIP($name) ? $name : '', 'name' => $name, 'canonical' => $userName);
         }
         $this->usersData = $users;
     }
     return $this->usersData;
 }
 protected function doCreate()
 {
     $params = $this->extractRequestParams();
     // Do validations
     foreach (explode('|', 'username|password|email') as $field) {
         if (!isset($params[$field])) {
             $this->dieUsage("Missing parameter {$field}", 'missingparam');
         }
     }
     $username = $params['username'];
     if (User::getCanonicalName($username, 'creatable') === false) {
         $this->dieUsage("User name is not acceptable", 'invalidusername');
     }
     $user = User::newFromName($username);
     if ($user->getID() !== 0) {
         $this->dieUsage("User name is in use", 'nonfreeusername');
     }
     $password = $params['password'];
     if (!$user->isValidPassword($password)) {
         $this->dieUsage("Password is not acceptable", 'invalidpassword');
     }
     $email = $params['email'];
     if (!Sanitizer::validateEmail($email)) {
         $this->dieUsage("Email is not acceptable", 'invalidemail');
     }
     $user = TranslateSandbox::addUser($username, $email, $password);
     $output = array('user' => array('name' => $user->getName(), 'id' => $user->getId()));
     $user->setOption('language', $this->getContext()->getLanguage()->getCode());
     $user->saveSettings();
     $this->getResult()->addValue(null, $this->getModuleName(), $output);
 }
 /**
  * Check if a username+password pair is a valid login.
  * The name will be normalized to MediaWiki's requirements, so
  * you might need to munge it (for instance, for lowercase initial
  * letters).
  *
  * @param $username String: username.
  * @param $password String: user password.
  * @return bool
  * @public
  */
 function authenticate($username, $password)
 {
     global $wgCentralAuthAutoMigrate, $wgCentralAuthCheckSULMigration;
     global $wgCentralAuthAutoMigrateNonGlobalAccounts;
     global $wgCentralAuthStrict;
     $central = new CentralAuthUser($username);
     $passwordMatch = self::checkPassword($central, $password);
     if (!$passwordMatch && $wgCentralAuthCheckSULMigration) {
         // Check to see if this is a user who was affected by a global username
         // collision during a forced migration to central auth accounts.
         $renamedUsername = User::getCanonicalName($username . '~' . str_replace('_', '-', wfWikiID()));
         if ($renamedUsername !== false) {
             wfDebugLog('CentralAuth', "CentralAuthMigration: Checking for migration of '{$username}' to '{$renamedUsername}'");
             $renamed = new CentralAuthUser($renamedUsername);
             $passwordMatch = self::checkPassword($renamed, $password);
             // Remember that the user was authenticated under a different name.
             if ($passwordMatch) {
                 $this->sulMigrationName = $renamedUsername;
             } elseif ($wgCentralAuthStrict) {
                 // Will also create log entry
                 $this->checkAttached($central, $username);
             }
             // Since we are falling back to check a force migrated user, we are done
             // regardless of password match status. We don't want to try to
             // automigrate or check detached accounts.
             return $passwordMatch;
         }
     }
     if (!$central->exists()) {
         wfDebugLog('CentralAuth', "plugin: no global account for '{$username}'");
         // See if all the unattached accounts match passwords
         // and can be globalized. (bug 70392)
         if ($wgCentralAuthAutoMigrateNonGlobalAccounts) {
             $ok = $central->storeAndMigrate(array($password), true, true, true);
             if ($ok) {
                 wfDebugLog('CentralAuth', "wgCentralAuthAutoMigrateNonGlobalAccounts successful in creating a global account for '{$username}'");
                 return true;
             }
         }
         return false;
     }
     if ($passwordMatch && $wgCentralAuthAutoMigrate) {
         // If the user passed in the global password, we can identify
         // any remaining local accounts with a matching password
         // and migrate them in transparently.
         //
         // That may or may not include the current wiki.
         //
         wfDebugLog('CentralAuth', "plugin: attempting wgCentralAuthAutoMigrate for '{$username}'");
         $central->attemptPasswordMigration($password);
     }
     // Will also create log entry
     if ($this->checkAttached($central, $username) === false) {
         return false;
     }
     return $passwordMatch;
 }
Ejemplo n.º 6
0
 protected function initFromName($name)
 {
     wfDebug(__METHOD__ . ": init User from name: {$name} \n");
     $name = User::getCanonicalName($name, 'usable');
     if (!is_string($name)) {
         return false;
     }
     return $this->initFromCond(array('user_name' => $name));
 }
 function onSubmit(array $data)
 {
     if (!isset($data['username'])) {
         $this->showCurrentRenames();
         return false;
     }
     $name = User::getCanonicalName($data['username'], 'usable');
     if (!$name) {
         $this->showCurrentRenames();
         return false;
     }
     $out = $this->getOutput();
     $this->renameuserStatus = new GlobalRenameUserStatus($name);
     $names = $this->renameuserStatus->getNames();
     if (!$names) {
         $this->checkCachePurge($name);
         $out->addWikiMsg('centralauth-rename-notinprogress', $name);
         $this->getForm()->displayForm(false);
         $this->showLogExtract($name);
         return true;
     }
     list($oldName, $newName) = $names;
     $statuses = $this->renameuserStatus->getStatuses();
     $this->getForm()->displayForm(false);
     // $newname will always be defined since we check
     // for 0 result rows above
     $caUser = new CentralAuthUser($newName);
     $attached = $caUser->listAttached();
     foreach ($attached as $wiki) {
         // If it's not in the db table, and there is
         // an attached acount, assume it's done.
         if (!isset($statuses[$wiki])) {
             $statuses[$wiki] = 'done';
         }
     }
     ksort($statuses);
     $table = Html::openElement('table', array('class' => 'wikitable sortable'));
     $table .= Html::openElement('tr');
     $table .= Html::element('th', array(), $this->msg('centralauth-rename-table-domain')->text());
     $table .= Html::element('th', array(), $this->msg('centralauth-rename-table-status')->text());
     $table .= Html::closeElement('tr');
     foreach ($statuses as $wiki => $status) {
         $table .= Html::openElement('tr');
         $table .= Html::element('td', array(), WikiMap::getWiki($wiki)->getDisplayName());
         // Messages used: centralauth-rename-table-status-inprogress
         // centralauth-rename-table-status-queued, centralauth-rename-table-status-done
         $table .= Html::rawElement('td', array(), $this->msg("centralauth-rename-table-status-{$status}")->parse());
         $table .= Html::closeElement('tr');
     }
     $table .= Html::closeElement('table');
     $fieldset = Xml::fieldset($this->msg('centralauth-rename-progress-fieldset')->text(), $table);
     $this->showLogExtract($newName);
     $out->addHTML($fieldset);
     return true;
 }
Ejemplo n.º 8
0
 public function execute()
 {
     global $wgUser, $wgSharedDB;
     if ($this->getOption('onlyshared', false) && empty($wgSharedDB)) {
         $this->output("Skipping wiki due to non-shared users database\n");
         return;
     }
     $wgUser = User::newFromName(self::USER_NAME);
     $bot = true;
     $time = $this->getOption('time');
     $time = wfTimestamp(TS_UNIX, $time);
     if (!$time) {
         $this->error('Invalid time', true);
     }
     $time = wfTimestamp(TS_MW, $time);
     $users = explode('|', $this->getOption('users'));
     foreach ($users as $user) {
         $username = User::isIP($user) ? $user : User::getCanonicalName($user);
         if (!$username) {
             $this->error('Invalid username', true);
         }
     }
     $summary = $this->getOption('summary', 'mass rollback');
     $titles = array();
     $results = array();
     if ($this->hasOption('titles')) {
         foreach (explode('|', $this->getOption('titles')) as $title) {
             $t = Title::newFromText($title);
             if (!$t) {
                 $this->error('Invalid title, ' . $title);
             } else {
                 $titles[] = $t;
             }
         }
     } else {
         $titles = $this->getRollbackTitles($users, $time);
     }
     if (!$titles) {
         $this->output("No suitable titles to be rolled back\n");
         return;
     }
     $this->output("Found " . count($titles) . " title(s) to process\n");
     global $wgTitle;
     foreach ($titles as $t) {
         $wgTitle = $t;
         $this->output('Processing ' . $t->getPrefixedText() . '...');
         $messages = '';
         $status = $this->rollbackTitle($t, $users, $time, $summary, $messages);
         if ($status) {
             $this->output("done ({$messages})\n");
         } else {
             $this->output("failed ({$messages})\n");
         }
     }
 }
Ejemplo n.º 9
0
 /**
  * @param $name string
  * @return bool
  */
 protected function initFromName($name)
 {
     # We might not need the 'usable' bit, but let's be safe.  Theoretically
     # this might return wrong results for old versions, but it's probably
     # good enough.
     $name = User::getCanonicalName($name, 'usable');
     if (!is_string($name)) {
         return false;
     }
     return $this->initFromCond(array('user_name' => $name));
 }
Ejemplo n.º 10
0
 public function execute()
 {
     global $wgUser;
     $this->getMain()->requestWriteMode();
     $params = $this->extractRequestParams();
     $titleObj = NULL;
     if (!isset($params['title'])) {
         $this->dieUsageMsg(array('missingparam', 'title'));
     }
     if (!isset($params['user'])) {
         $this->dieUsageMsg(array('missingparam', 'user'));
     }
     if (!isset($params['token'])) {
         $this->dieUsageMsg(array('missingparam', 'token'));
     }
     $titleObj = Title::newFromText($params['title']);
     if (!$titleObj) {
         $this->dieUsageMsg(array('invalidtitle', $params['title']));
     }
     if (!$titleObj->exists()) {
         $this->dieUsageMsg(array('notanarticle'));
     }
     $username = User::getCanonicalName($params['user']);
     if (!$username) {
         $this->dieUsageMsg(array('invaliduser', $params['user']));
     }
     $articleObj = new Article($titleObj);
     $summary = isset($params['summary']) ? $params['summary'] : "";
     $details = null;
     $dbw = wfGetDb(DB_MASTER);
     $dbw->begin();
     $retval = $articleObj->doRollback($username, $summary, $params['token'], $params['markbot'], $details);
     if (!empty($retval)) {
         // We don't care about multiple errors, just report one of them
         $this->dieUsageMsg(current($retval));
     }
     $dbw->commit();
     $current = $target = $summary = NULL;
     extract($details);
     $info = array('title' => $titleObj->getPrefixedText(), 'pageid' => $current->getPage(), 'summary' => $summary, 'revid' => $titleObj->getLatestRevID(), 'old_revid' => $current->getID(), 'last_revid' => $target->getID());
     $this->getResult()->addValue(null, $this->getModuleName(), $info);
 }
 function show()
 {
     $out = $this->getOutput();
     $filter = $this->mFilter;
     if ($filter) {
         $out->setPageTitle($this->msg('abusefilter-history', $filter));
     } else {
         $out->setPageTitle($this->msg('abusefilter-filter-log'));
     }
     # Check perms
     if ($filter && !$this->getUser()->isAllowed('abusefilter-modify') && AbuseFilter::filterHidden($filter)) {
         $out->addWikiMsg('abusefilter-history-error-hidden');
         return;
     }
     # Useful links
     $links = array();
     if ($filter) {
         $links['abusefilter-history-backedit'] = $this->getTitle($filter);
     }
     foreach ($links as $msg => $title) {
         $links[$msg] = Linker::link($title, $this->msg($msg)->parse());
     }
     $backlinks = $this->getLanguage()->pipeList($links);
     $out->addHTML(Xml::tags('p', null, $backlinks));
     # For user
     $user = User::getCanonicalName($this->getRequest()->getText('user'), 'valid');
     if ($user) {
         $out->addSubtitle($this->msg('abusefilter-history-foruser', Linker::userLink(1, $user), $user)->text());
     }
     // Add filtering of changes et al.
     $fields['abusefilter-history-select-user'] = Xml::input('user', 45, $user);
     $filterForm = Xml::buildForm($fields, 'abusefilter-history-select-submit');
     $filterForm .= "\n" . Html::hidden('title', $this->getTitle("history/{$filter}"));
     $filterForm = Xml::tags('form', array('action' => $this->getTitle("history/{$filter}")->getLocalURL(), 'method' => 'get'), $filterForm);
     $filterForm = Xml::fieldset($this->msg('abusefilter-history-select-legend')->text(), $filterForm);
     $out->addHTML($filterForm);
     $pager = new AbuseFilterHistoryPager($filter, $this, $user);
     $table = $pager->getBody();
     $out->addHTML($pager->getNavigationBar() . $table . $pager->getNavigationBar());
 }
Ejemplo n.º 12
0
 public function execute()
 {
     $user = $this->getOption('user');
     $username = User::isIP($user) ? $user : User::getCanonicalName($user);
     if (!$username) {
         $this->error('Invalid username', true);
     }
     $bot = $this->hasOption('bot');
     $summary = $this->getOption('summary', $this->mSelf . ' mass rollback');
     $titles = array();
     $results = array();
     if ($this->hasOption('titles')) {
         foreach (explode('|', $this->getOption('titles')) as $title) {
             $t = Title::newFromText($title);
             if (!$t) {
                 $this->error('Invalid title, ' . $title);
             } else {
                 $titles[] = $t;
             }
         }
     } else {
         $titles = $this->getRollbackTitles($user);
     }
     if (!$titles) {
         $this->output('No suitable titles to be rolled back');
         return;
     }
     $doer = User::newFromName('Maintenance script');
     foreach ($titles as $t) {
         $page = WikiPage::factory($t);
         $this->output('Processing ' . $t->getPrefixedText() . '... ');
         if (!$page->commitRollback($user, $summary, $bot, $results, $doer)) {
             $this->output("done\n");
         } else {
             $this->output("failed\n");
         }
     }
 }
 protected function rename($row, DatabaseBase $dbw)
 {
     $wiki = $row->utr_wiki;
     $name = $row->utr_name;
     $newNamePrefix = User::getCanonicalName($name . '~' . str_replace('_', '-', $wiki), 'usable');
     if (!$newNamePrefix) {
         $this->log("ERROR: New name '{$name}~{$wiki}' is not valid");
         return;
     }
     $this->log("Beginning rename of {$newNamePrefix}");
     $newCAUser = new CentralAuthUser($newNamePrefix);
     $count = 0;
     // Edge case: Someone created User:Foo~wiki manually.
     // So just start appending numbers to the end of the name
     // until we get one that isn't used.
     while ($newCAUser->exists()) {
         $count++;
         $newCAUser = new CentralAuthUser($newNamePrefix . (string) $count);
     }
     if ($newNamePrefix !== $newCAUser->getName()) {
         $this->log("WARNING: New name is now {$newCAUser->getName()}");
     }
     $this->log("Renaming {$name} to {$newCAUser->getName()}.");
     $statuses = new GlobalRenameUserStatus($name);
     $success = $statuses->setStatuses(array(array('ru_wiki' => $wiki, 'ru_oldname' => $name, 'ru_newname' => $newCAUser->getName(), 'ru_status' => 'queued')));
     if (!$success) {
         $this->log("WARNING: Race condition, renameuser_status already set for {$newCAUser->getName()}. Skipping.");
         return;
     }
     $this->log("Set renameuser_status for {$newCAUser->getName()}.");
     $job = new LocalRenameUserJob(Title::newFromText('Global rename job'), array('from' => $name, 'to' => $newCAUser->getName(), 'renamer' => 'Maintenance script', 'movepages' => true, 'suppressredirects' => true, 'promotetoglobal' => true, 'reason' => $this->getOption('reason')));
     JobQueueGroup::singleton($row->utr_wiki)->push($job);
     $this->log("Submitted job for {$newCAUser->getName()}.");
     $updates = new UsersToRenameDatabaseUpdates($dbw);
     $updates->markRenamed($row->utr_name, $row->utr_wiki);
 }
Ejemplo n.º 14
0
 /**
  * @deprecated since 1.27 - don't use LoginForm, use AuthManager instead
  */
 public static function clearLoginThrottle($username)
 {
     wfDeprecated(__METHOD__, "1.27");
     global $wgRequest;
     $username = User::getCanonicalName($username, 'usable') ?: $username;
     $throttler = new Throttler();
     return $throttler->clear($username, $wgRequest->getIP());
 }
 /**
  * Validate the 'user' parameter and set the value to compare
  * against `revision`.`rev_user_text`
  *
  * @param $user string
  */
 private function prepareUsername($user)
 {
     if (!is_null($user) && $user !== '') {
         $name = User::isIP($user) ? $user : User::getCanonicalName($user, 'valid');
         if ($name === false) {
             $this->dieUsage("User name {$user} is not valid", 'param_user');
         } else {
             $this->usernames[] = $name;
         }
     } else {
         $this->dieUsage('User parameter may not be empty', 'param_user');
     }
 }
 /**
  * @return bool
  */
 public function submit()
 {
     $retVal = true;
     $this->parent->setVarsFromRequest(array('wgSitename', '_NamespaceType', '_AdminName', '_AdminPassword', '_AdminPasswordConfirm', '_AdminEmail', '_Subscribe', '_SkipOptional', 'wgMetaNamespace'));
     // Validate site name
     if (strval($this->getVar('wgSitename')) === '') {
         $this->parent->showError('config-site-name-blank');
         $retVal = false;
     }
     // Fetch namespace
     $nsType = $this->getVar('_NamespaceType');
     if ($nsType == 'site-name') {
         $name = $this->getVar('wgSitename');
         // Sanitize for namespace
         // This algorithm should match the JS one in WebInstallerOutput.php
         $name = preg_replace('/[\\[\\]\\{\\}|#<>%+? ]/', '_', $name);
         $name = str_replace('&', '&amp;', $name);
         $name = preg_replace('/__+/', '_', $name);
         $name = ucfirst(trim($name, '_'));
     } elseif ($nsType == 'generic') {
         $name = wfMessage('config-ns-generic')->text();
     } else {
         // other
         $name = $this->getVar('wgMetaNamespace');
     }
     // Validate namespace
     if (strpos($name, ':') !== false) {
         $good = false;
     } else {
         // Title-style validation
         $title = Title::newFromText($name);
         if (!$title) {
             $good = $nsType == 'site-name';
         } else {
             $name = $title->getDBkey();
             $good = true;
         }
     }
     if (!$good) {
         $this->parent->showError('config-ns-invalid', $name);
         $retVal = false;
     }
     // Make sure it won't conflict with any existing namespaces
     global $wgContLang;
     $nsIndex = $wgContLang->getNsIndex($name);
     if ($nsIndex !== false && $nsIndex !== NS_PROJECT) {
         $this->parent->showError('config-ns-conflict', $name);
         $retVal = false;
     }
     $this->setVar('wgMetaNamespace', $name);
     // Validate username for creation
     $name = $this->getVar('_AdminName');
     if (strval($name) === '') {
         $this->parent->showError('config-admin-name-blank');
         $cname = $name;
         $retVal = false;
     } else {
         $cname = User::getCanonicalName($name, 'creatable');
         if ($cname === false) {
             $this->parent->showError('config-admin-name-invalid', $name);
             $retVal = false;
         } else {
             $this->setVar('_AdminName', $cname);
         }
     }
     // Validate password
     $msg = false;
     $pwd = $this->getVar('_AdminPassword');
     $user = User::newFromName($cname);
     if ($user) {
         $valid = $user->getPasswordValidity($pwd);
     } else {
         $valid = 'config-admin-name-invalid';
     }
     if (strval($pwd) === '') {
         # $user->getPasswordValidity just checks for $wgMinimalPasswordLength.
         # This message is more specific and helpful.
         $msg = 'config-admin-password-blank';
     } elseif ($pwd !== $this->getVar('_AdminPasswordConfirm')) {
         $msg = 'config-admin-password-mismatch';
     } elseif ($valid !== true) {
         $msg = $valid;
     }
     if ($msg !== false) {
         call_user_func_array(array($this->parent, 'showError'), (array) $msg);
         $this->setVar('_AdminPassword', '');
         $this->setVar('_AdminPasswordConfirm', '');
         $retVal = false;
     }
     // Validate e-mail if provided
     $email = $this->getVar('_AdminEmail');
     if ($email && !Sanitizer::validateEmail($email)) {
         $this->parent->showError('config-admin-error-bademail');
         $retVal = false;
     }
     // If they asked to subscribe to mediawiki-announce but didn't give
     // an e-mail, show an error. Bug 29332
     if (!$email && $this->getVar('_Subscribe')) {
         $this->parent->showError('config-subscribe-noemail');
         $retVal = false;
     }
     return $retVal;
 }
Ejemplo n.º 17
0
 function processRegForm(&$result)
 {
     global $wgRequest, $wgUser, $wgOut;
     $dbw = wfGetDB(DB_MASTER);
     $userOverride = strlen($wgRequest->getVal('requested_username'));
     $newname = $userOverride ? $wgRequest->getVal('requested_username') : $wgRequest->getVal('proposed_username');
     $newname = $dbw->strencode($newname);
     $email = $dbw->strencode($wgRequest->getVal('email'));
     $realname = $userOverride ? '' : $dbw->strencode($result['name']);
     $newname = User::getCanonicalName($newname);
     $exist = User::newFromName($newname);
     if ($exist->getID() > 0 && $exist->getID() != $wgUser->getID()) {
         $this->printRegForm($result, $newname, $email, wfMsg('fbconnect_username_inuse', $newname));
         return;
     }
     $authenticatedTimeStamp = wfTimestampNow();
     $dbw->update('user', array('user_name' => $newname, 'user_email' => $email, 'user_real_name' => $realname, 'user_email_authenticated' => $authenticatedTimeStamp), array('user_id' => $wgUser->getID()));
     if (!$userOverride) {
         $this->updateAvatar($result);
     }
     $wgUser->invalidateCache();
     $wgUser->loadFromID();
     $wgUser->setCookies();
     wfRunHooks('AddNewAccount', array($wgUser, true));
     wfRunHooks('FBLoginComplete', array($wgUser));
     // All registered. Send them along their merry way
     $this->setCookies();
     $wgOut->redirect($this->returnto);
 }
Ejemplo n.º 18
0
 function processForm()
 {
     global $wgRequest, $wgUser, $wgOut;
     $dbw = wfGetDB(DB_MASTER);
     $userOverride = strlen($wgRequest->getVal('requested_username'));
     $newname = $userOverride ? $wgRequest->getVal('requested_username') : $wgRequest->getVal('proposed_username');
     $newname = $dbw->strencode($newname);
     $email = $dbw->strencode($wgRequest->getVal('email'));
     $realname = $userOverride ? '' : $dbw->strencode($wgRequest->getVal('original_username'));
     $avatar = $wgRequest->getVal('avatar_url');
     $show_authorship = (int) ($wgRequest->getVal('show_authorship') == 'on');
     $newname = User::getCanonicalName($newname);
     if (self::usernameExists($newname)) {
         $this->showForm($wgRequest->getVal('gplus_id'), $wgRequest->getVal('original_username'), $wgRequest->getVal('email'), $wgRequest->getVal('avatar_url'), wfMsg('gplusconnect_username_inuse', $newname));
         return;
     }
     $dbw->update('user', array('user_name' => $newname, 'user_email' => $email, 'user_real_name' => $realname), array('user_id' => $wgUser->getID()));
     //update the avatar
     $this->updateAvatar($avatar);
     $wgUser->invalidateCache();
     $wgUser = User::newFromName($newname);
     //update authorship settings
     // [for later...] (hard code for now)
     //$wgUser->setOption('show_google_authorship', $show_authorship);
     $wgUser->setOption('show_google_authorship', false);
     //add G+ user in user options
     $wgUser->setOption('gplus_uid', $wgRequest->getVal('gplus_id'));
     $wgUser->saveSettings();
     $wgUser->setCookies();
     wfRunHooks('AddNewAccount', array($wgUser, true));
     wfRunHooks('GPlusLoginComplete', array($wgUser));
     // All registered. Send them along their merry way
     $wgOut->redirect($this->returnto);
 }
Ejemplo n.º 19
0
 /**
  * Clear the login attempt throttle hit count for the (username,current IP) tuple.
  * @param string $username The user name
  * @return void
  */
 public static function clearLoginThrottle($username)
 {
     global $wgRequest, $wgPasswordAttemptThrottle;
     $canUsername = User::getCanonicalName($username, 'usable');
     $username = $canUsername !== false ? $canUsername : $username;
     if (is_array($wgPasswordAttemptThrottle)) {
         $throttleConfig = $wgPasswordAttemptThrottle;
         if (isset($wgPasswordAttemptThrottle['count'])) {
             // old style. Convert for backwards compat.
             $throttleConfig = [$wgPasswordAttemptThrottle];
         }
         foreach ($throttleConfig as $index => $specificThrottle) {
             if (isset($specificThrottle['allIPs'])) {
                 $ip = 'All';
             } else {
                 $ip = $wgRequest->getIP();
             }
             $throttleKey = wfGlobalCacheKey('password-throttle', $index, $ip, md5($username));
             ObjectCache::getLocalClusterInstance()->delete($throttleKey);
         }
     }
 }
 /**
  * Get a MailAddress for a user on a remote wiki
  *
  * @param string $wiki
  * @param string $username
  * @return MailAddress|null
  */
 protected function getRemoteUserMailAddress($wiki, $username)
 {
     $lb = wfGetLB($wiki);
     $remoteDB = $lb->getConnection(DB_SLAVE, array(), $wiki);
     $row = $remoteDB->selectRow('user', array('user_email', 'user_name', 'user_real_name'), array('user_name' => User::getCanonicalName($username)), __METHOD__);
     if ($row === false) {
         $address = null;
     } else {
         $address = new MailAddress($row->user_email, $row->user_name, $row->user_real_name);
     }
     $lb->reuseConnection($remoteDB);
     return $address;
 }
Ejemplo n.º 21
0
 /**
  * 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
  * @return Status
  */
 public function fetchUser($username)
 {
     $parts = explode($this->getConfig()->get('UserrightsInterwikiDelimiter'), $username);
     if (count($parts) < 2) {
         $name = trim($username);
         $database = '';
     } else {
         list($name, $database) = array_map('trim', $parts);
         if ($database == wfWikiID()) {
             $database = '';
         } else {
             if (!$this->getUser()->isAllowed('userrights-interwiki')) {
                 return Status::newFatal('userrights-no-interwiki');
             }
             if (!UserRightsProxy::validDatabase($database)) {
                 return Status::newFatal('userrights-nodatabase', $database);
             }
         }
     }
     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 ($database == '') {
             $name = User::whoIs($id);
         } else {
             $name = UserRightsProxy::whoIs($database, $id);
         }
         if (!$name) {
             return Status::newFatal('noname');
         }
     } else {
         $name = User::getCanonicalName($name);
         if ($name === false) {
             // invalid name
             return Status::newFatal('nosuchusershort', $username);
         }
     }
     if ($database == '') {
         $user = User::newFromName($name);
     } else {
         $user = UserRightsProxy::newFromName($database, $name);
     }
     if (!$user || $user->isAnon()) {
         return Status::newFatal('nosuchusershort', $username);
     }
     return Status::newGood($user);
 }
Ejemplo n.º 22
0
 public function execute()
 {
     $params = $this->extractRequestParams();
     if (!is_null($params['prop'])) {
         $this->prop = array_flip($params['prop']);
     } else {
         $this->prop = array();
     }
     $users = (array) $params['users'];
     $goodNames = $done = array();
     $result = $this->getResult();
     // Canonicalize user names
     foreach ($users as $u) {
         $n = User::getCanonicalName($u);
         if ($n === false || $n === '') {
             $vals = array('name' => $u, 'invalid' => '');
             $fit = $result->addValue(array('query', $this->getModuleName()), null, $vals);
             if (!$fit) {
                 $this->setContinueEnumParameter('users', implode('|', array_diff($users, $done)));
                 $goodNames = array();
                 break;
             }
             $done[] = $u;
         } else {
             $goodNames[] = $n;
         }
     }
     if (count($goodNames)) {
         $this->addTables('user', 'u1');
         $this->addFields('u1.*');
         $this->addWhereFld('u1.user_name', $goodNames);
         if (isset($this->prop['groups'])) {
             $this->addTables('user_groups');
             $this->addJoinConds(array('user_groups' => array('LEFT JOIN', 'ug_user=u1.user_id')));
             $this->addFields('ug_group');
         }
         $this->showHiddenUsersAddBlockInfo(isset($this->prop['blockinfo']));
         $data = array();
         $res = $this->select(__METHOD__);
         foreach ($res as $row) {
             $user = User::newFromRow($row);
             $name = $user->getName();
             $data[$name]['name'] = $name;
             if (isset($this->prop['editcount'])) {
                 $data[$name]['editcount'] = intval($user->getEditCount());
             }
             if (isset($this->prop['registration'])) {
                 $data[$name]['registration'] = wfTimestampOrNull(TS_ISO_8601, $user->getRegistration());
             }
             if (isset($this->prop['groups']) && !is_null($row->ug_group)) {
                 // This row contains only one group, others will be added from other rows
                 $data[$name]['groups'][] = $row->ug_group;
             }
             if (isset($this->prop['rights']) && !is_null($row->ug_group)) {
                 if (!isset($data[$name]['rights'])) {
                     $data[$name]['rights'] = User::getGroupPermissions(User::getImplicitGroups());
                 }
                 $data[$name]['rights'] = array_unique(array_merge($data[$name]['rights'], User::getGroupPermissions(array($row->ug_group))));
                 $result->setIndexedTagName($data[$name]['rights'], 'r');
             }
             if ($row->ipb_deleted) {
                 $data[$name]['hidden'] = '';
             }
             if (isset($this->prop['blockinfo']) && !is_null($row->ipb_by_text)) {
                 $data[$name]['blockedby'] = $row->ipb_by_text;
                 $data[$name]['blockreason'] = $row->ipb_reason;
                 $data[$name]['blockexpiry'] = $row->ipb_expiry;
             }
             if (isset($this->prop['emailable']) && $user->canReceiveEmail()) {
                 $data[$name]['emailable'] = '';
             }
             if (isset($this->prop['gender'])) {
                 $gender = $user->getOption('gender');
                 if (strval($gender) === '') {
                     $gender = 'unknown';
                 }
                 $data[$name]['gender'] = $gender;
             }
             if (!is_null($params['token'])) {
                 $tokenFunctions = $this->getTokenFunctions();
                 foreach ($params['token'] as $t) {
                     $val = call_user_func($tokenFunctions[$t], $user);
                     if ($val === false) {
                         $this->setWarning("Action '{$t}' is not allowed for the current user");
                     } else {
                         $data[$name][$t . 'token'] = $val;
                     }
                 }
             }
         }
     }
     // Second pass: add result data to $retval
     foreach ($goodNames as $u) {
         if (!isset($data[$u])) {
             $data[$u] = array('name' => $u);
             $urPage = new UserrightsPage();
             $iwUser = $urPage->fetchUser($u);
             if ($iwUser instanceof UserRightsProxy) {
                 $data[$u]['interwiki'] = '';
                 if (!is_null($params['token'])) {
                     $tokenFunctions = $this->getTokenFunctions();
                     foreach ($params['token'] as $t) {
                         $val = call_user_func($tokenFunctions[$t], $iwUser);
                         if ($val === false) {
                             $this->setWarning("Action '{$t}' is not allowed for the current user");
                         } else {
                             $data[$u][$t . 'token'] = $val;
                         }
                     }
                 }
             } else {
                 $data[$u]['missing'] = '';
             }
         } else {
             if (isset($this->prop['groups']) && isset($data[$u]['groups'])) {
                 $autolist = ApiQueryUsers::getAutoGroups(User::newFromName($u));
                 $data[$u]['groups'] = array_merge($autolist, $data[$u]['groups']);
                 $this->getResult()->setIndexedTagName($data[$u]['groups'], 'g');
             }
         }
         $fit = $result->addValue(array('query', $this->getModuleName()), null, $data[$u]);
         if (!$fit) {
             $this->setContinueEnumParameter('users', implode('|', array_diff($users, $done)));
             break;
         }
         $done[] = $u;
     }
     return $this->getResult()->setIndexedTagName_internal(array('query', $this->getModuleName()), 'user');
 }
Ejemplo n.º 23
0
 public function execute()
 {
     $params = $this->extractRequestParams();
     if (!is_null($params['prop'])) {
         $this->prop = array_flip($params['prop']);
     } else {
         $this->prop = [];
     }
     $users = (array) $params['users'];
     $goodNames = $done = [];
     $result = $this->getResult();
     // Canonicalize user names
     foreach ($users as $u) {
         $n = User::getCanonicalName($u);
         if ($n === false || $n === '') {
             $vals = ['name' => $u, 'invalid' => true];
             $fit = $result->addValue(['query', $this->getModuleName()], null, $vals);
             if (!$fit) {
                 $this->setContinueEnumParameter('users', implode('|', array_diff($users, $done)));
                 $goodNames = [];
                 break;
             }
             $done[] = $u;
         } else {
             $goodNames[] = $n;
         }
     }
     $result = $this->getResult();
     if (count($goodNames)) {
         $this->addTables('user');
         $this->addFields(User::selectFields());
         $this->addWhereFld('user_name', $goodNames);
         $this->showHiddenUsersAddBlockInfo(isset($this->prop['blockinfo']));
         $data = [];
         $res = $this->select(__METHOD__);
         $this->resetQueryParams();
         // get user groups if needed
         if (isset($this->prop['groups']) || isset($this->prop['rights'])) {
             $userGroups = [];
             $this->addTables('user');
             $this->addWhereFld('user_name', $goodNames);
             $this->addTables('user_groups');
             $this->addJoinConds(['user_groups' => ['INNER JOIN', 'ug_user=user_id']]);
             $this->addFields(['user_name', 'ug_group']);
             $userGroupsRes = $this->select(__METHOD__);
             foreach ($userGroupsRes as $row) {
                 $userGroups[$row->user_name][] = $row->ug_group;
             }
         }
         foreach ($res as $row) {
             // create user object and pass along $userGroups if set
             // that reduces the number of database queries needed in User dramatically
             if (!isset($userGroups)) {
                 $user = User::newFromRow($row);
             } else {
                 if (!isset($userGroups[$row->user_name]) || !is_array($userGroups[$row->user_name])) {
                     $userGroups[$row->user_name] = [];
                 }
                 $user = User::newFromRow($row, ['user_groups' => $userGroups[$row->user_name]]);
             }
             $name = $user->getName();
             $data[$name]['userid'] = $user->getId();
             $data[$name]['name'] = $name;
             if (isset($this->prop['editcount'])) {
                 $data[$name]['editcount'] = $user->getEditCount();
             }
             if (isset($this->prop['registration'])) {
                 $data[$name]['registration'] = wfTimestampOrNull(TS_ISO_8601, $user->getRegistration());
             }
             if (isset($this->prop['groups'])) {
                 $data[$name]['groups'] = $user->getEffectiveGroups();
             }
             if (isset($this->prop['implicitgroups'])) {
                 $data[$name]['implicitgroups'] = $user->getAutomaticGroups();
             }
             if (isset($this->prop['rights'])) {
                 $data[$name]['rights'] = $user->getRights();
             }
             if ($row->ipb_deleted) {
                 $data[$name]['hidden'] = true;
             }
             if (isset($this->prop['blockinfo']) && !is_null($row->ipb_by_text)) {
                 $data[$name]['blockid'] = (int) $row->ipb_id;
                 $data[$name]['blockedby'] = $row->ipb_by_text;
                 $data[$name]['blockedbyid'] = (int) $row->ipb_by;
                 $data[$name]['blockedtimestamp'] = wfTimestamp(TS_ISO_8601, $row->ipb_timestamp);
                 $data[$name]['blockreason'] = $row->ipb_reason;
                 $data[$name]['blockexpiry'] = $row->ipb_expiry;
             }
             if (isset($this->prop['emailable'])) {
                 $data[$name]['emailable'] = $user->canReceiveEmail();
             }
             if (isset($this->prop['gender'])) {
                 $gender = $user->getOption('gender');
                 if (strval($gender) === '') {
                     $gender = 'unknown';
                 }
                 $data[$name]['gender'] = $gender;
             }
             if (isset($this->prop['centralids'])) {
                 $data[$name] += ApiQueryUserInfo::getCentralUserInfo($this->getConfig(), $user, $params['attachedwiki']);
             }
             if (!is_null($params['token'])) {
                 $tokenFunctions = $this->getTokenFunctions();
                 foreach ($params['token'] as $t) {
                     $val = call_user_func($tokenFunctions[$t], $user);
                     if ($val === false) {
                         $this->setWarning("Action '{$t}' is not allowed for the current user");
                     } else {
                         $data[$name][$t . 'token'] = $val;
                     }
                 }
             }
         }
     }
     $context = $this->getContext();
     // Second pass: add result data to $retval
     foreach ($goodNames as $u) {
         if (!isset($data[$u])) {
             $data[$u] = ['name' => $u];
             $urPage = new UserrightsPage();
             $urPage->setContext($context);
             $iwUser = $urPage->fetchUser($u);
             if ($iwUser instanceof UserRightsProxy) {
                 $data[$u]['interwiki'] = true;
                 if (!is_null($params['token'])) {
                     $tokenFunctions = $this->getTokenFunctions();
                     foreach ($params['token'] as $t) {
                         $val = call_user_func($tokenFunctions[$t], $iwUser);
                         if ($val === false) {
                             $this->setWarning("Action '{$t}' is not allowed for the current user");
                         } else {
                             $data[$u][$t . 'token'] = $val;
                         }
                     }
                 }
             } else {
                 $data[$u]['missing'] = true;
                 if (isset($this->prop['cancreate'])) {
                     $status = MediaWiki\Auth\AuthManager::singleton()->canCreateAccount($u);
                     $data[$u]['cancreate'] = $status->isGood();
                     if (!$status->isGood()) {
                         $data[$u]['cancreateerror'] = $this->getErrorFormatter()->arrayFromStatus($status);
                     }
                 }
             }
         } else {
             if (isset($this->prop['groups']) && isset($data[$u]['groups'])) {
                 ApiResult::setArrayType($data[$u]['groups'], 'array');
                 ApiResult::setIndexedTagName($data[$u]['groups'], 'g');
             }
             if (isset($this->prop['implicitgroups']) && isset($data[$u]['implicitgroups'])) {
                 ApiResult::setArrayType($data[$u]['implicitgroups'], 'array');
                 ApiResult::setIndexedTagName($data[$u]['implicitgroups'], 'g');
             }
             if (isset($this->prop['rights']) && isset($data[$u]['rights'])) {
                 ApiResult::setArrayType($data[$u]['rights'], 'array');
                 ApiResult::setIndexedTagName($data[$u]['rights'], 'r');
             }
         }
         $fit = $result->addValue(['query', $this->getModuleName()], null, $data[$u]);
         if (!$fit) {
             $this->setContinueEnumParameter('users', implode('|', array_diff($users, $done)));
             break;
         }
         $done[] = $u;
     }
     $result->addIndexedTagName(['query', $this->getModuleName()], 'user');
 }
Ejemplo n.º 24
0
 /**
  * @covers User::getCanonicalName()
  * @dataProvider provideGetCanonicalName
  */
 public function testGetCanonicalName($name, $expectedArray, $msg)
 {
     foreach ($expectedArray as $validate => $expected) {
         $this->assertEquals($expected, User::getCanonicalName($name, $validate === 'false' ? false : $validate), $msg . ' (' . $validate . ')');
     }
 }
Ejemplo n.º 25
0
 protected function prepareUsername($user)
 {
     if (!$user) {
         $this->dieUsage('User parameter may not be empty', 'param_user');
     }
     $name = User::isIP($user) ? $user : User::getCanonicalName($user, 'valid');
     if ($name === false) {
         $this->dieUsage("User name {$user} is not valid", 'param_user');
     }
     $this->usernames[] = $name;
 }
 /**
  * @param array $data
  * @return Status
  */
 public function onSubmit(array $data)
 {
     $wiki = $this->isGlobalUser() ? null : wfWikiID();
     $reason = isset($data['reason']) ? $data['reason'] : null;
     $safeName = User::getCanonicalName($data['newname'], 'creatable');
     $request = new GlobalRenameRequest();
     $request->setName($this->getUser()->getName());
     $request->setWiki($wiki);
     $request->setNewName($safeName);
     $request->setReason($reason);
     if ($request->save()) {
         $status = Status::newGood();
         if (isset($data['email'])) {
             $user = $this->getUser();
             $user->setEmail($data['email']);
             $user->saveSettings();
             $status = $user->sendConfirmationMail('set');
         }
     } else {
         $status = Status::newFatal($this->msg('globalrenamerequest-save-error'));
     }
     return $status;
 }
Ejemplo n.º 27
0
 /**
  * (Wikia) Validate the 'user' parameter
  * @param string $userName user name
  * @author ADi
  */
 private function prepareUsername($userName)
 {
     if ($userName) {
         $userName = User::getCanonicalName($userName, 'valid');
         if ($userName === false) {
             $this->dieUsage("User name {$userName} is not valid", 'param_user');
         } else {
             $userId = User::idFromName($userName);
             if (empty($userId)) {
                 $this->dieUsage("User name {$userName} not found", 'param_user');
             } else {
                 return $userName;
             }
         }
     } else {
         $this->dieUsage('User parameter may not be empty', 'param_user');
     }
 }
	/**
	 * Checks if the given comment is valid for posting.
	 * @param $comment Comment to validate.
	 * @return False if comment is valid, error message identifier otherwise.
	 */
	protected static function validateComment( WikilogComment &$comment ) {
		global $wgWikilogMaxCommentSize;

		$length = strlen( $comment->mText );

		if ( $length == 0 ) {
			return 'wikilog-comment-is-empty';
		}
		if ( $length > $wgWikilogMaxCommentSize ) {
			return 'wikilog-comment-too-long';
		}

		if ( $comment->mUserID == 0 ) {
			$anonname = User::getCanonicalName( $comment->mAnonName, 'usable' );
			if ( !$anonname ) {
				return 'wikilog-comment-invalid-name';
			}
			$comment->setAnon( $anonname );
		}

		return false;
	}
Ejemplo n.º 29
0
 private function getRbUser()
 {
     if ($this->mUser !== null) {
         return $this->mUser;
     }
     $params = $this->extractRequestParams();
     // We need to be able to revert IPs, but getCanonicalName rejects them
     $this->mUser = User::isIP($params['user']) ? $params['user'] : User::getCanonicalName($params['user']);
     if (!$this->mUser) {
         $this->dieUsageMsg(array('invaliduser', $params['user']));
     }
     return $this->mUser;
 }
Ejemplo n.º 30
0
 public function initValidationUsername()
 {
     // check empty username
     if ($this->mUsername == '') {
         $this->mainLoginForm(wfMsg('userlogin-error-noname'), 'error', 'username');
         return false;
     }
     // check if exist in tempUser
     if (F::build('TempUser', array($this->mUsername), 'getTempUserFromName')) {
         $this->mainLoginForm(wfMsg('userlogin-error-userexists'), 'error', 'username');
         return false;
     }
     // check username length
     if (!User::isNotMaxNameChars($this->mUsername)) {
         global $wgWikiaMaxNameChars;
         $this->mainLoginForm(wfMsg('usersignup-error-username-length', $wgWikiaMaxNameChars), 'error', 'username');
         return false;
     }
     // check valid username
     if (!User::getCanonicalName($this->mUsername, 'creatable')) {
         $this->mainLoginForm(wfMsg('usersignup-error-symbols-in-username'), 'error', 'username');
         return false;
     }
     return true;
 }