protected function setUp()
 {
     parent::setUp();
     $langObj = Language::factory('en');
     $localZone = 'UTC';
     $localOffset = date('Z') / 60;
     $this->setMwGlobals(array('wgMemc' => new EmptyBagOStuff(), 'wgContLang' => $langObj, 'wgLang' => $langObj, 'wgLocaltimezone' => $localZone, 'wgLocalTZoffset' => $localOffset, 'wgNamespaceProtection' => array(NS_MEDIAWIKI => 'editinterface')));
     $this->userName = '******';
     $this->altUserName = '******';
     date_default_timezone_set($localZone);
     $this->title = Title::makeTitle(NS_MAIN, "Main Page");
     if (!isset($this->userUser) || !$this->userUser instanceof User) {
         $this->userUser = User::newFromName($this->userName);
         if (!$this->userUser->getID()) {
             $this->userUser = User::createNew($this->userName, array("email" => "*****@*****.**", "real_name" => "Test User"));
             $this->userUser->load();
         }
         $this->altUser = User::newFromName($this->altUserName);
         if (!$this->altUser->getID()) {
             $this->altUser = User::createNew($this->altUserName, array("email" => "*****@*****.**", "real_name" => "Test User Alt"));
             $this->altUser->load();
         }
         $this->anonUser = User::newFromId(0);
         $this->user = $this->userUser;
     }
 }
 function setUp()
 {
     global $wgLocaltimezone, $wgLocalTZoffset, $wgMemc, $wgContLang, $wgLang;
     parent::setUp();
     if (!$wgMemc) {
         $wgMemc = new EmptyBagOStuff();
     }
     $wgContLang = $wgLang = Language::factory('en');
     $this->userName = "******";
     $this->altUserName = "******";
     date_default_timezone_set($wgLocaltimezone);
     $wgLocalTZoffset = date("Z") / 60;
     $this->title = Title::makeTitle(NS_MAIN, "Main Page");
     if (!isset($this->userUser) || !$this->userUser instanceof User) {
         $this->userUser = User::newFromName($this->userName);
         if (!$this->userUser->getID()) {
             $this->userUser = User::createNew($this->userName, array("email" => "*****@*****.**", "real_name" => "Test User"));
             $this->userUser->load();
         }
         $this->altUser = User::newFromName($this->altUserName);
         if (!$this->altUser->getID()) {
             $this->altUser = User::createNew($this->altUserName, array("email" => "*****@*****.**", "real_name" => "Test User Alt"));
             $this->altUser->load();
         }
         $this->anonUser = User::newFromId(0);
         $this->user = $this->userUser;
     }
 }
Example #3
0
 public function __construct($username, $realname = 'Real Name', $email = '*****@*****.**', $groups = array())
 {
     $this->assertNotReal();
     $this->username = $username;
     $this->password = '******';
     $this->user = User::newFromName($this->username);
     $this->user->load();
     // In an ideal world we'd have a new wiki (or mock data store) for every single test.
     // But for now, we just need to create or update the user with the desired properties.
     // we particularly need the new password, since we just generated it randomly.
     // In core MediaWiki, there is no functionality to delete users, so this is the best we can do.
     if (!$this->user->isLoggedIn()) {
         // create the user
         $this->user = User::createNew($this->username, array("email" => $email, "real_name" => $realname));
         if (!$this->user) {
             throw new MWException("Error creating TestUser " . $username);
         }
     }
     // Update the user to use the password and other details
     $change = $this->setPassword($this->password) || $this->setEmail($email) || $this->setRealName($realname);
     // Adjust groups by adding any missing ones and removing any extras
     $currentGroups = $this->user->getGroups();
     foreach (array_diff($groups, $currentGroups) as $group) {
         $this->user->addGroup($group);
     }
     foreach (array_diff($currentGroups, $groups) as $group) {
         $this->user->removeGroup($group);
     }
     if ($change) {
         $this->user->saveSettings();
     }
 }
Example #4
0
 static function setupUser()
 {
     if (self::$user == NULL) {
         self::$userName = "******";
         self::$passWord = User::randomPassword();
         self::$user = User::newFromName(self::$userName);
         if (!self::$user->getID()) {
             self::$user = User::createNew(self::$userName, array("password" => self::$passWord, "email" => "*****@*****.**", "real_name" => "Test User"));
         } else {
             self::$user->setPassword(self::$passWord);
         }
         self::$user->saveSettings();
     }
 }
