public function onAuthenticationSuccess(Request $request, TokenInterface $token) { $username = $token->getUser()->getUsername(); $user = new UserModel(); $website = Website::get(); if (!$user->readByUserName($username) or $user->role != SystemRoles::SYSTEM_ADMIN and !($user->siteRole->offsetExists($website->domain) and $user->siteRole[$website->domain] != SiteRoles::NONE)) { return $this->httpUtils->createRedirectResponse($request, '/app/logout'); } $request->getSession()->set('user_id', $user->id->asString()); $request->getSession()->set('user', array('username' => $username)); $projectId = $user->getDefaultProjectId($website->domain); if ($projectId) { $request->getSession()->set('projectId', $projectId); } $referer = $this->determineTargetUrl($request); if ($referer and strpos($referer, '/app/') !== false) { return $this->httpUtils->createRedirectResponse($request, $referer); } elseif ($projectId) { $project = ProjectModel::getById($projectId); $url = '/app/' . $project->appName . '/' . $projectId; return $this->httpUtils->createRedirectResponse($request, $url); } else { return $this->httpUtils->createRedirectResponse($request, '/'); } }
public function run($userId, $mode = 'test') { $testMode = $mode != 'run'; $message = "Ensure DB Indexes\n"; $numberOfIndexesCreated = 0; $website = Website::get(); $onDevMachine = strpos($website->domain, 'dev.') !== false; $onLocalMachine = strrpos($website->domain, '.local') !== false; $message .= "\n------------- Main Database:\n"; $mainCollectionName = ProjectModelMongoMapper::instance()->getCollectionName(); $mainIndexes = ProjectModelMongoMapper::instance()->INDEXES_REQUIRED; $mainIndexesToCreate = MongoStore::getIndexesNotSetInCollection(SF_DATABASE, $mainCollectionName, $mainIndexes); $numberOfIndexesCreated += count($mainIndexesToCreate); $message .= count($mainIndexesToCreate) . " main indexes created.\n"; if (($onDevMachine || $onLocalMachine) && MongoStore::hasDB(SF_TEST_DATABASE)) { $message .= "\n------------- Test Database:\n"; $mainIndexesToCreate = MongoStore::getIndexesNotSetInCollection(SF_TEST_DATABASE, $mainCollectionName, $mainIndexes); $numberOfIndexesCreated += count($mainIndexesToCreate); $message .= count($mainIndexesToCreate) . " test indexes created.\n"; } if (!$testMode) { MongoStore::ensureIndexesInCollection(SF_DATABASE, $mainCollectionName, $mainIndexes); if (($onDevMachine || $onLocalMachine) && MongoStore::hasDB(SF_TEST_DATABASE)) { MongoStore::ensureIndexesInCollection(SF_TEST_DATABASE, $mainCollectionName, $mainIndexes); } } // loop over every project $projectList = new ProjectListModel(); $projectList->read(); foreach ($projectList->entries as $projectParams) { $project = ProjectModel::getById($projectParams['id']); if ($project->appName == 'lexicon') { $message .= "\n------------- {$project->projectName} project:\n"; $lexiconCollectionName = LexEntryModel::mapper($project->databaseName())->getCollectionName(); $lexiconIndexes = LexEntryModel::mapper($project->databaseName())->INDEXES_REQUIRED; $lexiconIndexesToCreate = MongoStore::getIndexesNotSetInCollection($project->databaseName(), $lexiconCollectionName, $lexiconIndexes); $numberOfIndexesCreated += count($lexiconIndexesToCreate); $optionListCollectionName = LexOptionListModel::mapper($project->databaseName())->getCollectionName(); $optionListIndexes = LexOptionListModel::mapper($project->databaseName())->INDEXES_REQUIRED; $optionListIndexesToCreate = MongoStore::getIndexesNotSetInCollection($project->databaseName(), $optionListCollectionName, $optionListIndexes); $numberOfIndexesCreated += count($optionListIndexesToCreate); if (count($lexiconIndexesToCreate) + count($optionListIndexesToCreate) > 0) { $message .= count($lexiconIndexesToCreate) . " lexicon indexes created.\n"; $message .= count($optionListIndexesToCreate) . " option list indexes created.\n"; } else { $message .= "No indexes needed creating.\n"; } if (!$testMode) { MongoStore::ensureIndexesInCollection($project->databaseName(), $lexiconCollectionName, $lexiconIndexes); MongoStore::ensureIndexesInCollection($project->databaseName(), $optionListCollectionName, $optionListIndexes); } } } if ($numberOfIndexesCreated > 0) { $message .= "\nCreated {$numberOfIndexesCreated} DB Indexes.\n\n"; } else { $message .= "\nAll indexes were present.\n\n"; } return $message; }
public function __construct($domain = 'scriptureforge.org') { $this->db = MongoStore::connect(SF_DATABASE); $this->website = Website::get($domain); if (!isset($this->uploadFilePaths)) { $this->uploadFilePaths = array(); } }
public function testGet_Works() { $website = Website::get('scriptureforge.org'); $this->assertEqual($website->domain, 'scriptureforge.org'); $this->assertEqual($website->base, 'scriptureforge'); $this->assertEqual($website->theme, 'default'); $website = Website::get('randomdomain.com'); $this->assertNull($website); }
public function run($userId, $mode = 'test') { $testMode = $mode != 'run'; $message = "Fix site roles integrity\n\n"; // loop over every project $projectlist = new ProjectListModel(); $projectlist->read(); $fixCount = array(); $userNoRoleCount = 0; foreach ($projectlist->entries as $projectParams) { // foreach existing project $projectId = $projectParams['id']; $project = new ProjectModel($projectId); $hostname = $project->siteName; $website = Website::get($hostname); $fixCount[$hostname] = 0; $projectUserRefs = array_keys($project->users->getArrayCopy()); //$message .= "------------- " . $project->projectName . "\n"; foreach ($projectUserRefs as $userId) { // foreach user that is a member of this project $user = new UserModel($userId); if (!array_key_exists($hostname, $user->siteRole) && $user->username != '') { $message .= "Fixed user '" . $user->username . "' who did not have a site role on " . $hostname . "\n"; $fixCount[$hostname]++; $user->siteRole[$hostname] = $website->userDefaultSiteRole; if (!$testMode) { $user->write(); } } } } // loop over users who do not belong to any projects $userlist = new UserListModel(); $userlist->read(); foreach ($userlist->entries as $userParams) { // foreach existing user $userId = $userParams['id']; $user = new UserModel($userId); if (count($user->projects->refs) == 0 && count(array_keys($user->siteRole->getArrayCopy())) == 0) { $userNoRoleCount++; //$message .= "Warning: user '" . $user->username . "' has no projects and no siteRoles on any site!\n"; } } foreach ($fixCount as $site => $count) { if ($count > 0) { $message .= "\n\n{$site} : Fixed {$count} non-existent site roles \n\n"; } else { $message .= "\n\n{$site} : Nothing to do \n\n"; } } if ($userNoRoleCount > 0) { $message .= "Warning: {$userNoRoleCount} useless users had no projects and no siteRoles on any site!\n"; } return $message; }
public function __construct(Application $app) { $this->app = $app; $this->website = Website::get(); $this->userId = SilexSessionHelper::getUserId($app); $this->projectId = SilexSessionHelper::getProjectId($app, $this->website); // "Kick" session every time we use an API call, so it won't time out $this->update_last_activity(); // TODO put in the LanguageForge style error handler for logging / jsonrpc return formatting etc. CP 2013-07 ini_set('display_errors', 0); }
public function __construct($controller) { $this->_userId = (string) $controller['session']->get('user_id'); $this->_projectId = (string) $controller['session']->get('projectId'); $this->_controller = $controller; $this->_website = Website::get(); // "Kick" session every time we use an API call, so it won't time out $this->update_last_activity(); // TODO put in the LanguageForge style error handler for logging / jsonrpc return formatting etc. CP 2013-07 ini_set('display_errors', 0); }
private static function _createEmptyProject($languageCode, $languageName, $userId) { $website = Website::get(); $projectCode = SemDomTransProjectModel::projectCode($languageCode); $projectName = SemDomTransProjectModel::projectName($languageCode, $languageName); $projectID = ProjectCommands::createProject($projectName, $projectCode, LfProjectModel::SEMDOMTRANS_APP, $userId, $website); $project = new SemDomTransProjectModel($projectID); $project->languageIsoCode = $languageCode; $project->isSourceLanguage = false; $project->semdomVersion = SemDomTransProjectModel::SEMDOM_VERSION; // by default all created projects have English as their source. A future feature would allow creating projects off of other source languages $englishProject = SemDomTransProjectModel::getEnglishProject(); $project->sourceLanguageProjectId->id = $englishProject->id->asString(); return $project->write(); }
public function loadUserByUsername($usernameOrEmail) { $user = new UserModelWithPassword(); // try to load user by email address if (strpos($usernameOrEmail, '@') !== false) { $user->readByEmail($usernameOrEmail); } else { $user->readByUserName($usernameOrEmail); } if ($user->id->asString() == '') { throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $usernameOrEmail)); } if (!$user->hasRoleOnSite($this->website) and $user->role != SystemRoles::SYSTEM_ADMIN) { $shouldThrowException = true; // special case: if known user on languageforge.org logs in on scriptureforge.org and vice versa, we automatically add them to the site. // This is because scriptureforge and languageforge are sister sites where cross-login is expected and allowed. $sisterSiteMap = array('scriptureforge.org' => 'languageforge.org', 'scriptureforge.local' => 'languageforge.local', 'dev.scriptureforge.org' => 'dev.languageforge.org'); $sisterSiteMap = array_merge($sisterSiteMap, array_flip($sisterSiteMap)); if (array_key_exists($this->website->domain, $sisterSiteMap)) { $otherWebsite = Website::get($sisterSiteMap[$this->website->domain]); if ($user->hasRoleOnSite($otherWebsite)) { $shouldThrowException = false; $user->siteRole[$this->website->domain] = $this->website->userDefaultSiteRole; $user->write(); } } if ($shouldThrowException) { throw new AccessDeniedException(sprintf('Username "%s" not available on "%s". Use "Create an Account".', $usernameOrEmail, $this->website->domain)); } } /* $identityCheck = UserCommands::checkIdentity($usernameOrEmail, '', $this->website); if (! $identityCheck->usernameExists) { throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $usernameOrEmail)); } $user->readByUserName($usernameOrEmail); if (! $identityCheck->usernameExistsOnThisSite and $user->role != SystemRoles::SYSTEM_ADMIN) { throw new AccessDeniedException(sprintf('Username "%s" not available on "%s". Use "Create an Account".', $usernameOrEmail, $this->website->domain)); } */ $roles = array('ROLE_' . $user->role); if ($user->siteRole and $user->siteRole->offsetExists($this->website->domain) and $user->siteRole[$this->website->domain] !== SiteRoles::NONE) { $roles[] = 'ROLE_SITE_' . $user->siteRole[$this->website->domain]; } return new UserWithId($user->username, $user->password, $user->id->asString(), $roles); }
public function __construct() { $this->website = Website::get(); $this->_isLoggedIn = false; $this->data['isLoggedIn'] = $this->_isLoggedIn; $this->data['isAdmin'] = false; $this->data['projects'] = array(); $this->data['smallAvatarUrl'] = ''; $this->data['userName'] = ''; $this->data['version'] = VERSION; $this->data['http_host'] = $_SERVER['HTTP_HOST']; $this->data['jsFiles'] = array(); $this->data['jsNotMinifiedFiles'] = array(); $this->data['cssFiles'] = array(); $this->addCssFiles("Site/views/shared/css"); $this->addCssFiles($this->getThemePath() . "/css"); }
public function run($userId, $mode = 'test') { $testMode = $mode != 'run'; $message = "Fix project site name integrity\n\n"; // loop over every project $projectlist = new ProjectListModel(); $projectlist->read(); $fixCount = 0; foreach ($projectlist->entries as $projectParams) { // foreach existing project $projectId = $projectParams['id']; $project = new ProjectModel($projectId); $hostname = $project->siteName; $website = Website::get($hostname); if (!$website) { // the website does not exist anymore $message .= "{$hostname} does not exist anymore..."; // see if there is a redirect $redirect = Website::getRawRedirect($hostname); if ($redirect) { $message .= "changed to {$redirect}\n"; $project->siteName = $redirect; $fixCount++; if (!$testMode) { $project->write(); } } else { $message .= "ERROR: dont know what to change it to since no redirect is available\n"; } } } if ($fixCount > 0) { $message .= "\n\nFixed siteNames in {$fixCount} project(s)\n\n"; } else { $message .= "\n\nNo non-existent siteNames were found in the projects collection\n\n"; } return $message; }
public function onAuthenticationSuccess(Request $request, TokenInterface $token) { $username = $token->getUser()->getUsername(); $user = new UserModel(); $website = Website::get(); // automatically logout if 1) the user doesn't exist or 2) the user is not a system admin and has no site rights on the current site if (!$user->readByUserName($username) or $user->role != SystemRoles::SYSTEM_ADMIN and !($user->siteRole->offsetExists($website->domain) and $user->siteRole[$website->domain] != SiteRoles::NONE)) { return $this->httpUtils->createRedirectResponse($request, '/app/logout'); } $projectId = $user->getCurrentProjectId($website->domain); // redirect to page before the login screen was presented, or to the default project for this user $referer = $this->determineTargetUrl($request); $url = '/app/projects'; if ($referer and strpos($referer, '/app/') !== false) { $url = $referer; } elseif ($projectId && ProjectModel::projectExistsOnWebsite($projectId, $website)) { $project = ProjectModel::getById($projectId); if ($project->userIsMember($user->id->asString())) { $url = '/app/' . $project->appName . '/' . $projectId; } } return $this->httpUtils->createRedirectResponse($request, $url); }
use Api\Model\Shared\Command\ProjectCommands; use Api\Model\Shared\Command\UserCommands; use Api\Model\Shared\Mapper\MongoStore; use Api\Model\Shared\ProjectModel; use Api\Model\Shared\Rights\ProjectRoles; use Api\Model\Shared\Rights\SystemRoles; use Api\Model\Shared\UserModel; $constants = json_decode(file_get_contents(TestPath . 'app/testConstants.json'), true); // Fake some $_SERVER variables like HTTP_HOST for the sake of the code that needs it $hostname = "languageforge.local"; if (count($argv) > 1) { // hostname is passed in on command line $hostname = $argv[1]; } $_SERVER['HTTP_HOST'] = $hostname; $website = Website::get($hostname); if (is_null($website)) { exit("Error: {$hostname} is not a registered website hostname!\n\n"); } $site = $website->base; // start with a fresh database MongoStore::dropAllCollections(SF_DATABASE); // Also empty out databases for the test projects $projectArrays = array($constants['testProjectName'] => $constants['testProjectCode'], $constants['otherProjectName'] => $constants['otherProjectCode'], $constants['fourthProjectName'] => $constants['fourthProjectCode'], $constants['srProjectName'] => $constants['srProjectCode']); foreach ($projectArrays as $projectName => $projectCode) { $projectModel = new ProjectModel(); $projectModel->projectName = $projectName; $projectModel->projectCode = $projectCode; MongoStore::dropAllCollections($projectModel->databaseName()); } // drop the third database because it is used in a rename test
public function testSendSignup_WithProject_PropertiesToFromBodyOk() { $e = new MongoTestEnvironment(); $e->clean(); $userId = $e->createUser('User', 'Name', '*****@*****.**'); $user = new UserModel($userId); $project = $e->createProject(SF_TESTPROJECT, SF_TESTPROJECTCODE); $project->projectCode = 'test_project'; $project->write(); $delivery = new MockCommunicateDelivery(); $website = Website::get('scriptureforge.org'); $website->defaultProjectCode = 'test_project'; Communicate::sendSignup($user, $website, $delivery); // What's in the delivery? $senderEmail = 'no-reply@' . $e->website->domain; $expectedTo = array($user->emailPending => $user->name); $this->assertPattern('/' . $e->website->name . '/', $delivery->from[$senderEmail]); $this->assertEqual($expectedTo, $delivery->to); $this->assertPattern('/' . $e->website->name . '/', $delivery->subject); $this->assertPattern('/Name/', $delivery->content); $this->assertPattern('/' . $user->validationKey . '/', $delivery->content); }
#!/usr/bin/php -q <?php require_once '../scriptsConfig.php'; use Api\Model\Command\UserCommands; use Api\Model\Shared\Rights\SystemRoles; use Api\Model\ProjectModel; use Api\Library\Shared\Website; use Api\Model\ProjectListModel; php_sapi_name() == 'cli' or die('this script must be run on the command-line'); $scriptureforgeWebsite = Website::get('scriptureforge.org'); $languageforgeWebsite = Website::get('languageforge.org'); // remove all existing projects $runForReal = false; if (count($argv) > 1 && $argv[1] == 'run') { $runForReal = true; } else { print "\nTest Mode - no data will be changed\n--------------------------------\n\n"; } $projectList = new ProjectListModel(); $projectList->read(); print "{$projectList->count} projects will be deleted\n\n"; foreach ($projectList->entries as $p) { $project = new ProjectModel($p['id']); print "Deleting Project " . $project->projectName . "\n"; if ($runForReal) { try { $project->remove(); } catch (\Exception $e) { // don't do anything }
public function Run($argv) { $runForReal = false; if (count($argv) > 1 && $argv[1] == 'run') { $runForReal = true; } else { print "\nUsage: FactoryReset.php <run> <DIRECTORY>\n"; print "Run factory reset and restore mongodb and assets from DIRECTORY\n"; print "\nTest Mode - no data will be changed\n--------------------------------\n\n"; } $archivePath = count($argv) > 2 ? $argv[2] : ""; $projectList = new ProjectListModel(); $projectList->read(); // remove all existing projects print "\n{$projectList->count} projects will be deleted\n"; foreach ($projectList->entries as $p) { $project = new ProjectModel($p['id']); print "Deleting Project " . $project->projectName . "\n"; if ($runForReal) { try { $project->remove(); } catch (\Exception $e) { // don't do anything } } } // start with a fresh database print "\nDropping main database...\n"; if ($runForReal) { MongoStore::dropAllCollections(SF_DATABASE); } print "\nDropping other dbs on the server (like test dbs)\n"; $cmd = "mongo --quiet {$this->hostOption} --eval 'db.getMongo().getDBNames().forEach(function(i){ " . "if (i.indexOf(\"sf_\") == 0 || i.indexOf(\"scriptureforge\") == 0) { " . "print(\"Dropping \" + i); db.getSiblingDB(i).dropDatabase()}})'"; $this->Execute($runForReal, $cmd); if (is_dir($archivePath)) { print "\nExtracting archives...\n"; foreach (glob("{$archivePath}/*.tgz") as $filename) { print "Extracting {$filename}\n"; $cmd = "tar -xzf {$filename} -C {$archivePath}"; $this->Execute($runForReal, $cmd); } print "\nEnsure www-data has permissions...\n"; $cmd = "sudo chgrp -R www-data {$archivePath}/var/www"; $this->Execute($runForReal, $cmd); $cmd = "sudo chown -R www-data:fieldworks {$archivePath}/var/lib"; $this->Execute($runForReal, $cmd); print "\nRestoring mongodb...\n"; $mongodbBackup = $archivePath . "/mongo_backup"; $cmd = "mongorestore {$this->hostOption} {$mongodbBackup}"; $this->Execute($runForReal, $cmd); print "\nUpdating DB site names...\n"; $this->UpdateDBSiteName($runForReal); print "\nRestoring assets...\n"; $cmd = "rsync -rzlt --chmod=Dug=rwx,Fug=rw,o-rwx --group " . "--delete-during --stats --rsync-path='sudo rsync' " . "--exclude=sfchecks " . "{$archivePath}/var/www/languageforge.org/htdocs/assets/ " . "{$this->lfAssetsPath}/htdocs/assets/"; $this->Execute($runForReal, $cmd); $cmd = "rsync -rzlt --chmod=Dug=rwx,Fug=rw,o-rwx --group " . "--delete-during --stats --rsync-path='sudo rsync' " . "--exclude=lexicon --exclude=semdomtrans " . "{$archivePath}/var/www/scriptureforge.org/htdocs/assets/ " . "{$this->sfAssetsPath}/htdocs/assets/"; $this->Execute($runForReal, $cmd); $cmd = "sudo rm -R {$this->lfmergeSendReceivePath}/state/*"; $this->Execute($runForReal, $cmd); $cmd = "sudo rm -R {$this->lfmergeSendReceivePath}/webwork/*"; $this->Execute($runForReal, $cmd); $cmd = "rsync -rzlt --chmod=Dug=rwx,Fug=rw,o-rwx --group " . "--delete-during --stats --rsync-path='sudo rsync' " . "{$archivePath}{$this->lfmergeSendReceivePath} {$this->lfmergeSendReceivePath}"; $this->Execute($runForReal, $cmd); print "\nCleanup extracted files...\n"; $cmd = "sudo rm -R {$archivePath}/var"; $this->Execute($runForReal, $cmd); $cmd = "sudo rm -R {$archivePath}/mongo_backup"; $this->Execute($runForReal, $cmd); } else { print "\nCreating local user: admin password: password\n"; if ($runForReal) { $scriptureforgeWebsite = Website::get('scriptureforge.org'); $languageforgeWebsite = Website::get('languageforge.org'); $adminUser = UserCommands::createUser(array('id' => '', 'name' => 'Admin', 'email' => '*****@*****.**', 'username' => 'admin', 'password' => 'password', 'active' => true, 'role' => SystemRoles::SYSTEM_ADMIN), $languageforgeWebsite); } } }
<?php use Api\Library\Shared\Website; $rootPath = realpath(__DIR__ . '/../../') . '/'; // Fake app path define define('APPPATH', $rootPath . 'src/'); require_once APPPATH . 'vendor/autoload.php'; define('TestMode', true); define('TestPath', $rootPath . 'test/php/'); define('TestLibPath', $rootPath . 'test/lib/'); define('SimpleTestPath', $rootPath . 'src/vendor/simpletest/simpletest/'); define('SourcePath', $rootPath . 'src/'); define('SF_DATABASE', 'scriptureforge_test'); define('SF_TESTPROJECT', 'Test Project'); define('SF_TESTPROJECTCODE', 'TestCode1'); define('SF_TESTPROJECT2', 'Test Project2'); define('SF_TESTPROJECTCODE2', 'TestCode2'); define('BCRYPT_COST', 7); global $WEBSITE; $WEBSITE = Website::get('dev.scriptureforge.org');
/** * @return Website */ public function website() { return Website::get($this->siteName); }