public function execute() { if (!class_exists('CentralAuthUser')) { $this->error("CentralAuth isn't enabled on this wiki\n", 1); } $username = $this->getArg(0); $user = User::newFromName($username); if ($user === false) { $this->error("'{$username}' is an invalid username\n", 1); } // Normalize username $username = $user->getName(); if ($user->getId()) { $this->error("User '{$username}' already exists\n", 1); } else { global $wgAuth; $central = CentralAuthUser::getInstance($user); if (!$central->exists()) { $this->error("No such global user: '******'\n", 1); } $user->loadDefaults($username); $user->addToDatabase(); $wgAuth->initUser($user, true); $wgAuth->updateUser($user); # Notify hooks (e.g. Newuserlog) Hooks::run('AuthPluginAutoCreate', array($user)); # Update user count $ssUpdate = new SiteStatsUpdate(0, 0, 0, 0, 1); $ssUpdate->doUpdate(); $this->output("User '{$username}' created\n"); } }
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"); }
function go_auth() { global $wgUser, $wgLanguageCode, $wgRequest, $wgOut; // For a few special pages, don't do anything. $title = $wgRequest->getVal('title'); $lg = Language::factory($wgLanguageCode); if ($title == $lg->specialPage("Userlogout") || $title == $lg->specialPage("Userlogin")) { return true; } $data = go_getsession(); if ($wgUser->IsAnon() || $data && $wgUser->getName() != $data['username']) { if (isset($data['user_id'])) { $wgUser = User::newFromName($data['username']); // Create a new account if the user does not exists if ($wgUser->getID() == 0) { // Create the user $wgUser->addToDatabase(); $wgUser->setRealName($data['username']); //$wgUser->setEmail($data['GO_SESSION']['email']); $wgUser->setPassword(md5($data['username'] . 'zout')); // do something random $wgUser->setToken(); $wgUser->saveSettings(); // Update user count $ssUpdate = new SiteStatsUpdate(0, 0, 0, 0, 1); $ssUpdate->doUpdate(); } $wgUser->setOption("rememberpassword", 1); $wgUser->setCookies(); $wgOut->returnToMain(); } } return true; }
/** * Sets up the messenger account for our use if it hasn't been already. * Based on code from AbuseFilter * https://mediawiki.org/wiki/Extension:AbuseFilter * * @return User */ public static function getMessengerUser() { global $wgMassMessageAccountUsername; // Function kinda copied from the AbuseFilter $user = User::newFromName($wgMassMessageAccountUsername); $user->load(); if ($user->getId() && $user->mPassword == '') { // We've already stolen the account return $user; } if (!$user->getId()) { $user->addToDatabase(); $user->saveSettings(); // Increment site_stats.ss_users $ssu = new SiteStatsUpdate(0, 0, 0, 0, 1); $ssu->doUpdate(); } else { // Someone already created the account, lets take it over. $user->setPassword(null); $user->setEmail(null); $user->saveSettings(); } // Make the user a bot so it doesn't look weird $user->addGroup('bot'); return $user; }
public function execute() { $name = $this->getArg(); $delete = $this->getOption('delete', false); $ns = $this->getOption('ns', NS_MAIN); $dbw = wfGetDB(DB_MASTER); $dbw->begin(); $tbl_pag = $dbw->tableName('page'); $tbl_rec = $dbw->tableName('recentchanges'); $tbl_rev = $dbw->tableName('revision'); # Get page ID $this->output("Searching for \"{$name}\"..."); $title = Title::newFromText($name, $ns); if ($title) { $id = $title->getArticleID(); $real = $title->getPrefixedText(); $isGoodArticle = $title->isContentPage(); $this->output("found \"{$real}\" with ID {$id}.\n"); # Get corresponding revisions $this->output("Searching for revisions..."); $res = $dbw->query("SELECT rev_id FROM {$tbl_rev} WHERE rev_page = {$id}"); $revs = array(); foreach ($res as $row) { $revs[] = $row->rev_id; } $count = count($revs); $this->output("found {$count}.\n"); # Delete the page record and associated recent changes entries if ($delete) { $this->output("Deleting page record..."); $dbw->query("DELETE FROM {$tbl_pag} WHERE page_id = {$id}"); $this->output("done.\n"); $this->output("Cleaning up recent changes..."); $dbw->query("DELETE FROM {$tbl_rec} WHERE rc_cur_id = {$id}"); $this->output("done.\n"); } $dbw->commit(); # Delete revisions as appropriate if ($delete && $count) { $this->output("Deleting revisions..."); $this->deleteRevisions($revs); $this->output("done.\n"); $this->purgeRedundantText(true); } # Update stats as appropriate if ($delete) { $this->output("Updating site stats..."); $ga = $isGoodArticle ? -1 : 0; // if it was good, decrement that too $stats = new SiteStatsUpdate(0, -$count, $ga, -1); $stats->doUpdate(); $this->output("done.\n"); } } else { $this->output("not found in database.\n"); $dbw->commit(); } }
/** * constructor */ function wfSpecialStatistics() { global $wgUser, $wgOut, $wgLang, $wgRequest; $fname = 'wfSpecialStatistics'; $action = $wgRequest->getVal('action'); $dbr =& wfGetDB(DB_SLAVE); extract($dbr->tableNames('page', 'site_stats', 'user', 'user_groups')); $row = $dbr->selectRow('site_stats', '*', false, $fname); $views = $row->ss_total_views; $edits = $row->ss_total_edits; $good = $row->ss_good_articles; # This code is somewhat schema-agnostic, because I'm changing it in a minor release -- TS if (isset($row->ss_total_pages) && $row->ss_total_pages == -1) { # Update schema $u = new SiteStatsUpdate(0, 0, 0); $u->doUpdate(); $row = $dbr->selectRow('site_stats', '*', false, $fname); } if (isset($row->ss_total_pages)) { $total = $row->ss_total_pages; } else { $sql = "SELECT COUNT(page_namespace) AS total FROM {$page}"; $res = $dbr->query($sql, $fname); $pageRow = $dbr->fetchObject($res); $total = $pageRow->total; } if (isset($row->ss_users)) { $users = $row->ss_users; } else { $sql = "SELECT MAX(user_id) AS total FROM {$user}"; $res = $dbr->query($sql, $fname); $userRow = $dbr->fetchObject($res); $users = $userRow->total; } $sql = "SELECT COUNT(*) AS total FROM {$user_groups} WHERE ug_group='sysop'"; $res = $dbr->query($sql, $fname); $row = $dbr->fetchObject($res); $admins = $row->total; if ($action == 'raw') { $wgOut->disable(); header('Pragma: nocache'); echo "total={$total};good={$good};views={$views};edits={$edits};users={$users};admins={$admins}\n"; return; } else { $text = '==' . wfMsg('sitestats') . "==\n"; $text .= wfMsg('sitestatstext', $wgLang->formatNum($total), $wgLang->formatNum($good), $wgLang->formatNum($views), $wgLang->formatNum($edits), $wgLang->formatNum(sprintf('%.2f', $total ? $edits / $total : 0)), $wgLang->formatNum(sprintf('%.2f', $edits ? $views / $edits : 0))); $text .= "\n==" . wfMsg('userstats') . "==\n"; $text .= wfMsg('userstatstext', $wgLang->formatNum($users), $wgLang->formatNum($admins), '[[' . wfMsg('administrators') . ']]', $wgLang->formatNum(sprintf('%.2f', $admins / $users * 100))); $wgOut->addWikiText($text); } }
public static function onOpauthUserAuthorized($provider, $uid, $info, $raw) { global $wgUser, $wgOut; // Called when user was successfully authenticated from Opauth // This function should compare UID with internal storage and decide to create new account for this user // or load existing user from database if (OpauthLogin::isUidLinked($uid, $provider)) { // Login existing user into system $user = OpauthLogin::getUidUser($uid, $provider); wfRunHooks('OpauthLoginUserAuthorized', array($user, $provider, $uid, $info)); } else { // Create new user from external data, $info refers to https://github.com/opauth/opauth/wiki/Auth-response /** * We set UID based string as user name in mediawiki to avoid * user nicknames override and collisions problems. We store external user name into * "real name" field of user object. This should be supported in skin. */ $user = User::newFromName(md5($provider . $uid) . '_' . $uid, false); $user->setRealName($info['name']); if (array_key_exists('email', $info)) { if (!OpauthLogin::isEmailCollate($info['email'])) { $user->setEmail($info['email']); } } $user->setPassword(md5($info['name'] . time())); $user->setToken(); $user->confirmEmail(); // Mark email address as confirmed by default $user->addToDatabase(); // Commit changes to database OpauthLogin::addUidLink($uid, $provider, $user->getId()); // Update site stats $ssUpdate = new SiteStatsUpdate(0, 0, 0, 0, 1); $ssUpdate->doUpdate(); // Run AddNewAccount hook for proper handling wfRunHooks('AddNewAccount', array($user, false)); wfRunHooks('OpauthLoginUserCreated', array($user, $provider, $info, $uid)); } // Replace current user with new one $wgUser = $user; $wgUser->setCookies(null, null, true); if (array_key_exists('opauth_returnto', $_SESSION) && isset($_SESSION['opauth_returnto'])) { $returnToTitle = Title::newFromText($_SESSION['opauth_returnto']); unset($_SESSION['opauth_returnto']); $wgOut->redirect($returnToTitle->getFullURL()); return true; } $wgOut->redirect(Title::newMainPage()->getFullURL()); return true; }
static function load($recache = false) { if (self::$loaded && !$recache) { return; } $dbr =& wfGetDB(DB_SLAVE); self::$row = $dbr->selectRow('site_stats', '*', false, __METHOD__); # This code is somewhat schema-agnostic, because I'm changing it in a minor release -- TS if (!isset(self::$row->ss_total_pages) && self::$row->ss_total_pages == -1) { # Update schema $u = new SiteStatsUpdate(0, 0, 0); $u->doUpdate(); self::$row = $dbr->selectRow('site_stats', '*', false, __METHOD__); } }
public function execute() { $this->output("Refresh Site Statistics\n\n"); $counter = new SiteStatsInit($this->hasOption('use-master')); $this->output("Counting total edits..."); $edits = $counter->edits(); $this->output("{$edits}\nCounting number of articles..."); $good = $counter->articles(); $this->output("{$good}\nCounting total pages..."); $pages = $counter->pages(); $this->output("{$pages}\nCounting number of users..."); $users = $counter->users(); $this->output("{$users}\nCounting number of images..."); $image = $counter->files(); $this->output("{$image}\n"); if (!$this->hasOption('noviews')) { $this->output("Counting total page views..."); $views = $counter->views(); $this->output("{$views}\n"); } if ($this->hasOption('active')) { $this->output("Counting active users..."); $active = SiteStatsUpdate::cacheUpdate(); $this->output("{$active}\n"); } $this->output("\nUpdating site statistics..."); if ($this->hasOption('update')) { $counter->update(); } else { $counter->refresh(); } $this->output("done.\n"); }
public function execute() { $this->output("Refresh Site Statistics\n\n"); $counter = new SiteStatsInit($this->hasOption('use-master')); $this->output("Counting total edits..."); $edits = $counter->edits(); $this->output("{$edits}\nCounting number of articles..."); $good = $counter->articles(); $this->output("{$good}\nCounting total pages..."); $pages = $counter->pages(); $this->output("{$pages}\nCounting number of users..."); $users = $counter->users(); $this->output("{$users}\nCounting number of images..."); $image = $counter->files(); $this->output("{$image}\n"); if ($this->hasOption('update')) { $this->output("\nUpdating site statistics..."); $counter->refresh(); $this->output("done.\n"); } else { $this->output("\nTo update the site statistics table, run the script " . "with the --update option.\n"); } if ($this->hasOption('active')) { $this->output("\nCounting and updating active users..."); $active = SiteStatsUpdate::cacheUpdate($this->getDB(DB_MASTER)); $this->output("{$active}\n"); } $this->output("\nDone.\n"); }
public function execute($par) { global $wgMemc, $wgDisableCounters, $wgMiserMode; $this->setHeaders(); $this->getOutput()->addModuleStyles('mediawiki.special'); $this->views = SiteStats::views(); $this->edits = SiteStats::edits(); $this->good = SiteStats::articles(); $this->images = SiteStats::images(); $this->total = SiteStats::pages(); $this->users = SiteStats::users(); $this->activeUsers = SiteStats::activeUsers(); $this->hook = ''; # Staticic - views $viewsStats = ''; if (!$wgDisableCounters) { $viewsStats = $this->getViewsStats(); } # Set active user count if (!$wgMiserMode) { $key = wfMemcKey('sitestats', 'activeusers-updated'); // Re-calculate the count if the last tally is old... if (!$wgMemc->get($key)) { $dbw = wfGetDB(DB_MASTER); SiteStatsUpdate::cacheUpdate($dbw); $wgMemc->set($key, '1', 24 * 3600); // don't update for 1 day } } $text = Xml::openElement('table', array('class' => 'wikitable mw-statistics-table')); # Statistic - pages $text .= $this->getPageStats(); # Statistic - edits $text .= $this->getEditStats(); # Statistic - users $text .= $this->getUserStats(); # Statistic - usergroups $text .= $this->getGroupStats(); $text .= $viewsStats; # Statistic - popular pages if (!$wgDisableCounters && !$wgMiserMode) { $text .= $this->getMostViewedPages(); } # Statistic - other $extraStats = array(); if (wfRunHooks('SpecialStatsAddExtra', array(&$extraStats))) { $text .= $this->getOtherStats($extraStats); } $text .= Xml::closeElement('table'); #<Wikia> wfRunHooks("CustomSpecialStatistics", array(&$this, &$text)); #</Wikia> # Customizable footer $footer = wfMessage('statistics-footer'); if (!$footer->isBlank()) { $text .= "\n" . $footer->parse(); } $this->getOutput()->addHTML($text); }
public function execute($par) { global $wgOut, $wgMemc; global $wgDisableCounters, $wgMiserMode; $this->setHeaders(); $this->views = SiteStats::views(); $this->edits = SiteStats::edits(); $this->good = SiteStats::articles(); $this->images = SiteStats::images(); $this->total = SiteStats::pages(); $this->users = SiteStats::users(); $this->activeUsers = SiteStats::activeUsers(); $this->admins = SiteStats::numberingroup('sysop'); $this->hook = ''; # Staticic - views $viewsStats = ''; if (!$wgDisableCounters) { $viewsStats = $this->getViewsStats(); } # Set active user count if (!$wgMiserMode) { $key = wfMemcKey('sitestats', 'activeusers-updated'); // Re-calculate the count if the last tally is old... if (!$wgMemc->get($key)) { $dbw = wfGetDB(DB_MASTER); SiteStatsUpdate::cacheUpdate($dbw); $wgMemc->set($key, '1', 24 * 3600); // don't update for 1 day } } $text = Xml::openElement('table', array('class' => 'wikitable mw-statistics-table')); # Statistic - pages $text .= $this->getPageStats(); # Statistic - edits $text .= $this->getEditStats(); # Statistic - users $text .= $this->getUserStats(); # Statistic - usergroups $text .= $this->getGroupStats(); $text .= $viewsStats; # Statistic - popular pages if (!$wgDisableCounters && !$wgMiserMode) { $text .= $this->getMostViewedPages(); } # Statistic - other $extraStats = array(); if (wfRunHooks('SpecialStatsAddExtra', array(&$extraStats))) { $text .= $this->getOtherStats($extraStats); } $text .= Xml::closeElement('table'); # Customizable footer $footer = wfMsgExt('statistics-footer', array('parseinline')); if (!wfEmptyMsg('statistics-footer', $footer) && $footer != '') { $text .= "\n" . $footer; } $wgOut->addHTML($text); }
public function execute($par) { global $wgOut, $wgRequest, $wgMessageCache; global $wgDisableCounters, $wgMiserMode; $wgMessageCache->loadAllMessages(); $this->setHeaders(); $this->views = SiteStats::views(); $this->edits = SiteStats::edits(); $this->good = SiteStats::articles(); $this->images = SiteStats::images(); $this->total = SiteStats::pages(); $this->users = SiteStats::users(); $this->activeUsers = SiteStats::activeUsers(); $this->admins = SiteStats::numberingroup('sysop'); $this->numJobs = SiteStats::jobs(); # Staticic - views $viewsStats = ''; if (!$wgDisableCounters) { $viewsStats = $this->getViewsStats(); } # Set active user count if (!$wgMiserMode) { $dbw = wfGetDB(DB_MASTER); SiteStatsUpdate::cacheUpdate($dbw); } # Do raw output if ($wgRequest->getVal('action') == 'raw') { $this->doRawOutput(); } $text = Xml::openElement('table', array('class' => 'mw-statistics-table')); # Statistic - pages $text .= $this->getPageStats(); # Statistic - edits $text .= $this->getEditStats(); # Statistic - users $text .= $this->getUserStats(); # Statistic - usergroups $text .= $this->getGroupStats(); $text .= $viewsStats; # Statistic - popular pages if (!$wgDisableCounters && !$wgMiserMode) { $text .= $this->getMostViewedPages(); } $text .= Xml::closeElement('table'); # Customizable footer $footer = wfMsgExt('statistics-footer', array('parseinline')); if (!wfEmptyMsg('statistics-footer', $footer) && $footer != '') { $text .= "\n" . $footer; } $wgOut->addHTML($text); }
/** * @param $user User * @param $mungedUsername String * @return bool */ public static function attemptAddUser($user, $mungedUsername) { /** * @var $wgAuth LdapAuthenticationPlugin */ global $wgAuth; if (!$wgAuth->autoCreate()) { $wgAuth->printDebug("Cannot automatically create accounts.", NONSENSITIVE); return false; } $wgAuth->printDebug("User does not exist in local database; creating.", NONSENSITIVE); // Checks passed, create the user $user->loadDefaults($mungedUsername); $user->addToDatabase(); $wgAuth->initUser($user, true); $user->setCookies(); wfSetupSession(); # Update user count $ssUpdate = new SiteStatsUpdate(0, 0, 0, 0, 1); $ssUpdate->doUpdate(); # Notify hooks (e.g. Newuserlog) wfRunHooks('AuthPluginAutoCreate', array($user)); return true; }
public function execute($par) { global $wgMemc; $miserMode = $this->getConfig()->get('MiserMode'); $this->setHeaders(); $this->getOutput()->addModuleStyles('mediawiki.special'); $this->edits = SiteStats::edits(); $this->good = SiteStats::articles(); $this->images = SiteStats::images(); $this->total = SiteStats::pages(); $this->users = SiteStats::users(); $this->activeUsers = SiteStats::activeUsers(); $this->hook = ''; # Set active user count if (!$miserMode) { $key = wfMemcKey('sitestats', 'activeusers-updated'); // Re-calculate the count if the last tally is old... if (!$wgMemc->get($key)) { $dbw = wfGetDB(DB_MASTER); SiteStatsUpdate::cacheUpdate($dbw); $wgMemc->set($key, '1', 24 * 3600); // don't update for 1 day } } $text = Xml::openElement('table', array('class' => 'wikitable mw-statistics-table')); # Statistic - pages $text .= $this->getPageStats(); # Statistic - edits $text .= $this->getEditStats(); # Statistic - users $text .= $this->getUserStats(); # Statistic - usergroups $text .= $this->getGroupStats(); # Statistic - other $extraStats = array(); if (Hooks::run('SpecialStatsAddExtra', array(&$extraStats, $this->getContext()))) { $text .= $this->getOtherStats($extraStats); } $text .= Xml::closeElement('table'); # Customizable footer $footer = $this->msg('statistics-footer'); if (!$footer->isBlank()) { $text .= "\n" . $footer->parse(); } $this->getOutput()->addHTML($text); }
protected function acceptRequest(IContextSource $context) { global $wgAuth, $wgAccountRequestTypes, $wgConfirmAccountSaveInfo; global $wgAllowAccountRequestFiles, $wgConfirmAccountFSRepos; $accReq = $this->accountReq; // convenience # Now create user and check if the name is valid $user = User::newFromName($this->userName, 'creatable'); if (!$user) { return array('accountconf_invalid_name', wfMsgHtml('noname')); } # Check if account name is already in use if (0 != $user->idForName() || $wgAuth->userExists($user->getName())) { return array('accountconf_user_exists', wfMsgHtml('userexists')); } $dbw = wfGetDB(DB_MASTER); $dbw->begin(); # Make a random password $p = User::randomPassword(); # Insert the new user into the DB... $tokenExpires = $accReq->getEmailTokenExpires(); $authenticated = $accReq->getEmailAuthTimestamp(); $params = array('real_name' => $accReq->getRealName(), 'newpassword' => User::crypt($p), 'email' => $accReq->getEmail(), 'email_authenticated' => $dbw->timestampOrNull($authenticated), 'email_token_expires' => $dbw->timestamp($tokenExpires), 'email_token' => $accReq->getEmailToken()); $user = User::createNew($user->getName(), $params); # Grant any necessary rights (exclude blank or dummy groups) $group = self::getGroupFromType($this->type); if ($group != '' && $group != 'user' && $group != '*') { $user->addGroup($group); } $acd_id = null; // used for rollback cleanup # Save account request data to credentials system if ($wgConfirmAccountSaveInfo) { $key = $accReq->getFileStorageKey(); # Copy any attached files to new storage group if ($wgAllowAccountRequestFiles && $key) { $repoOld = new FSRepo($wgConfirmAccountFSRepos['accountreqs']); $repoNew = new FSRepo($wgConfirmAccountFSRepos['accountcreds']); $pathRel = UserAccountRequest::relPathFromKey($key); $oldPath = $repoOld->getZonePath('public') . '/' . $pathRel; $triplet = array($oldPath, 'public', $pathRel); $status = $repoNew->storeBatch(array($triplet)); // copy! if (!$status->isOK()) { $dbw->rollback(); # DELETE new rows in case there was a COMMIT somewhere $this->acceptRequest_rollback($dbw, $user->getId(), $acd_id); return array('accountconf_copyfailed', $context->getOutput()->parse($status->getWikiText())); } } $acd_id = $dbw->nextSequenceValue('account_credentials_acd_id_seq'); # Move request data into a separate table $dbw->insert('account_credentials', array('acd_user_id' => $user->getID(), 'acd_real_name' => $accReq->getRealName(), 'acd_email' => $accReq->getEmail(), 'acd_email_authenticated' => $dbw->timestampOrNull($authenticated), 'acd_bio' => $accReq->getBio(), 'acd_notes' => $accReq->getNotes(), 'acd_urls' => $accReq->getUrls(), 'acd_ip' => $accReq->getIP(), 'acd_filename' => $accReq->getFileName(), 'acd_storage_key' => $accReq->getFileStorageKey(), 'acd_areas' => $accReq->getAreas('flat'), 'acd_registration' => $dbw->timestamp($accReq->getRegistration()), 'acd_accepted' => $dbw->timestamp(), 'acd_user' => $this->admin->getID(), 'acd_comment' => $this->reason, 'acd_id' => $acd_id), __METHOD__); if (is_null($acd_id)) { $acd_id = $dbw->insertId(); // set $acd_id to ID inserted } } # Add to global user login system (if there is one) if (!$wgAuth->addUser($user, $p, $accReq->getEmail(), $accReq->getRealName())) { $dbw->rollback(); # DELETE new rows in case there was a COMMIT somewhere $this->acceptRequest_rollback($dbw, $user->getId(), $acd_id); return array('accountconf_externaldberror', wfMsgHtml('externaldberror')); } # OK, now remove the request from the queue $accReq->remove(); # Commit this if we make past the CentralAuth system # and the groups are added. Next step is sending out an # email, which we cannot take back... $dbw->commit(); # Prepare a temporary password email... if ($this->reason != '') { $msg = "confirmaccount-email-body2-pos{$this->type}"; # If the user is in a group and there is a welcome for that group, use it if ($group && !wfEmptyMsg($msg)) { $ebody = wfMsgExt($msg, array('parsemag', 'content'), $user->getName(), $p, $this->reason); # Use standard if none found... } else { $ebody = wfMsgExt('confirmaccount-email-body2', array('parsemag', 'content'), $user->getName(), $p, $this->reason); } } else { $msg = "confirmaccount-email-body-pos{$this->type}"; # If the user is in a group and there is a welcome for that group, use it if ($group && !wfEmptyMsg($msg)) { $ebody = wfMsgExt($msg, array('parsemag', 'content'), $user->getName(), $p, $this->reason); # Use standard if none found... } else { $ebody = wfMsgExt('confirmaccount-email-body', array('parsemag', 'content'), $user->getName(), $p, $this->reason); } } # Actually send out the email (@TODO: rollback on failure including $wgAuth) $result = $user->sendMail(wfMsgForContent('confirmaccount-email-subj'), $ebody); /* if ( !$result->isOk() ) { # DELETE new rows in case there was a COMMIT somewhere $this->acceptRequest_rollback( $dbw, $user->getId(), $acd_id ); return array( 'accountconf_mailerror', wfMsg( 'mailerror', $context->getOutput()->parse( $result->getWikiText() ) ) ); } */ # Update user count $ssUpdate = new SiteStatsUpdate(0, 0, 0, 0, 1); $ssUpdate->doUpdate(); # Safe to hook/log now... wfRunHooks('AddNewAccount', array($user, false)); $user->addNewUserLogEntry(); # Clear cache for notice of how many account requests there are ConfirmAccount::clearAccountRequestCountCache(); # Delete any attached file and don't stop the whole process if this fails if ($wgAllowAccountRequestFiles) { $key = $accReq->getFileStorageKey(); if ($key) { $repoOld = new FSRepo($wgConfirmAccountFSRepos['accountreqs']); $pathRel = UserAccountRequest::relPathFromKey($key); $oldPath = $repoOld->getZonePath('public') . '/' . $pathRel; if (file_exists($oldPath)) { unlink($oldPath); // delete! } } } # Start up the user's userpages if set to do so. # Will not append, so previous content will be blanked. $this->createUserPage($user); # Greet the new user if set to do so. $this->createUserTalkPage($user); return array(true, null); }
/** * @return User */ public static function getFilterUser() { $user = User::newFromName(wfMessage('abusefilter-blocker')->inContentLanguage()->text()); $user->load(); if ($user->getId() && $user->mPassword == '') { // Already set up. return $user; } // Not set up. Create it. if (!$user->getId()) { print 'Trying to create account -- user id is ' . $user->getId(); $user->addToDatabase(); $user->saveSettings(); // Increment site_stats.ss_users $ssu = new SiteStatsUpdate(0, 0, 0, 0, 1); $ssu->doUpdate(); } else { // Take over the account $user->setPassword(null); $user->setEmail(null); $user->saveSettings(); } // Promote user so it doesn't look too crazy. $user->addGroup('sysop'); return $user; }
/** * Run the transaction, except the cleanup batch. * The cleanup batch should be run in a separate transaction, because it locks different * rows and there's no need to keep the image row locked while it's acquiring those locks * The caller may have its own transaction open. * So we save the batch and let the caller call cleanup() * @return FileRepoStatus */ function execute() { global $wgLang; if (!$this->all && !$this->ids) { // Do nothing return $this->file->repo->newGood(); } $exists = $this->file->lock(); $dbw = $this->file->repo->getMasterDB(); $status = $this->file->repo->newGood(); // Fetch all or selected archived revisions for the file, // sorted from the most recent to the oldest. $conditions = array('fa_name' => $this->file->getName()); if (!$this->all) { $conditions['fa_id'] = $this->ids; } $result = $dbw->select('filearchive', ArchivedFile::selectFields(), $conditions, __METHOD__, array('ORDER BY' => 'fa_timestamp DESC')); $idsPresent = array(); $storeBatch = array(); $insertBatch = array(); $insertCurrent = false; $deleteIds = array(); $first = true; $archiveNames = array(); foreach ($result as $row) { $idsPresent[] = $row->fa_id; if ($row->fa_name != $this->file->getName()) { $status->error('undelete-filename-mismatch', $wgLang->timeanddate($row->fa_timestamp)); $status->failCount++; continue; } if ($row->fa_storage_key == '') { // Revision was missing pre-deletion $status->error('undelete-bad-store-key', $wgLang->timeanddate($row->fa_timestamp)); $status->failCount++; continue; } $deletedRel = $this->file->repo->getDeletedHashPath($row->fa_storage_key) . $row->fa_storage_key; $deletedUrl = $this->file->repo->getVirtualUrl() . '/deleted/' . $deletedRel; if (isset($row->fa_sha1)) { $sha1 = $row->fa_sha1; } else { // old row, populate from key $sha1 = LocalRepo::getHashFromKey($row->fa_storage_key); } # Fix leading zero if (strlen($sha1) == 32 && $sha1[0] == '0') { $sha1 = substr($sha1, 1); } if (is_null($row->fa_major_mime) || $row->fa_major_mime == 'unknown' || is_null($row->fa_minor_mime) || $row->fa_minor_mime == 'unknown' || is_null($row->fa_media_type) || $row->fa_media_type == 'UNKNOWN' || is_null($row->fa_metadata)) { // Refresh our metadata // Required for a new current revision; nice for older ones too. :) $props = RepoGroup::singleton()->getFileProps($deletedUrl); } else { $props = array('minor_mime' => $row->fa_minor_mime, 'major_mime' => $row->fa_major_mime, 'media_type' => $row->fa_media_type, 'metadata' => $row->fa_metadata); } if ($first && !$exists) { // This revision will be published as the new current version $destRel = $this->file->getRel(); $insertCurrent = array('img_name' => $row->fa_name, 'img_size' => $row->fa_size, 'img_width' => $row->fa_width, 'img_height' => $row->fa_height, 'img_metadata' => $props['metadata'], 'img_bits' => $row->fa_bits, 'img_media_type' => $props['media_type'], 'img_major_mime' => $props['major_mime'], 'img_minor_mime' => $props['minor_mime'], 'img_description' => $row->fa_description, 'img_user' => $row->fa_user, 'img_user_text' => $row->fa_user_text, 'img_timestamp' => $row->fa_timestamp, 'img_sha1' => $sha1); // The live (current) version cannot be hidden! if (!$this->unsuppress && $row->fa_deleted) { $status->fatal('undeleterevdel'); $this->file->unlock(); return $status; } } else { $archiveName = $row->fa_archive_name; if ($archiveName == '') { // This was originally a current version; we // have to devise a new archive name for it. // Format is <timestamp of archiving>!<name> $timestamp = wfTimestamp(TS_UNIX, $row->fa_deleted_timestamp); do { $archiveName = wfTimestamp(TS_MW, $timestamp) . '!' . $row->fa_name; $timestamp++; } while (isset($archiveNames[$archiveName])); } $archiveNames[$archiveName] = true; $destRel = $this->file->getArchiveRel($archiveName); $insertBatch[] = array('oi_name' => $row->fa_name, 'oi_archive_name' => $archiveName, 'oi_size' => $row->fa_size, 'oi_width' => $row->fa_width, 'oi_height' => $row->fa_height, 'oi_bits' => $row->fa_bits, 'oi_description' => $row->fa_description, 'oi_user' => $row->fa_user, 'oi_user_text' => $row->fa_user_text, 'oi_timestamp' => $row->fa_timestamp, 'oi_metadata' => $props['metadata'], 'oi_media_type' => $props['media_type'], 'oi_major_mime' => $props['major_mime'], 'oi_minor_mime' => $props['minor_mime'], 'oi_deleted' => $this->unsuppress ? 0 : $row->fa_deleted, 'oi_sha1' => $sha1); } $deleteIds[] = $row->fa_id; if (!$this->unsuppress && $row->fa_deleted & File::DELETED_FILE) { // private files can stay where they are $status->successCount++; } else { $storeBatch[] = array($deletedUrl, 'public', $destRel); $this->cleanupBatch[] = $row->fa_storage_key; } $first = false; } unset($result); // Add a warning to the status object for missing IDs $missingIds = array_diff($this->ids, $idsPresent); foreach ($missingIds as $id) { $status->error('undelete-missing-filearchive', $id); } // Remove missing files from batch, so we don't get errors when undeleting them $storeBatch = $this->removeNonexistentFiles($storeBatch); // Run the store batch // Use the OVERWRITE_SAME flag to smooth over a common error $storeStatus = $this->file->repo->storeBatch($storeBatch, FileRepo::OVERWRITE_SAME); $status->merge($storeStatus); if (!$status->isGood()) { // Even if some files could be copied, fail entirely as that is the // easiest thing to do without data loss $this->cleanupFailedBatch($storeStatus, $storeBatch); $status->ok = false; $this->file->unlock(); return $status; } // Run the DB updates // Because we have locked the image row, key conflicts should be rare. // If they do occur, we can roll back the transaction at this time with // no data loss, but leaving unregistered files scattered throughout the // public zone. // This is not ideal, which is why it's important to lock the image row. if ($insertCurrent) { $dbw->insert('image', $insertCurrent, __METHOD__); } if ($insertBatch) { $dbw->insert('oldimage', $insertBatch, __METHOD__); } if ($deleteIds) { $dbw->delete('filearchive', array('fa_id' => $deleteIds), __METHOD__); } // If store batch is empty (all files are missing), deletion is to be considered successful if ($status->successCount > 0 || !$storeBatch) { if (!$exists) { wfDebug(__METHOD__ . " restored {$status->successCount} items, creating a new current\n"); DeferredUpdates::addUpdate(SiteStatsUpdate::factory(array('images' => 1))); $this->file->purgeEverything(); } else { wfDebug(__METHOD__ . " restored {$status->successCount} as archived versions\n"); $this->file->purgeDescription(); $this->file->purgeHistory(); } } $this->file->unlock(); return $status; }
/** * @private */ function addNewAccountInternal() { global $wgUser, $wgOut; global $wgEnableSorbs, $wgProxyWhitelist; global $wgMemc, $wgAccountCreationThrottle; global $wgAuth, $wgMinimalPasswordLength; // If the user passes an invalid domain, something is fishy if (!$wgAuth->validDomain($this->mDomain)) { $this->mainLoginForm(wfMsg('wrongpassword')); return false; } // If we are not allowing users to login locally, we should // be checking to see if the user is actually able to // authenticate to the authentication server before they // create an account (otherwise, they can create a local account // and login as any domain user). We only need to check this for // domains that aren't local. if ('local' != $this->mDomain && '' != $this->mDomain) { if (!$wgAuth->canCreateAccounts() && (!$wgAuth->userExists($this->mName) || !$wgAuth->authenticate($this->mName, $this->mPassword))) { $this->mainLoginForm(wfMsg('wrongpassword')); return false; } } if (wfReadOnly()) { $wgOut->readOnlyPage(); return false; } if (!$wgUser->isAllowedToCreateAccount()) { $this->userNotPrivilegedMessage(); return false; } $ip = wfGetIP(); if ($wgEnableSorbs && !in_array($ip, $wgProxyWhitelist) && $wgUser->inSorbsBlacklist($ip)) { $this->mainLoginForm(wfMsg('sorbs_create_account_reason') . ' (' . htmlspecialchars($ip) . ')'); return; } $name = trim($this->mName); $u = User::newFromName($name, 'creatable'); if (is_null($u)) { $this->mainLoginForm(wfMsg('noname')); return false; } if (0 != $u->idForName()) { $this->mainLoginForm(wfMsg('userexists')); return false; } if (0 != strcmp($this->mPassword, $this->mRetype)) { $this->mainLoginForm(wfMsg('badretype')); return false; } if (!$wgUser->isValidPassword($this->mPassword)) { $this->mainLoginForm(wfMsg('passwordtooshort', $wgMinimalPasswordLength)); return false; } $abortError = ''; if (!wfRunHooks('AbortNewAccount', array($u, &$abortError))) { // Hook point to add extra creation throttles and blocks wfDebug("LoginForm::addNewAccountInternal: a hook blocked creation\n"); $this->mainLoginForm($abortError); return false; } if ($wgAccountCreationThrottle) { $key = wfMemcKey('acctcreate', 'ip', $ip); $value = $wgMemc->incr($key); if (!$value) { $wgMemc->set($key, 1, 86400); } if ($value > $wgAccountCreationThrottle) { $this->throttleHit($wgAccountCreationThrottle); return false; } } if (!$wgAuth->addUser($u, $this->mPassword)) { $this->mainLoginForm(wfMsg('externaldberror')); return false; } # Update user count $ssUpdate = new SiteStatsUpdate(0, 0, 0, 0, 1); $ssUpdate->doUpdate(); return $this->initUser($u); }
/** * Actually add a user to the database. * Give it a User object that has been initialised with a name. * * This is a custom version of similar code in SpecialUserLogin's LoginForm with differences * due to the fact that this code doesn't require a password, etc. * * @param $u User object. * @param $autocreate boolean -- true if this is an autocreation via auth plugin * @return User object. * @private */ function initUser($u, $autocreate) { global $wgAuth, $wgExternalAuthType; if ($wgExternalAuthType) { $u = ExternalUser::addUser($u, $this->mPassword, $this->mEmail, $this->mRealName); if (is_object($u)) { $this->mExtUser = ExternalUser::newFromName($this->mName); } } else { $u->addToDatabase(); } // No passwords for FBConnect accounts //if ( $wgAuth->allowPasswordChange() ) { // $u->setPassword( $this->mPassword ); //} $u->setEmail($this->mEmail); $u->setRealName($this->mRealName); $u->setToken(); $wgAuth->initUser($u, $autocreate); if (is_object($this->mExtUser)) { $this->mExtUser->linkToLocal($u->getId()); $email = $this->mExtUser->getPref('emailaddress'); if ($email && !$this->mEmail) { $u->setEmail($email); } } //$u->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 ); $u->setOption('marketingallowed', $this->mMarketingOptIn ? 1 : 0); $u->setOption('skinoverwrite', 1); $u->saveSettings(); # Update user count $ssUpdate = new SiteStatsUpdate(0, 0, 0, 0, 1); $ssUpdate->doUpdate(); return $u; }
/** * Actually add a user to the database. * Give it a User object that has been initialised with a name. * * @param $u User object. * @param $autocreate boolean -- true if this is an autocreation via auth plugin * @return User object. * @private */ function initUser($u, $autocreate) { global $wgAuth; $u->addToDatabase(); if ($wgAuth->allowPasswordChange()) { $u->setPassword($this->mPassword); } $u->setEmail($this->mEmail); $u->setRealName($this->mRealName); $u->setToken(); $wgAuth->initUser($u, $autocreate); $u->setOption('rememberpassword', $this->mRemember ? 1 : 0); $u->saveSettings(); # Update user count $ssUpdate = new SiteStatsUpdate(0, 0, 0, 0, 1); $ssUpdate->doUpdate(); return $u; }
private function userSignup() { // Get user input and check the environment $this->mUserDataChecker->run(); // Throw if data getting or environment checks have failed which indicates that account creation is impossible $checker_error = $this->mUserDataChecker->getError(); if ( $checker_error ) { throw new Exception( $checker_error ); } $user = $this->mUserDataChecker->mUser; $user->setEmail( $this->mUserDataChecker->mEmail ); $user->setRealName( $this->mUserDataChecker->mRealname ); $abortError = ''; if ( !wfRunHooks( 'AbortNewAccount', array( $user, &$abortError ) ) ) { // Hook point to add extra creation throttles and blocks wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" ); throw new Exception( $abortError ); } global $wgAccountCreationThrottle; global $wgUser, $wgRequest; if ( $wgAccountCreationThrottle && $wgUser->isPingLimitable() ) { $key = wfMemcKey( 'acctcreate', 'ip', $wgRequest->getIP() ); $value = $wgMemc->incr( $key ); if ( !$value ) { $wgMemc->set( $key, 1, 86400 ); } if ( $value > $wgAccountCreationThrottle ) { throw new Exception( wfMsg( 'ses-throttlehit' ) ); } } global $wgAuth; $addedUser = $wgAuth->addUser( $user, $this->mUserDataChecker->mPassword, $this->mUserDataChecker->mEmail, $this->mUserDataChecker->mRealname ); if ( !$addedUser ) { throw new Exception( 'externaldberror' ); } $user->addToDatabase(); if ( $wgAuth->allowPasswordChange() ) { $user->setPassword( $this->mUserDataChecker->mPassword ); } $user->setToken(); $wgAuth->initUser( $user, false ); $user->setOption( 'rememberpassword', $this->mUserDataChecker->mRemember ? 1 : 0 ); $user->saveSettings(); # Update user count $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 ); $ssUpdate->doUpdate(); global $wgLoginLanguageSelector; $language = $this->mUserDataChecker->mLanguage; if ( $wgLoginLanguageSelector && $language ) { $user->setOption( 'language', $language ); } global $wgEmailAuthentication; if ( $wgEmailAuthentication && User::isValidEmailAddr( $user->getEmail() ) ) { $status = $user->sendConfirmationMail(); if ( !$status->isGood() ) { throw new Exception( wfMsg( 'ses-emailfailed' ) . "\n" . $status->getMessage() ); } } $user->saveSettings(); wfRunHooks( 'AddNewAccount', array( $user ) ); }
* @author Rob Church <*****@*****.**> */ #ubuntu specific directory: require_once '/var/www/wiki/maintenance/commandLine.inc'; if (!count($args) == 2) { echo "Please provide a username and password for the new account.\n"; die(1); } $username = $args[0]; $password = $args[1]; echo wfWikiID() . ": Creating wiki User:{$username}..."; # Validate username and check it doesn't exist $user = User::newFromName($username); if (!is_object($user)) { echo "invalid username.\n"; die(1); } elseif (0 != $user->idForName()) { echo "Wiki account exists.\n"; die(0); } # Insert the account into the database $user->addToDatabase(); $user->setPassword($password); $user->setToken(); #this may be readded as an option but probably not # Promote user #$user->addGroup( 'sysop' ); # Increment site_stats.ss_users $ssu = new SiteStatsUpdate(0, 0, 0, 0, 1); $ssu->doUpdate(); echo "done.\n";
function casLogin($user, &$result) { global $CASAuth; global $casIsSetUp; global $IP, $wgLanguageCode, $wgRequest, $wgOut; if (isset($_REQUEST["title"])) { $lg = Language::factory($wgLanguageCode); if ($_REQUEST["title"] == $lg->specialPage("Userlogin")) { // Setup for a web request require_once "{$IP}/includes/WebStart.php"; // Load phpCAS require_once $CASAuth["phpCAS"] . "/CAS.php"; if (!$casIsSetUp) { return false; } //Will redirect to CAS server if not logged in phpCAS::forceAuthentication(); // Get username $username = casNameLookup(phpCAS::getUser()); $email = casEmailLookup(phpCAS::getUser()); // If we are restricting users AND the user is not in // the allowed users list, lets block the login if ($CASAuth["RestrictUsers"] == true && !in_array($username, $CASAuth["AllowedUsers"])) { // redirect user to the RestrictRedirect page $wgOut->redirect($CASAuth["RestrictRedirect"]); return true; } // Get MediaWiki user $u = User::newFromName($username); // Create a new account if the user does not exists if ($u->getID() == 0 && $CASAuth["CreateAccounts"]) { // Create the user $u->addToDatabase(); $u->setRealName($username); $u->setEmail($email); // PwdSecret is used to salt the username for an hmac // hash which becomes the password $u->setPassword(hash_hmac('sha256', $username, $CASAuth["PwdSecret"])); $u->setToken(); $u->saveSettings(); // Update user count $ssUpdate = new SiteStatsUpdate(0, 0, 0, 0, 1); $ssUpdate->doUpdate(); } // Login successful if ($CASAuth["RememberMe"]) { $u->setOption("rememberpassword", 1); } $u->setCookies(); $user = $u; // Redirect if a returnto parameter exists $returnto = $wgRequest->getVal("returnto"); if ($returnto) { $target = Title::newFromText($returnto); if ($target) { //action=purge is used to purge the cache $wgOut->redirect($target->getFullUrl('action=purge')); } } } else { if ($_REQUEST["title"] == $lg->specialPage("Userlogout")) { // Logout casLogout(); } } } // Back to MediaWiki home after login return true; }
function executeScript($type) { global $wgOut, $wgRequest, $wgUser; wfLoadExtensionMessages('Maintenance'); @set_time_limit(0); //if we can, disable the time limit $this->setHeaders(); $wgOut->addHTML($wgUser->getSkin()->makeKnownLinkObj($this->getTitle(), wfMsgHtml('maintenance-backlink')) . '<br />'); switch ($type) { case 'changePassword': $name = $wgRequest->getText('wpName'); $password = $wgRequest->getText('wpPassword'); $user = User::newFromName($name); if (!is_object($user) || !$user->getId()) { $wgOut->addWikiMsg('maintenance-invalidname'); return; } $dbw = wfGetDB(DB_MASTER); $user->setPassword($password); $user->saveSettings(); $wgOut->addWikiMsg('maintenance-success', $type); break; case 'createAndPromote': $name = $wgRequest->getText('wpName'); $password = $wgRequest->getText('wpPassword'); $bcrat = $wgRequest->getCheck('wpBcrat'); $user = User::newFromName($name); if (!is_object($user)) { $wgOut->addWikiMsg('maintenance-invalidname'); return; } elseif (0 != $user->idForName()) { $wgOut->addWikiMsg('maintenance-userexists'); return; } $user->addToDatabase(); $user->setPassword($password); $user->saveSettings(); $user->addGroup('sysop'); if ($bcrat) { $user->addGroup('bureaucrat'); } $ssu = new SiteStatsUpdate(0, 0, 0, 0, 1); $ssu->doUpdate(); $wgOut->addWikiMsg('maintenance-success', $type); break; case 'deleteBatch': $reason = $wgRequest->getText('wpReason', ''); $interval = 0; $pages = $wgRequest->getText('wpDelete'); $dbw = wfGetDB(DB_MASTER); $lines = explode("\n", $pages); foreach ($lines as &$line) { $line = trim($line); if ($line == '') { continue; } $page = Title::newFromText($line); if (is_null($page)) { $wgOut->addWikiMsg('maintenance-invalidtitle', $line); continue; } if (!$page->exists()) { $wgOut->addWikiMsg('maintenance-titlenoexist', $line); continue; } $return = '* ' . $page->getPrefixedText(); // Switch the user here from the current user to Delete page script $OldUser = $wgUser; $wgUser = User::newFromName('Delete page script'); // Begin transaction $dbw->begin(); if ($page->getNamespace() == NS_IMAGE) { $art = new ImagePage($page); $img = wfFindFile($art->mTitle); if (!$img || !$img->delete($reason)) { $return .= '... ' . wfMsg('maintenance-failed'); } } else { $art = new Article($page); } $success = $art->doDeleteArticle($reason); // Commit changes to the database $dbw->commit(); // ...and switch user back to the old user $wgUser = $OldUser; if ($success) { $return .= '... ' . wfMsg('maintenance-deleted'); } else { $return .= '... ' . wfMsg('maintenance-failed'); } $wgOut->addWikiText($return); waitForSlaves(5); } $wgOut->addWikiMsg('maintenance-success', $type); break; case 'deleteRevision': $delete = $wgRequest->getText('wpDelete'); $revisions = explode("\n", $delete); $wgOut->addWikiMsg('maintenance-revdelete', implode(', ', $revisions), wfWikiID()); $affected = 0; // Switch the user here from the current user to Delete page script $OldUser = $wgUser; $wgUser = User::newFromName('Delete page script'); $dbw = wfGetDB(DB_MASTER); foreach ($revisions as $revID) { $dbw->insertSelect('archive', array('page', 'revision'), array('ar_namespace' => 'page_namespace', 'ar_title' => 'page_title', 'ar_comment' => 'rev_comment', 'ar_user' => 'rev_user', 'ar_user_text' => 'rev_user_text', 'ar_timestamp' => 'rev_timestamp', 'ar_minor_edit' => 'rev_minor_edit', 'ar_rev_id' => 'rev_id', 'ar_text_id' => 'rev_text_id'), array('rev_id' => $revID, 'page_id = rev_page'), __METHOD__); if (!$dbw->affectedRows()) { $wgOut->addWikiMsg('maintenance-revnotfound', array($revID)); } else { $affected += $dbw->affectedRows(); $dbw->delete('revision', array('rev_id' => $revID)); } } // ...and switch user back to the old user $wgUser = $OldUser; $wgOut->addWikiMsg('maintenance-success', $type); break; case 'purgeDeletedText': # Data should come off the master, wrapped in a transaction $dbw = wfGetDB(DB_MASTER); $dbw->begin(); # compute table names $tbl_arc = $dbw->tableName('archive'); $tbl_rev = $dbw->tableName('revision'); $tbl_txt = $dbw->tableName('text'); # Delete as appropriate $dbw->query("TRUNCATE TABLE {$tbl_arc}"); // list of "valid" text ids $new_ids = array(); $new_start = 0; // list of "existing" text ids $old_ids = array(); $old_start = 0; // index id $id = 1; // list of ids to be deleted $del_ids = array(); while ($id > 0 && count($del_ids) < 1000) { // get some new "valid" text ids if (count($new_ids) == 0) { $res = $dbw->query("SELECT DISTINCTROW rev_text_id FROM {$tbl_rev} ORDER BY rev_text_id ASC LIMIT {$new_start},100"); while ($row = $dbw->fetchObject($res)) { $new_ids[$row->rev_text_id] = $row->rev_text_id; } if (count($new_ids) == 0) { $id = 0; } else { $new_start += count($new_ids); } } // get some new "existing" text ids if (count($old_ids) == 0) { $res = $dbw->query("SELECT DISTINCTROW old_id FROM {$tbl_txt} ORDER BY old_id ASC LIMIT {$old_start},100"); while ($row = $dbw->fetchObject($res)) { $old_ids[$row->old_id] = $row->old_id; } if (count($old_ids) == 0) { $id = 0; } else { $old_start += count($old_ids); } } // for all ids, check that existing ids are valid while (count($new_ids) > 0 && count($old_ids) > 0) { if (isset($new_ids[$id])) { unset($new_ids[$id]); } else { if (isset($old_ids[$id])) { $del_ids[] = $id; } } unset($old_ids[$id]); $id += 1; } } // print result foreach ($del_ids as $del_id) { $wgOut->addHTML(strval($del_id) . '<br/>'); } // delete rows if (count($del_ids) > 0) { $set = implode(', ', $del_ids); $dbw->query("DELETE FROM {$tbl_txt} WHERE old_id IN ( {$set} )"); } // this solution consummes too much memory //# Get "active" text records from the revisions table //$res = $dbw->query( "SELECT DISTINCTROW rev_text_id FROM $tbl_rev" ); //while( $row = $dbw->fetchObject( $res ) ) { // $cur[] = $row->rev_text_id; //} //# Get the IDs of all text records not in these sets //$set = implode( ', ', $cur ); //$res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" ); //$old = array(); //while( $row = $dbw->fetchObject( $res ) ) { // $old[] = $row->old_id; //} //$count = count( $old ); //# Delete as appropriate //if( $count ) { // $set = implode( ', ', $old ); // $dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" ); //} // this solution is too slow //$res = $dbw->query( "SELECT DISTINCTROW old_id FROM $tbl_txt WHERE NOT EXISTS (SELECT * FROM $tbl_rev WHERE $tbl_rev.rev_text_id = $tbl_txt.old_id)" ); //while( $row = $dbw->fetchObject( $res ) ) { // $old_id = $row->old_id; // $wgOut->addHTML( strval($old_id).'<br/>' ); //} # done $dbw->commit(); $wgOut->addWikiMsg('maintenance-success', $type); break; case 'eval': $temp = error_reporting(E_ALL); ob_start(); $str = eval($wgRequest->getText('wpCode', 'return;')); $ext = ob_get_clean(); error_reporting(0); if ($ext) { $wgOut->addHTML(nl2br($ext) . '<hr />'); } if (!$str) { // do nothing } elseif (is_string($str)) { $wgOut->addHTML(nl2br($str) . '<hr />'); } else { $wgOut->addHTML(nl2br(var_export($str, true)) . '<hr />'); } $wgOut->addWikiMsg('maintenance-success', $type); break; case 'initEditCount': global $wgDBservers; $dbw = wfGetDB(DB_MASTER); $user = $dbw->tableName('user'); $revision = $dbw->tableName('revision'); $dbver = $dbw->getServerVersion(); $dbr = wfGetDB(DB_SLAVE); $chunkSize = 100; $lastUser = $dbr->selectField('user', 'MAX(user_id)', '', __FUNCTION__); $start = microtime(true); $migrated = 0; for ($min = 0; $min <= $lastUser; $min += $chunkSize) { $max = $min + $chunkSize; $result = $dbr->query("SELECT\r\n\t\t\t\t\t\t\tuser_id,\r\n\t\t\t\t\t\t\tCOUNT(rev_user) AS user_editcount\r\n\t\t\t\t\t\tFROM {$user}\r\n\t\t\t\t\t\tLEFT OUTER JOIN {$revision} ON user_id=rev_user\r\n\t\t\t\t\t\tWHERE user_id > {$min} AND user_id <= {$max}\r\n\t\t\t\t\t\tGROUP BY user_id", 'initEditCount'); while ($row = $dbr->fetchObject($result)) { $dbw->update('user', array('user_editcount' => $row->user_editcount), array('user_id' => $row->user_id), 'initEditCount'); ++$migrated; } $dbr->freeResult($result); waitForSlaves(10); } $wgOut->addWikiMsg('maintenance-success', $type); break; case 'initStats': $dbr = wfGetDB(DB_SLAVE); $edits = $dbr->selectField('revision', 'COUNT(*)', '', __METHOD__); $edits += $dbr->selectField('archive', 'COUNT(*)', '', __METHOD__); $wgOut->addWikiMsg('maintenance-stats-edits', $edits); global $wgContentNamespaces; $good = $dbr->selectField('page', 'COUNT(*)', array('page_namespace' => $wgContentNamespaces, 'page_is_redirect' => 0, 'page_len > 0'), __METHOD__); $wgOut->addWikiMsg('maintenance-stats-articles', $good); $pages = $dbr->selectField('page', 'COUNT(*)', '', __METHOD__); $wgOut->addWikiMsg('maintenance-stats-pages', $pages); $users = $dbr->selectField('user', 'COUNT(*)', '', __METHOD__); $wgOut->addWikiMsg('maintenance-stats-users', $users); $admin = $dbr->selectField('user_groups', 'COUNT(*)', array('ug_group' => 'sysop'), __METHOD__); $wgOut->addWikiMsg('maintenance-stats-admins', $admin); $image = $dbr->selectField('image', 'COUNT(*)', '', __METHOD__); $wgOut->addWikiMsg('maintenance-stats-images', $image); if (!$wgRequest->getCheck('wpNoview')) { $views = $dbr->selectField('page', 'SUM(page_counter)', '', __METHOD__); $wgOut->addWikiMsg('maintenance-stats-views', $views); } $wgOut->addWikiMsg('maintenance-stats-update'); $dbw = wfGetDB(DB_MASTER); $values = array('ss_total_edits' => $edits, 'ss_good_articles' => $good, 'ss_total_pages' => $pages, 'ss_users' => $users, 'ss_admins' => $admin, 'ss_images' => $image); $conds = array('ss_row_id' => 1); $views = array('ss_total_views' => isset($views) ? $views : 0); if ($wgRequest->getCheck('wpUpdate')) { $dbw->update('site_stats', $values, $conds, __METHOD__); } else { $dbw->delete('site_stats', $conds, __METHOD__); $dbw->insert('site_stats', array_merge($values, $conds, $views), __METHOD__); } $wgOut->addWikiMsg('maintenance-success', $type); break; case 'moveBatch': $reason = $wgRequest->getText('wpReason', ''); $interval = 0; $pages = $wgRequest->getText('wpMove'); $dbw = wfGetDB(DB_MASTER); $lines = explode("\n", $pages); foreach ($lines as $line) { $parts = array_map('trim', explode('|', $line)); if (count($parts) != 2) { continue; } $source = Title::newFromText($parts[0]); $dest = Title::newFromText($parts[1]); if (is_null($source) || is_null($dest)) { continue; } $wgOut->addWikiText('* ' . wfMsg('maintenance-move', array($source->getPrefixedText(), $dest->getPrefixedText()))); $dbw->begin(); $err = $source->moveTo($dest, false, $reason); if ($err !== true) { $wgOut->addWikiText('** ' . wfMsg('maintenance-movefail', array($err))); } $dbw->commit(); waitForSlaves(5); } $wgOut->addWikiMsg('maintenance-success', $type); break; case 'reassignEdits': $wpFrom = $wgRequest->getVal('wpFrom'); $wpTo = $wgRequest->getVal('wpTo'); if (User::isIP($wpFrom)) { $from = new User(); $from->setId(0); $from->setName($wpFrom); } else { $from = User::newFromName($wpFrom); } if (User::isIP($wpTo)) { $to = new User(); $to->setId(0); $to->setName($wpTo); } else { $to = User::newFromName($wpTo); } if ($to->getId() || $wgRequest->getCheck('wpForce')) { $report = $wgRequest->getCheck('wpReport'); $dbw = wfGetDB(DB_MASTER); $dbw->immediateBegin(); $rcond = $from->getId() ? array('rev_user' => $from->getId()) : array('rev_user_text' => $from->getName()); $res = $dbw->select('revision', 'COUNT(*) AS count', $rcond, 'Maintenance::reassignEdits'); $row = $dbw->fetchObject($res); $cur = $row->count; $wgOut->addWikiMsg('maintenance-re-ce', $cur); $acond = $from->getId() ? array('ar_user' => $from->getId()) : array('ar_user_text' => $from->getName()); $res = $dbw->select('archive', 'COUNT(*) AS count', $acond, 'Maintenance::reassignEdits'); $row = $dbw->fetchObject($res); $del = $row->count; $wgOut->addWikiMsg('maintenance-re-de', $del); if (!$wgRequest->getCheck('wpRc')) { $ccond = $from->getId() ? array('rc_user' => $from->getId()) : array('rc_user_text' => $from->getName()); $res = $dbw->select('recentchanges', 'COUNT(*) AS count', $ccond, 'Maintenance::reassignEdits'); $row = $dbw->fetchObject($res); $rec = $row->count; $wgOut->addWikiMsg('maintenance-re-rce', $rec); } else { $rec = 0; } $total = $cur + $del + $rec; $wgOut->addWikiMsg('maintenance-re-total', $total); if (!$report) { $rspec = array('rev_user' => $to->getId(), 'rev_user_text' => $to->getName()); $res = $dbw->update('revision', $rspec, $rcond, 'Maintenance::reassignEdits'); $aspec = array('ar_user' => $to->getId(), 'ar_user_text' => $to->getName()); $res = $dbw->update('archive', $aspec, $acond, 'Maintenance::reassignEdits'); if (!$wgRequest->getCheck('wpRc')) { $cspec = array('rc_user' => $to->getId(), 'rc_user_text' => $to->getName()); $res = $dbw->update('recentchanges', $cspec, $ccond, 'Maintenance::reassignEdits'); } } $dbw->immediateCommit(); if ($report) { $wgOut->addWikiMsg('maintenance-re-rr', wfMsg('maintenance-re-report')); } } else { $ton = $to->getName(); $wgOut->addWikiMsg('maintenance-re-nf', $ton); } $wgOut->addWikiMsg('maintenance-success', $type); break; case 'runJobs': $maxJobs = 10000; $dbw = wfGetDB(DB_MASTER); $n = 0; while ($dbw->selectField('job', 'count(*)', '', 'runJobs.php')) { $offset = 0; for (;;) { $job = Job::pop($offset); if ($job == false) { break; } waitForSlaves(5); $wgOut->addWikiText("* " . $job->id . " " . $job->toString()); $offset = $job->id; if (!$job->run()) { $wgOut->addWikiText("** " . wfMsg('maintenance-error', array($job->error))); } if ($maxJobs && ++$n > $maxJobs) { break 2; } } } $wgOut->addWikiMsg('maintenance-success', $type); break; case 'showJobs': $dbw = wfGetDB(DB_MASTER); $count = $dbw->selectField('job', 'count(*)', '', 'runJobs.php'); $wgOut->addHTML($count); $wgOut->addWikiMsg('maintenance-success', $type); break; case 'stats': global $wgMemc; if (get_class($wgMemc) == 'FakeMemCachedClient') { $wgOut->addWikiMsg('maintenance-memc-fake'); return; } $wgOut->addWikiText('<h2>' . wfMsg('maintenance-memc-requests') . '</h2>'); $session = intval($wgMemc->get(wfMemcKey('stats', 'request_with_session'))); $noSession = intval($wgMemc->get(wfMemcKey('stats', 'request_without_session'))); $total = $session + $noSession; $requests = sprintf(wfMsg('maintenance-memc-withsession') . " %-10d %6.2f%%\n", $session, $session / $total * 100) . '<br />'; $requests .= sprintf(wfMsg('maintenance-memc-withoutsession') . " %-10d %6.2f%%\n", $noSession, $noSession / $total * 100) . '<br />'; $requests .= sprintf(wfMsg('maintenance-memc-total') . " %-10d %6.2f%%\n", $total, 100) . '<br />'; $wgOut->addWikiText($requests); $wgOut->addWikiText('<h2>' . wfMsg('maintenance-memc-parsercache') . '</h2>'); $hits = intval($wgMemc->get(wfMemcKey('stats', 'pcache_hit'))); $invalid = intval($wgMemc->get(wfMemcKey('stats', 'pcache_miss_invalid'))); $expired = intval($wgMemc->get(wfMemcKey('stats', 'pcache_miss_expired'))); $absent = intval($wgMemc->get(wfMemcKey('stats', 'pcache_miss_absent'))); $stub = intval($wgMemc->get(wfMemcKey('stats', 'pcache_miss_stub'))); $total = $hits + $invalid + $expired + $absent + $stub; $pcache = sprintf(wfMsg('maintenance-memc-hits') . " %-10d %6.2f%%\n", $hits, $hits / $total * 100) . '<br />'; $pcache .= sprintf(wfMsg('maintenance-memc-invalid') . " %-10d %6.2f%%\n", $invalid, $invalid / $total * 100) . '<br />'; $pcache .= sprintf(wfMsg('maintenance-memc-expired') . " %-10d %6.2f%%\n", $expired, $expired / $total * 100) . '<br />'; $pcache .= sprintf(wfMsg('maintenance-memc-absent') . " %-10d %6.2f%%\n", $absent, $absent / $total * 100) . '<br />'; $pcache .= sprintf(wfMsg('maintenance-memc-stub') . " %-10d %6.2f%%\n", $stub, $stub / $total * 100) . '<br />'; $pcache .= sprintf(wfMsg('maintenance-memc-total') . " %-10d %6.2f%%\n", $total, 100) . '<br />'; $wgOut->addWikiText($pcache); $hits = intval($wgMemc->get(wfMemcKey('stats', 'image_cache_hit'))); $misses = intval($wgMemc->get(wfMemcKey('stats', 'image_cache_miss'))); $updates = intval($wgMemc->get(wfMemcKey('stats', 'image_cache_update'))); $total = $hits + $misses; $wgOut->addWikiText('<h2>' . wfMsg('maintenance-memc-imagecache') . '</h2>'); $icache = sprintf(wfMsg('maintenance-memc-hits') . " %-10d %6.2f%%\n", $hits, $hits / $total * 100) . '<br />'; $icache .= sprintf(wfMsg('maintenance-memc-misses') . " %-10d %6.2f%%\n", $misses, $misses / $total * 100) . '<br />'; $icache .= sprintf(wfMsg('maintenance-memc-updates') . " %-10d\n", $updates) . '<br />'; $wgOut->addWikiText($icache); $hits = intval($wgMemc->get(wfMemcKey('stats', 'diff_cache_hit'))); $misses = intval($wgMemc->get(wfMemcKey('stats', 'diff_cache_miss'))); $uncacheable = intval($wgMemc->get(wfMemcKey('stats', 'diff_uncacheable'))); $total = $hits + $misses + $uncacheable; $wgOut->addWikiText('<h2>' . wfMsg('maintenance-memc-diffcache') . '</h2>'); $dcache = sprintf(wfMsg('maintenance-memc-hits') . " %-10d %6.2f%%\n", $hits, $hits / $total * 100) . '<br />'; $dcache .= sprintf(wfMsg('maintenance-memc-misses') . " %-10d %6.2f%%\n", $misses, $misses / $total * 100) . '<br />'; $dcache .= sprintf(wfMsg('maintenance-memc-uncacheable') . " %-10d %6.2f%%\n", $uncacheable, $uncacheable / $total * 100) . '<br />'; $wgOut->addWikiText($dcache); $wgOut->addWikiMsg('maintenance-success', $type); break; case 'sql': $db = wfGetDB(DB_MASTER); $q = $wgRequest->getText('wpQuery', ''); $db->begin(); try { $r = $db->query($q, 'Maintenance::sql.php'); } catch (DBQueryError $e) { global $wgShowSQLErrors; $temp = $wgShowSQLErrors; $wgShowSQLErrors = true; $wgOut->addWikiText('<pre style="overflow: auto">' . $e->getText() . '</pre>'); $wgShowSQLErrors = $temp; $r = false; } if ($r === true) { $wgOut->addWikiMsg('maintenance-sql-aff', $db->affectedRows()); } elseif ($r instanceof ResultWrapper) { $res = array(); for ($i = 0; $i < $r->numRows(); $i++) { $row = $r->fetchRow(); $res[] = $row; foreach ($row as $key => $meh) { $names[] = $key; } } $names = array_unique($names); $rtable = '<table class="wikitable"><tr>'; foreach ($names as $name) { if (is_numeric($name)) { continue; } $rtable .= '<th>' . $name . '</th>'; } $rtable .= '</tr>'; foreach ($res as $data) { $rtable .= '<tr>'; foreach ($data as $key => $value) { if (is_numeric($key)) { continue; } $rtable .= '<td><nowiki>' . $value . '</nowiki></td>'; } $rtable .= '</tr>'; } $rtable .= '</table>'; $wgOut->addWikiMsg('maintenance-sql-res', $r->numRows(), $rtable); $db->freeResult($r); } $db->commit(); $wgOut->addWikiMsg('maintenance-success', $type); break; default: $wgOut->addWikiMsg('maintenance-invalidtype'); return; } }
function execute($par) { global $wgUser, $wgOut, $wgLang, $wgTitle, $wgMemc, $wgDBname, $wgScriptPath; global $wgRequest, $wgSitename, $wgLanguageCode; global $wgScript; $fname = "wfSpecialEmailLink"; if ($wgRequest->getVal('fromajax')) { $wgOut->setArticleBodyOnly(true); } $this->setHeaders(); $me = Title::makeTitle(NS_SPECIAL, "EmailLink"); $action = $me->getFullURL(); $fc = new FancyCaptcha(); $pass_captcha = true; $name = $from = $r1 = $r2 = $r3 = $m = ""; if ($wgRequest->wasPosted()) { $pass_captcha = $fc->passCaptcha(); $email = $wgRequest->getVal("email"); $name = $wgRequest->getVal("name"); $recipient1 = $wgRequest->getVal('recipient1'); $recipient2 = $wgRequest->getVal('recipient2'); $recipient3 = $wgRequest->getVal('recipient3'); if (preg_match("@kittens683\\@aol.com@", $recipient1) || preg_match("@kittens683\\@aol.com@", $recipient2) || preg_match("@kittens683\\@aol.com@", $recipient3)) { return; } $message = $wgRequest->getVal('message'); } if (!$wgRequest->wasPosted() || !$pass_captcha) { if ($wgUser->getID() > 0 && !$wgUser->canSendEmail()) { $userEmail = $wgUser->getEmail(); // If there is no verification time stamp and no email on record, show initial message to have a user input a valid email address if (empty($userEmail)) { wfDebug("User can't send.\n"); $wgOut->errorpage("mailnologin", "mailnologintext"); } else { // When user does have an email on record, but has not verified it yet wfDebug("User can't send without verification.\n"); $wgOut->errorpage("mailnologin", "mailnotverified"); } return; } $titleKey = isset($par) ? $par : $wgRequest->getVal('target'); if ($titleKey == "") { $wgOut->addHTML("<br/></br><font color=red>" . wfMsg('error-no-title') . "</font>"); return; } $titleObj = Title::newFromURL($titleKey); if (!$titleObj) { $titleObj = Title::newFromURL(urldecode($titleKey)); } if (!$titleObj || $titleObj->getArticleID() < 0) { $wgOut->addHTML("<br/></br><font color=red>" . wfMsg('error-article-not-found') . "</font>"); return; } else { $titleKey = $titleObj->getDBKey(); } $articleObj = new Article($titleObj); $subject = $titleObj->getText(); $titleText = $titleObj->getText(); if (WikihowArticleEditor::articleIsWikiHow($articleObj)) { $subject = wfMsg('howto', $subject); $titleText = wfMsg('howto', $titleText); } $subject = wfMsg('wikihow-article-subject', $subject); if ($titleObj->getText() == wfMsg('mainpage')) { $subject = wfMsg('wikihow-article-subject-main-page'); } // add the form HTML $article_title = wfMsg('article') . ":"; if ($titleObj->getNamespace() == NS_ARTICLE_REQUEST) { $wgOut->addHTML("<br/><br/>" . wfMsg('know-someone-answer-topic-request')); $article_title = wfMsg('topic-requested') . ":"; } if ($titleObj->getNamespace() != NS_MAIN && $titleObj->getNamespace() != NS_ARTICLE_REQUEST && $titleObj->getNamespace() != NS_PROJECT) { $wgOut->errorPage('emaillink', 'emaillink_invalidpage'); return; } if ($titleObj->getText() == "Books For Africa") { $message = wfMsg('friend-sends-article-email-africa-body'); } $titleKey = urlencode($titleKey); $token = $this->getToken1(); $wgOut->addHTML("\n<link type='text/css' rel='stylesheet' href='" . wfGetPad('/extensions/wikihow/common/jquery-ui-themes/jquery-ui.css?rev=' . WH_SITEREV) . "' />\n<form id=\"emaillink\" method=\"post\" action=\"{$action}\">\n<input type=\"hidden\" name=\"target\" value=\"{$titleKey}\">\n<input type=\"hidden\" name=\"token\" value=\"{$token}\">\n<table border=\"0\">\n<tr>\n<td valign=\"top\" colspan=\"1\" class='mw-label'>{$article_title}</td>\n<td valign=\"top\" colspan=\"2\">{$titleText}</td>\n</tr>\n"); if ($wgUser->getID() <= 0) { $wgOut->addHTML("\n<tr>\n<td valign=\"top\" colspan=\"1\" class='mw-label'>" . wfMsg('your-name') . ":</td>\n<td valign=\"top\" colspan=\"2\"><input type=text size=\"40\" name=\"name\" value=\"{$name}\" class='input_med'></td>\n</tr>\n<tr>\n<td valign=\"top\" colspan=\"1\" class='mw-label'>" . wfMsg('your-email') . ":</td>\n<td valign=\"top\" colspan=\"2\"><input type=text size=\"40\" name=\"email\" value=\"{$email}\" class='input_med'></td>\n</tr>"); } $wgOut->addHTML("\n<tr>\n<td valign=\"top\" width=\"300px\" colspan=\"1\" rowspan='3' class='mw-label'>" . wfMsg('recipient-emails') . ":</td>\n<td valign=\"top\" colspan=\"2\"><input type=text size=\"40\" name=\"recipient1\" value=\"{$recipient1}\" class='input_med'></td>\n</tr>\n<tr>\n<td valign=\"top\" colspan=\"2\"><input type=text size=\"40\" name=\"recipient2\" value=\"{$recipient2}\" class='input_med'></td>\n</tr>\n<tr>\n<td valign=\"top\" colspan=\"2\"><input type=text size=\"40\" name=\"recipient3\" value=\"{$recipient3}\" class='input_med'></td>\n</tr>\n<!--<tr>\n<td valign=\"top\" colspan=\"1\">" . wfMsg('emailsubject') . ":</td>\n<td valign=\"top\" colspan=\"2\"><input type=text size=\"40\" name=\"subject\" value=\"{$subject}\" class='input_med'></td>\n</tr>-->\n<tr>\n<td colspan=\"1\" valign=\"top\" class='mw-label'>" . wfMsg('emailmessage') . ":</td>\n<td colspan=\"2\"><TEXTAREA rows=\"5\" cols=\"55\" name=\"message\">{$message}</TEXTAREA></td>\n</tr>\n<tr>\n<TD> </TD>\n<TD colspan=\"2\"><br/>\n" . wfMsgWikiHTML('emaillink_captcha') . "\n" . ($pass_captcha ? "" : "<br><br/><font color='red'>Sorry, that phrase was incorrect, try again.</font><br/><br/>") . "\n" . $fc->getForm('') . "\n</TD>\n</tr>\n<tr>\n<TD> </TD>\n<TD colspan=\"2\"><br/>\n<input type='submit' name=\"wpEmaiLinkSubmit\" value=\"" . wfMsg('submit') . "\" class=\"button primary\" />\n</td>\n</tr>\n<tr>\n<TD colspan=\"3\">\n<br/><br/>\n" . wfMsg('share-message-three-friends') . "\n</TD>\n</TR>\n\n"); // do this if the user isn't logged in $wgOut->addHTML("</table> </form>"); } else { if ($wgUser->pingLimiter('emailfriend')) { $wgOut->rateLimited(); wfProfileOut("{$fname}-checks"); wfProfileOut($fname); return false; } $usertoken = $wgRequest->getVal('token'); $token1 = $this->getToken1(); $token2 = $this->getToken2(); if ($usertoken != $token1 && $usertoken != $token2) { $this->reject(); echo "token {$usertoken} {$token1} {$token2}\n"; exit; return; } // check referrer $good_referer = Title::makeTitle(NS_SPECIAL, "EmailLink")->getFullURL(); $referer = $_SERVER["HTTP_REFERER"]; if (strpos($refer, $good_referer) != 0) { $this->reject(); echo "referrer bad\n"; exit; } // this is a post, accept the POST data and create the Request article $recipient1 = $_POST['recipient1']; $recipient2 = $_POST['recipient2']; $recipient3 = $_POST['recipient3']; $titleKey = $_POST['target']; $message = $_POST['message']; if ($titleKey == "Books-For-Africa") { $titleKey = "wikiHow:" . $titleKey; } $titleKey = urldecode($titleKey); $titleObj = Title::newFromDBKey($titleKey); if ($titleObj->getArticleID() <= 0) { $this->reject(); echo "no article id\n"; exit; } $dbkey = $titleObj->getDBKey(); $articleObj = new Article($titleObj); $subject = $titleObj->getText(); $how_to = $subject; if (WikihowArticleEditor::articleIsWikiHow($articleObj)) { $subject = wfMsg("howto", $subject); } $how_to = $subject; if ($titleObj->getNamespace() == NS_ARTICLE_REQUEST) { $subject = wfMsg('subject-requested-howto') . ": " . wfMsg("howto", $subject); } else { if ($titleObj->getNamespace() == NS_PROJECT) { $subject = wfMsg('friend-sends-article-email-africa-subject'); } else { $subject = wfMsg('wikihow-article-subject', $subject); } } if ($titleObj->getNamespace() != NS_MAIN && $titleObj->getNamespace() != NS_ARTICLE_REQUEST && $titleObj->getNamespace() != NS_PROJECT) { $wgOut->errorPage('emaillink', 'emaillink_invalidpage'); return; } // for the body of the email $titleText = $titleObj->getText(); if ($titleText != wfMsg('mainpage')) { $summary = Article::getSection($articleObj->getContent(true), 0); // trip out all MW and HTML tags $summary = ereg_replace("<.*>", "", $summary); $summary = ereg_replace("\\[\\[.*\\]\\]", "", $summary); $summary = ereg_replace("\\{\\{.*\\}\\}", "", $summary); } $url = $titleObj->getFullURL(); $from_name = ""; $validEmail = ""; if ($wgUser->getID() > 0) { $from_name = $wgUser->getName(); $real_name = $wgUser->getRealName(); if ($real_name != "") { $from_name = $real_name; } $email = $wgUser->getEmail(); if ($email != "") { $validEmail = $email; $from_name .= "<{$email}>"; } else { $from_name .= "<*****@*****.**>"; } } else { $email = $wgRequest->getVal("email"); $name = $wgRequest->getVal("name"); if ($email == "") { $email = "*****@*****.**"; } else { $validEmail = $email; } $from_name = "{$name} <{$email}>"; } if (strpos($email, "\n") !== false || strpos($recipient1, "\n") !== false || strpos($recipient2, "\n") !== false || strpos($recipient3, "\n") !== false || strpos($title, "\n") !== false) { echo "reciep\n"; exit; $this->reject(); return; } $r_array = array(); $num_recipients = 0; if ($recipient1 != "") { $num_recipients++; $x = split(";", $recipient1); $r_array[] = $x[0]; } if ($recipient2 != "") { $num_recipients++; $x = split(";", $recipient2); $r_array[] = $x[0]; } if ($recipient3 != "") { $num_recipients++; $x = split(";", $recipient3); $r_array[] = $x[0]; } if ($titleObj->getNamespace() == NS_PROJECT) { $r_array[] = '*****@*****.**'; } if ($validEmail != "" && !in_array($validEmail, $r_array)) { $num_recipients++; $r_array[] = $validEmail; } if ($titleObj->getNamespace() == NS_ARTICLE_REQUEST) { $body = "{$message}\n\n----------------\n\n\t" . wfMsg('article-request-email', $how_to, "http://www.wikihow.com/index.php?title2={$dbkey}&action=easy&requested={$dbkey}", "http://www.wikihow.com/Request:{$dbkey}", "http://www.wikihow.com/" . wfMsg('writers-guide-url'), "http://www.wikihow.com/" . wfMsg('about-wikihow-url') . ""); } else { if ($titleObj->getText() == wfMsg('mainpage')) { $body = "{$message}\n\n----------------\n\n\t" . wfMsg('friend-sends-article-email-main-page') . "\n\n\t"; } else { if ($titleObj->getNamespace() == NS_PROJECT) { $body = "{$message}"; } else { $body = "{$message}\n\n----------------\n\n" . wfMsg('friend-sends-article-email', $how_to, $summary, $url) . "\n\n\t"; } } } $from = new MailAddress($email); foreach ($r_array as $address) { $address = preg_replace("@,.*@", "", $address); $to = new MailAddress($address); $sbody = $body; if ($address == $validEmail) { $sbody = wfMsg('copy-email-from-yourself') . "\n\n" . $sbody; } if (!userMailer($to, $from, $subject, $sbody, false)) { //echo "got an en error\n"; } } SiteStatsUpdate::addLinksEmailed($num_recipients); $this->thanks(); } }
/** * Do all updates and commit them. More or less a replacement * for the original initStats, but without output. * * @param $database DatabaseBase|bool * - Boolean: whether to use the master DB * - DatabaseBase: database connection to use * @param array $options of options, may contain the following values * - update Boolean: whether to update the current stats (true) or write fresh (false) (default: false) * - views Boolean: when true, do not update the number of page views (default: true) * - activeUsers Boolean: whether to update the number of active users (default: false) */ public static function doAllAndCommit($database, array $options = array()) { $options += array('update' => false, 'views' => true, 'activeUsers' => false); // Grab the object and count everything $counter = new SiteStatsInit($database); $counter->edits(); $counter->articles(); $counter->pages(); $counter->users(); $counter->files(); // Only do views if we don't want to not count them if ($options['views']) { $counter->views(); } // Update/refresh if ($options['update']) { $counter->update(); } else { $counter->refresh(); } // Count active users if need be if ($options['activeUsers']) { SiteStatsUpdate::cacheUpdate(wfGetDB(DB_MASTER)); } }
/** * Mostly for hook use * @param Title $title * @param ForeignTitle $foreignTitle * @param int $revCount * @param int $sRevCount * @param array $pageInfo * @return bool */ public function finishImportPage($title, $foreignTitle, $revCount, $sRevCount, $pageInfo) { // Update article count statistics (T42009) // The normal counting logic in WikiPage->doEditUpdates() is designed for // one-revision-at-a-time editing, not bulk imports. In this situation it // suffers from issues of slave lag. We let WikiPage handle the total page // and revision count, and we implement our own custom logic for the // article (content page) count. $page = WikiPage::factory($title); $page->loadPageData('fromdbmaster'); $content = $page->getContent(); if ($content === null) { wfDebug(__METHOD__ . ': Skipping article count adjustment for ' . $title . ' because WikiPage::getContent() returned null'); } else { $editInfo = $page->prepareContentForEdit($content); $countKey = 'title_' . $title->getPrefixedText(); $countable = $page->isCountable($editInfo); if (array_key_exists($countKey, $this->countableCache) && $countable != $this->countableCache[$countKey]) { DeferredUpdates::addUpdate(SiteStatsUpdate::factory(array('articles' => (int) $countable - (int) $this->countableCache[$countKey]))); } } $args = func_get_args(); return Hooks::run('AfterImportPage', $args); }
/** * Create the first user account, grant it sysop and bureaucrat rights * * @return Status */ protected function createSysop() { $name = $this->getVar('_AdminName'); $user = User::newFromName($name); if (!$user) { // We should've validated this earlier anyway! return Status::newFatal('config-admin-error-user', $name); } if ($user->idForName() == 0) { $user->addToDatabase(); try { $user->setPassword($this->getVar('_AdminPassword')); } catch (PasswordError $pwe) { return Status::newFatal('config-admin-error-password', $name, $pwe->getMessage()); } $user->addGroup('sysop'); $user->addGroup('bureaucrat'); if ($this->getVar('_AdminEmail')) { $user->setEmail($this->getVar('_AdminEmail')); } $user->saveSettings(); // Update user count $ssUpdate = new SiteStatsUpdate(0, 0, 0, 0, 1); $ssUpdate->doUpdate(); } $status = Status::newGood(); if ($this->getVar('_Subscribe') && $this->getVar('_AdminEmail')) { $this->subscribeToMediaWikiAnnounce($status); } return $status; }
/** * Actually add a user to the database. * Give it a User object that has been initialised with a name. * * @param $tempUser User object. * @param $autocreate boolean -- true if this is an autocreation via auth plugin * @return User object. * @private */ function initUser( $tempUser, $autocreate = false ) { global $wgAuth; $tempUser->addToDatabase(); if ( $wgAuth->allowPasswordChange() ) { $tempUser->setPassword( $this->mPassword ); } $tempUser->setEmail( $this->mEmail ); $tempUser->setRealName( $this->mRealName ); $tempUser->setToken(); $wgAuth->initUser( $tempUser, $autocreate ); if ( $this->mExtUser ) { $this->mExtUser->linkToLocal( $tempUser->getId() ); $email = $this->mExtUser->getPref( 'emailaddress' ); if ( $email && !$this->mEmail ) { $tempUser->setEmail( $email ); } } $tempUser->setOption( 'rememberpassword', $this->mRemember ? 1 : 0 ); $tempUser->saveSettings(); # Update user count $ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 ); $ssUpdate->doUpdate(); $this->addToSourceTracking( $tempUser ); return $tempUser; }