Example #5
0
 public function __construct($userName, $password, $group = '')
 {
     $this->userName = $userName;
     $this->password = $password;
     $this->user = User::newFromName($this->userName);
     if (!$this->user->getId()) {
         $this->user = User::createNew($this->userName, ["email" => "*****@*****.**", "real_name" => "Test User"]);
     }
     TestUser::setPasswordForUser($this->user, $this->password);
     if ($group !== '') {
         $this->user->addGroup($group);
     }
     $this->user->saveSettings();
 }
Example #6
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     //
     //en caso de no haber sesion
     // return Response::json(Input::all());
     if (Auth::user()->is_admin) {
         $usuario = User::createNew();
         $usuario->setUsername(Input::get('username'));
         $usuario->setPassword(Input::get('password'), Input::get('password_confirm'));
         $usuario->setFirstName(Input::get('first_name'));
         $usuario->setLastName(Input::get('last_name'));
         $usuario->setEmail(Input::get('email'));
         $usuario->setPhone(Input::get('phone'));
         if (Input::get('admin') == 1) {
             $usuario->is_admin = 1;
         } else {
             $usuario->is_admin = 0;
         }
         //$usuario->branch_id = Input::get('branch');
         $usuario->setPriceType(Input::get('price'));
         $usuario->setGroupId(implode(",", Input::get('groups')));
         $usuario->setBranch(Input::get('branch'));
         // return var_dump($usuario);
         if ($usuario->Guardar()) {
             //redireccionar con el mensaje a la siguiente vista
             Session::flash('message', $usuario->getErrorMessage());
             if (Input::has('branch')) {
                 foreach (Input::get('branch') as $branch_id) {
                     # code...
                     // $cantidad = $cantidad +$sucursal;
                     $userbranch = UserBranch::createNew();
                     $userbranch->account_id = Auth::user()->account_id;
                     $userbranch->user_id = $usuario->id;
                     $userbranch->branch_id = $branch_id;
                     // $userbranch->branch_id = UserBranch::getPublicId();
                     $userbranch->save();
                 }
             }
             return Redirect::to('usuarios');
         }
         Session::flash('error', $usuario->getErrorMessage());
         return Redirect::to('usuarios/create');
     }
     return Redirect::to('inicio');
 }
Example #7
0
 function setWgUser()
 {
     global $wgUser;
     $dbw = wfGetDB(DB_MASTER);
     $wh_userid = $dbw->selectField('facebook_connect', array('wh_user'), array('fb_user' => $this->userid));
     // Never here before?  create a new user and log them in
     if ($wh_userid == null) {
         $u = User::createNew('FB_' . $this->userid);
         if (!$u) {
             $u = User::newFromName('FB_' . $this->userid);
         }
         $dbw->insert('facebook_connect', array('wh_user' => $u->getID(), 'fb_user' => $this->userid));
     } else {
         $u = User::newFromID($wh_userid);
         $dbw->update('facebook_connect', array('num_login = num_login + 1'), array('wh_user' => $wh_userid));
     }
     $wgUser = $u;
     $wgUser->setCookies();
 }
Example #8
0
 public function __construct($username, $realname = 'Real Name', $email = '*****@*****.**', $groups = [])
 {
     $this->assertNotReal();
     $this->username = $username;
     $this->password = '******';
     $this->user = User::newFromName($this->username);
     $this->user->load();
     // In an ideal world we'd have a new wiki (or mock data store) for every single test.
     // But for now, we just need to create or update the user with the desired properties.
     // we particularly need the new password, since we just generated it randomly.
     // In core MediaWiki, there is no functionality to delete users, so this is the best we can do.
     if (!$this->user->isLoggedIn()) {
         // create the user
         $this->user = User::createNew($this->username, ["email" => $email, "real_name" => $realname]);
         if (!$this->user) {
             throw new MWException("Error creating TestUser " . $username);
         }
     }
     // Update the user to use the password and other details
     $this->setPassword($this->password);
     $change = $this->setEmail($email) || $this->setRealName($realname);
     // Adjust groups by adding any missing ones and removing any extras
     $currentGroups = $this->user->getGroups();
     foreach (array_diff($groups, $currentGroups) as $group) {
         $this->user->addGroup($group);
     }
     foreach (array_diff($currentGroups, $groups) as $group) {
         $this->user->removeGroup($group);
     }
     if ($change) {
         // Disable CAS check before saving. The User object may have been initialized from cached
         // information that may be out of whack with the database during testing. If tests were
         // perfectly isolated, this would not happen. But if it does happen, let's just ignore the
         // inconsistency, and just write the data we want - during testing, we are not worried
         // about data loss.
         $this->user->mTouched = '';
         $this->user->saveSettings();
     }
 }
Example #9
0
 function __construct($username, $realname = 'Real Name', $email = '*****@*****.**', $groups = array())
 {
     $this->username = $username;
     $this->realname = $realname;
     $this->email = $email;
     $this->groups = $groups;
     // don't allow user to hardcode or select passwords -- people sometimes run tests
     // on live wikis. Sometimes we create sysop users in these tests. A sysop user with
     // a known password would be a Bad Thing.
     $this->password = User::randomPassword();
     $this->user = User::newFromName($this->username);
     $this->user->load();
     // In an ideal world we'd have a new wiki (or mock data store) for every single test.
     // But for now, we just need to create or update the user with the desired properties.
     // we particularly need the new password, since we just generated it randomly.
     // In core MediaWiki, there is no functionality to delete users, so this is the best we can do.
     if (!$this->user->getID()) {
         // create the user
         $this->user = User::createNew($this->username, array("email" => $this->email, "real_name" => $this->realname));
         if (!$this->user) {
             throw new Exception("error creating user");
         }
     }
     // update the user to use the new random password and other details
     $this->user->setPassword($this->password);
     $this->user->setEmail($this->email);
     $this->user->setRealName($this->realname);
     // remove all groups, replace with any groups specified
     foreach ($this->user->getGroups() as $group) {
         $this->user->removeGroup($group);
     }
     if (count($this->groups)) {
         foreach ($this->groups as $group) {
             $this->user->addGroup($group);
         }
     }
     $this->user->saveSettings();
 }
Example #10
0
 function setWgUser()
 {
     global $wgUser, $wgOut, $wgDBname;
     LoginForm::renewSessionId();
     $bNew = true;
     $dbw = wfGetDB(DB_MASTER);
     $dbw->selectDB(WH_DATABASE_NAME_SHARED);
     $wh_userid = $dbw->selectField('gplus_connect', array('wh_user'), array('gplus_user' => $this->userid));
     $dbw->selectDB($wgDBname);
     // Never here before?  create a new user and log them in
     if ($wh_userid == null) {
         $u = User::createNew('GP_' . $this->userid);
         if (!$u) {
             $u = User::newFromName('GP_' . $this->userid);
         }
         $dbw->selectDB(WH_DATABASE_NAME_SHARED);
         $dbw->insert('gplus_connect', array('wh_user' => $u->getID(), 'gplus_user' => $this->userid));
         $dbw->selectDB($wgDBname);
     } else {
         $u = User::newFromID($wh_userid);
         $dbw->selectDB(WH_DATABASE_NAME_SHARED);
         $dbw->update('gplus_connect', array('num_login = num_login + 1'), array('wh_user' => $wh_userid));
         $dbw->selectDB($wgDBname);
         $bNew = false;
     }
     $wgUser = $u;
     $wgUser->setCookies();
     if (!$bNew) {
         $dbw->selectDB(WH_DATABASE_NAME_SHARED);
         $registered = $dbw->selectField('user', array('user_email'), array('user_id' => $wh_userid));
         $dbw->selectDB($wgDBname);
         //pass them to our start page if they're logging in again...
         if ($registered) {
             $wgOut->redirect($this->returnto);
         }
     }
 }
Example #11
0
    /**
     * Add data about uploads to the new test DB, and set up the upload
     * directory. This should be called after either setDatabase() or
     * setupDatabase().
     *
     * @param ScopedCallback|null $nextTeardown The next teardown object
     * @return ScopedCallback The teardown object
     */
    public function setupUploads($nextTeardown = null)
    {
        $teardown = [];
        $this->checkSetupDone('setupDatabase', 'setDatabase');
        $teardown[] = $this->markSetupDone('setupUploads');
        // Create the files in the upload directory (or pretend to create them
        // in a MockFileBackend). Append teardown callback.
        $teardown[] = $this->setupUploadBackend();
        // Create a user
        $user = User::createNew('WikiSysop');
        // Register the uploads in the database
        $image = wfLocalFile(Title::makeTitle(NS_FILE, 'Foobar.jpg'));
        # note that the size/width/height/bits/etc of the file
        # are actually set by inspecting the file itself; the arguments
        # to recordUpload2 have no effect.  That said, we try to make things
        # match up so it is less confusing to readers of the code & tests.
        $image->recordUpload2('', 'Upload of some lame file', 'Some lame file', ['size' => 7881, 'width' => 1941, 'height' => 220, 'bits' => 8, 'media_type' => MEDIATYPE_BITMAP, 'mime' => 'image/jpeg', 'metadata' => serialize([]), 'sha1' => Wikimedia\base_convert('1', 16, 36, 31), 'fileExists' => true], $this->db->timestamp('20010115123500'), $user);
        $image = wfLocalFile(Title::makeTitle(NS_FILE, 'Thumb.png'));
        # again, note that size/width/height below are ignored; see above.
        $image->recordUpload2('', 'Upload of some lame thumbnail', 'Some lame thumbnail', ['size' => 22589, 'width' => 135, 'height' => 135, 'bits' => 8, 'media_type' => MEDIATYPE_BITMAP, 'mime' => 'image/png', 'metadata' => serialize([]), 'sha1' => Wikimedia\base_convert('2', 16, 36, 31), 'fileExists' => true], $this->db->timestamp('20130225203040'), $user);
        $image = wfLocalFile(Title::makeTitle(NS_FILE, 'Foobar.svg'));
        $image->recordUpload2('', 'Upload of some lame SVG', 'Some lame SVG', ['size' => 12345, 'width' => 240, 'height' => 180, 'bits' => 0, 'media_type' => MEDIATYPE_DRAWING, 'mime' => 'image/svg+xml', 'metadata' => serialize([]), 'sha1' => Wikimedia\base_convert('', 16, 36, 31), 'fileExists' => true], $this->db->timestamp('20010115123500'), $user);
        # This image will be blacklisted in [[MediaWiki:Bad image list]]
        $image = wfLocalFile(Title::makeTitle(NS_FILE, 'Bad.jpg'));
        $image->recordUpload2('', 'zomgnotcensored', 'Borderline image', ['size' => 12345, 'width' => 320, 'height' => 240, 'bits' => 24, 'media_type' => MEDIATYPE_BITMAP, 'mime' => 'image/jpeg', 'metadata' => serialize([]), 'sha1' => Wikimedia\base_convert('3', 16, 36, 31), 'fileExists' => true], $this->db->timestamp('20010115123500'), $user);
        $image = wfLocalFile(Title::makeTitle(NS_FILE, 'Video.ogv'));
        $image->recordUpload2('', 'A pretty movie', 'Will it play', ['size' => 12345, 'width' => 320, 'height' => 240, 'bits' => 0, 'media_type' => MEDIATYPE_VIDEO, 'mime' => 'application/ogg', 'metadata' => serialize([]), 'sha1' => Wikimedia\base_convert('', 16, 36, 31), 'fileExists' => true], $this->db->timestamp('20010115123500'), $user);
        $image = wfLocalFile(Title::makeTitle(NS_FILE, 'Audio.oga'));
        $image->recordUpload2('', 'An awesome hitsong', 'Will it play', ['size' => 12345, 'width' => 0, 'height' => 0, 'bits' => 0, 'media_type' => MEDIATYPE_AUDIO, 'mime' => 'application/ogg', 'metadata' => serialize([]), 'sha1' => Wikimedia\base_convert('', 16, 36, 31), 'fileExists' => true], $this->db->timestamp('20010115123500'), $user);
        # A DjVu file
        $image = wfLocalFile(Title::makeTitle(NS_FILE, 'LoremIpsum.djvu'));
        $image->recordUpload2('', 'Upload a DjVu', 'A DjVu', ['size' => 3249, 'width' => 2480, 'height' => 3508, 'bits' => 0, 'media_type' => MEDIATYPE_BITMAP, 'mime' => 'image/vnd.djvu', 'metadata' => '<?xml version="1.0" ?>
<!DOCTYPE DjVuXML PUBLIC "-//W3C//DTD DjVuXML 1.1//EN" "pubtext/DjVuXML-s.dtd">
<DjVuXML>
<HEAD></HEAD>
<BODY><OBJECT height="3508" width="2480">
<PARAM name="DPI" value="300" />
<PARAM name="GAMMA" value="2.2" />
</OBJECT>
<OBJECT height="3508" width="2480">
<PARAM name="DPI" value="300" />
<PARAM name="GAMMA" value="2.2" />
</OBJECT>
<OBJECT height="3508" width="2480">
<PARAM name="DPI" value="300" />
<PARAM name="GAMMA" value="2.2" />
</OBJECT>
<OBJECT height="3508" width="2480">
<PARAM name="DPI" value="300" />
<PARAM name="GAMMA" value="2.2" />
</OBJECT>
<OBJECT height="3508" width="2480">
<PARAM name="DPI" value="300" />
<PARAM name="GAMMA" value="2.2" />
</OBJECT>
</BODY>
</DjVuXML>', 'sha1' => Wikimedia\base_convert('', 16, 36, 31), 'fileExists' => true], $this->db->timestamp('20010115123600'), $user);
        return $this->createTeardownObject($teardown, $nextTeardown);
    }
Example #12
0
 public function processRegistration($data, &$remember)
 {
     $remember = UserConfig::$allowRememberMe && UserConfig::$rememberUserOnRegistration;
     $errors = array();
     if (array_key_exists('pass', $data) && array_key_exists('repeatpass', $data) && $data['pass'] !== $data['repeatpass']) {
         $errors['repeatpass'][] = 'Passwords don\'t match';
     }
     if (array_key_exists('pass', $data) && strlen($data['pass']) < 6) {
         $errors['pass'][] = 'Passwords must be at least 6 characters long';
     }
     if (array_key_exists('username', $data)) {
         $username = strtolower(trim(mb_convert_encoding($data['username'], 'UTF-8')));
         if (strlen($username) < 2) {
             $errors['username'][] = 'Username must be at least 2 characters long';
         }
         if (strlen($username) > 25) {
             $errors['username'][] = 'Username must be no more then 25 characters long';
         }
         if (preg_match('/^[a-z][a-z0-9.]*[a-z0-9]$/', $username) !== 1) {
             $errors['username'][] = "Username must start with the letter and contain only latin letters, digits or '.' symbols";
         }
     } else {
         $errors['username'][] = "No username passed";
     }
     if (array_key_exists('name', $data)) {
         $name = trim(mb_convert_encoding($data['name'], 'UTF-8'));
         if ($name == '') {
             $errors['name'][] = "Name can't be empty";
         }
     } else {
         $errors['name'][] = 'No name specified';
     }
     if (array_key_exists('email', $data)) {
         $email = trim(mb_convert_encoding($data['email'], 'UTF-8'));
         if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
             $errors['email'][] = 'Invalid email address';
         }
     } else {
         $errors['email'][] = 'No email specified';
     }
     if (count($errors) > 0) {
         throw new InputValidationException('Validation failed', 0, $errors);
     }
     if (count(User::getUsersByEmailOrUsername($username)) > 0) {
         $errors['username'][] = "This username is already used, please pick another one";
     }
     if (count(User::getUsersByEmailOrUsername($email)) > 0) {
         $errors['email'][] = "This email is already used by another user, please enter another email address.";
     }
     if (count($errors) > 0) {
         throw new ExistingUserException('User already exists', 0, $errors);
     }
     // ok, let's create a user
     $user = User::createNew($name, $username, $email, $data['pass']);
     $user->recordActivity(USERBASE_ACTIVITY_REGISTER_UPASS);
     return $user;
 }
Example #13
0
 /**
  * Create or select a bot user to attribute the code generation to
  * @return user object
  * @note there doesn't seem to be a decent method for checking if a user already exists
  * */
 private function _getBot()
 {
     $bot = User::createNew(QRCODEBOT);
     if ($bot != null) {
         wfDebug('QrCode::_getBot: Created new user ' . QRCODEBOT . "\n");
         //$bot->setPassword( '' );   // doc says empty password disables, but this triggers an exception
     } else {
         $bot = User::newFromName(QRCODEBOT);
     }
     if (!$bot->isAllowed('bot')) {
         // User::isBot() has been deprecated
         $bot->addGroup('bot');
         wfDebug('QrCode::_getBot: Added user ' . QRCODEBOT . ' to the Bot group' . "\n");
     }
     return $bot;
 }
 /**
  * Do the whole dirty job of renaming user
  *
  * @return bool True if the process succeded
  */
 private function doRun()
 {
     global $wgMemc, $wgAuth;
     $this->addLog("User rename global task start." . (!empty($this->mFakeUserId) ? ' Process is being repeated.' : null));
     $this->addLog("Renaming user {$this->mOldUsername} (ID {$this->mUserId}) to {$this->mNewUsername}");
     $hookName = 'RenameUser::Abort';
     $this->addLog("Broadcasting hook: {$hookName}");
     // Give other affected extensions a chance to validate or abort
     if (!wfRunHooks($hookName, array($this->mUserId, $this->mOldUsername, $this->mNewUsername, &$this->mErrors))) {
         $this->addLog("Aborting procedure as requested by hook.");
         $this->addError(wfMsgForContent('userrenametool-error-extension-abort'));
         wfProfileOut(__METHOD__);
         return false;
     }
     //enumerate IDs for wikis the user has been active in
     $this->addLog("Searching for user activity on wikis.");
     $wikiIDs = RenameUserHelper::lookupRegisteredUserActivity($this->mUserId);
     $this->addLog("Found " . count($wikiIDs) . " wikis: " . implode(', ', $wikiIDs));
     $hookName = 'UserRename::BeforeAccountRename';
     $this->addLog("Broadcasting hook: {$hookName}");
     wfRunHooks($hookName, array($this->mUserId, $this->mOldUsername, $this->mNewUsername));
     //rename the user account across clusters
     $clusters = WikiFactory::getClusters();
     foreach ($clusters as $clusterName) {
         if (!$this->renameAccount($clusterName)) {
             $this->addLog("Renaming user account on cluster {$clusterName} resulted in a failure.");
             //if main shared DB, rename operation failed and not repeating then something's wrong dude...
             if ($clusterName === RenameUserHelper::CLUSTER_DEFAULT && empty($this->mFakeUserId)) {
                 $this->addLog("Cluster {$clusterName} is the main shared DB, aborting.");
                 $this->addError(wfMsgForContent('userrenametool-error-cannot-rename-account'));
                 wfProfileOut(__METHOD__);
                 return false;
             }
         }
     }
     $this->invalidateUser($this->mNewUsername);
     /*if not repeating the process
     		create a new account storing the old username and some extra information in the realname field
     		this avoids creating new accounts with the old name and let's resume/repeat the process in case is needed*/
     $this->addLog("Creating fake user account");
     $fakeUser = null;
     if (empty($this->mFakeUserId)) {
         //IMPORTANT: thi extension is meant to be enabled only on community central
         $fakeUser = User::createNew($this->mOldUsername);
         $fakeUser->setOption('renameData', self::RENAME_TAG . '=' . $this->mNewUsername . ';' . self::PROCESS_TAG . '=' . '1');
         $fakeUser->saveToCache();
         $this->mFakeUserId = $fakeUser->getId();
         $this->addLog("Created fake user account with ID {$this->mFakeUserId} and renameData '{$fakeUser->getOption('renameData', '')}'");
     } else {
         $fakeUser = User::newFromId($this->mFakeUserId);
         $this->addLog("Fake user account already exists: {$this->mFakeUserId}");
     }
     $this->invalidateUser($this->mOldUsername);
     //Block the user from logging in before logging him out
     $this->addLog("Creating a Phalanx block for the user.");
     if (empty($this->mPhalanxBlockId)) {
         $this->mPhalanxBlockId = PhalanxHelper::save(array('text' => $this->mNewUsername, 'exact' => 1, 'case' => 1, 'regex' => 0, 'timestamp' => wfTimestampNow(), 'expire' => null, 'author_id' => $this->mRequestorId, 'reason' => 'User rename process requested', 'lang' => null, 'type' => Phalanx::TYPE_USER), false);
         if (!$this->mPhalanxBlockId) {
             $this->addLog("Creation of the block failed.");
             $this->addError(wfMsgForContent('userrenametool-error-cannot-create-block'));
             wfProfileOut(__METHOD__);
             return false;
         } else {
             $fakeUser->setOption('renameData', $fakeUser->getOption('renameData', '') . ';' . self::PHALANX_BLOCK_TAG . '=' . $this->mPhalanxBlockId);
             $fakeUser->saveSettings();
             $this->addLog("Block created with ID {$this->mPhalanxBlockId}.");
         }
     } else {
         $this->addLog("Block with ID {$this->mPhalanxBlockId} already exists.");
     }
     $hookName = 'UserRename::AfterAccountRename';
     $this->addLog("Broadcasting hook: {$hookName}");
     wfRunHooks($hookName, array($this->mUserId, $this->mOldUsername, $this->mNewUsername));
     //process global tables
     $this->addLog("Initializing update of global shared DB's.");
     $this->updateGlobal();
     // create a new task for the Task Manager to handle all the global tables
     $this->addLog("Setting up a task for processing global DB");
     $task = new UserRenameGlobalTask();
     $task->createTask(array('rename_user_id' => $this->mUserId, 'rename_old_name' => $this->mOldUsername, 'rename_new_name' => $this->mNewUsername, 'tasks' => self::$mStatsDefaults), TASK_QUEUED);
     $this->addLog("Task created with ID " . $task->getID());
     $this->addLog("Setting up a task for processing local DB's");
     //create a new task for the Task Manager to handle all the local tables per each wiki
     $task = new UserRenameLocalTask();
     $task->createTask(array('city_ids' => $wikiIDs, 'requestor_id' => $this->mRequestorId, 'requestor_name' => $this->mRequestorName, 'rename_user_id' => $this->mUserId, 'rename_old_name' => $this->mOldUsername, 'rename_new_name' => $this->mNewUsername, 'rename_fake_user_id' => $this->mFakeUserId, 'phalanx_block_id' => $this->mPhalanxBlockId, 'reason' => $this->mReason, 'global_task_id' => $this->mGlobalTask->getID()), TASK_QUEUED);
     $this->addLog("Task created with ID " . $task->getID());
     $this->addLog("User rename global task end.");
     wfProfileOut(__METHOD__);
     return true;
 }
 private function createTestUser($name, $groups = array())
 {
     $user = User::createNew($name);
     $user->setPassword($this->TEST_PASSWORD);
     # With "qqx" language selected, messages are replaced with
     # their names, so parsing process is translation-independent.
     $user->setOption('language', 'qqx');
     $user->saveSettings();
     foreach ($groups as $g) {
         $user->addGroup($g);
     }
     return $user;
 }
$page->name = '404 Not Found';
$page->content = "\n  <h1>Not Found</h1>\n  \n  <p>The requested URL <span id=\"url\"></span> was not found on this server.</p>\n  \n  <script type=\"text/javascript\">\n    var url = document.location.toString().replace(/.*abhibeckert.com/, '');\n  \n    document.getElementById('url').innerHTML = url;\n  </script>\n";
$page->modifiedBy = 'setup';
$page->save();
$page = Page::createNew();
$page->url = '/login';
$page->name = 'Login';
$page->content = '';
$page->class = 'Fierce\\LoginController';
$page->modifiedBy = 'setup';
$page->save();
$page = Page::createNew();
$page->url = '/admin';
$page->name = 'Pages';
$page->content = '';
$page->class = 'Fierce\\PagesController';
$page->modifiedBy = 'setup';
$page->save();
$page = Page::createNew();
$page->url = '/admin/users';
$page->name = 'Users';
$page->content = '';
$page->class = 'Fierce\\UsersController';
$page->modifiedBy = 'setup';
$page->save();
$user = User::createNew();
$user->name = 'Admin';
$user->email = 'admin';
$user->newPassword = '******';
$user->modifiedBy = 'setup';
$user->save(false);
 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);
 }
 /**
  * @dataProvider provideUserWasLastToEdit
  */
 public function testUserWasLastToEdit($sinceIdx, $expectedLast)
 {
     $userA = User::newFromName("RevisionStorageTest_userA");
     $userB = User::newFromName("RevisionStorageTest_userB");
     if ($userA->getId() === 0) {
         $userA = User::createNew($userA->getName());
     }
     if ($userB->getId() === 0) {
         $userB = User::createNew($userB->getName());
     }
     $ns = $this->getDefaultWikitextNS();
     $dbw = wfGetDB(DB_MASTER);
     $revisions = [];
     // create revisions -----------------------------
     $page = WikiPage::factory(Title::newFromText('RevisionStorageTest_testUserWasLastToEdit', $ns));
     $page->insertOn($dbw);
     # zero
     $revisions[0] = new Revision(['page' => $page->getId(), 'title' => $page->getTitle(), 'timestamp' => '20120101000000', 'user' => $userA->getId(), 'text' => 'zero', 'content_model' => CONTENT_MODEL_WIKITEXT, 'summary' => 'edit zero']);
     $revisions[0]->insertOn($dbw);
     # one
     $revisions[1] = new Revision(['page' => $page->getId(), 'title' => $page->getTitle(), 'timestamp' => '20120101000100', 'user' => $userA->getId(), 'text' => 'one', 'content_model' => CONTENT_MODEL_WIKITEXT, 'summary' => 'edit one']);
     $revisions[1]->insertOn($dbw);
     # two
     $revisions[2] = new Revision(['page' => $page->getId(), 'title' => $page->getTitle(), 'timestamp' => '20120101000200', 'user' => $userB->getId(), 'text' => 'two', 'content_model' => CONTENT_MODEL_WIKITEXT, 'summary' => 'edit two']);
     $revisions[2]->insertOn($dbw);
     # three
     $revisions[3] = new Revision(['page' => $page->getId(), 'title' => $page->getTitle(), 'timestamp' => '20120101000300', 'user' => $userA->getId(), 'text' => 'three', 'content_model' => CONTENT_MODEL_WIKITEXT, 'summary' => 'edit three']);
     $revisions[3]->insertOn($dbw);
     # four
     $revisions[4] = new Revision(['page' => $page->getId(), 'title' => $page->getTitle(), 'timestamp' => '20120101000200', 'user' => $userA->getId(), 'text' => 'zero', 'content_model' => CONTENT_MODEL_WIKITEXT, 'summary' => 'edit four']);
     $revisions[4]->insertOn($dbw);
     // test it ---------------------------------
     $since = $revisions[$sinceIdx]->getTimestamp();
     $wasLast = Revision::userWasLastToEdit($dbw, $page->getId(), $userA->getId(), $since);
     $this->assertEquals($expectedLast, $wasLast);
 }
 /**
  * Make a user for testing ACL $key - the same user is returned for the same $key
  */
 protected function makeUser($key)
 {
     if (!isset($this->aclUsers[$key])) {
         $name = 'AclTestUser' . count($this->aclUsers);
         $u = User::newFromName($name);
         if (!$u || !$u->getId()) {
             $u = User::createNew($name, array());
             if (!$u) {
                 throw new Exception("Failed to create user {$name}");
             }
         }
         $this->aclUsers[$key] = $u;
     }
     return $this->aclUsers[$key];
 }
 protected function setUp()
 {
     parent::setUp();
     $langObj = Language::factory('en');
     $localZone = 'UTC';
     $localOffset = date('Z') / 60;
     $this->setMwGlobals(array('wgMemc' => new EmptyBagOStuff(), 'wgContLang' => $langObj, 'wgLanguageCode' => 'en', 'wgLang' => $langObj, 'wgLocaltimezone' => $localZone, 'wgLocalTZoffset' => $localOffset, 'wgNamespaceProtection' => array(NS_MEDIAWIKI => 'editinterface')));
     // Without this testUserBlock will use a non-English context on non-English MediaWiki
     // installations (because of how Title::checkUserBlock is implemented) and fail.
     RequestContext::resetMain();
     $this->userName = '******';
     $this->altUserName = '******';
     date_default_timezone_set($localZone);
     $this->title = Title::makeTitle(NS_MAIN, "Main Page");
     if (!isset($this->userUser) || !$this->userUser instanceof User) {
         $this->userUser = User::newFromName($this->userName);
         if (!$this->userUser->getID()) {
             $this->userUser = User::createNew($this->userName, array("email" => "*****@*****.**", "real_name" => "Test User"));
             $this->userUser->load();
         }
         $this->altUser = User::newFromName($this->altUserName);
         if (!$this->altUser->getID()) {
             $this->altUser = User::createNew($this->altUserName, array("email" => "*****@*****.**", "real_name" => "Test User Alt"));
             $this->altUser->load();
         }
         $this->anonUser = User::newFromId(0);
         $this->user = $this->userUser;
     }
 }