function testEncode_EntriesAndLoadPartial_PartialOk()
 {
     $userId = self::$environ->createUser('User', 'Name', '*****@*****.**');
     $user = new UserModel($userId);
     $user->role = SystemRoles::USER;
     $project = self::$environ->createProject(SF_TESTPROJECT, SF_TESTPROJECTCODE);
     $projectId = $project->id->asString();
     $project->addUser($userId, ProjectRoles::CONTRIBUTOR);
     $user->addProject($projectId);
     $user->write();
     $project->write();
     $sense = new LexSense();
     $sense->definition->form('en', 'apple');
     for ($i = 9; $i >= 0; $i--) {
         $entry = new LexEntryModel($project);
         $entry->lexeme->form('th', 'Apfel' . $i);
         $entry->senses[] = $sense;
         $entry->write();
     }
     $result = LexDbeDto::encode($projectId, $userId, null, 5);
     $this->assertCount(5, $result['entries']);
     $this->assertEquals(5, $result['itemCount']);
     $this->assertEquals(10, $result['itemTotalCount']);
     $this->assertEquals('Apfel0', $result['entries'][0]['lexeme']['th']['value'], 'Apfel0 should sort first');
     $this->assertEquals('Apfel4', $result['entries'][4]['lexeme']['th']['value'], 'Apfel4 should sort first');
     $result = LexDbeDto::encode($projectId, $userId, null, 9);
     $this->assertCount(1, $result['entries']);
     $this->assertEquals(1, $result['itemCount']);
     $this->assertEquals(10, $result['itemTotalCount']);
     $this->assertEquals('Apfel0', $result['entries'][0]['lexeme']['th']['value'], 'Apfel0 should sort first');
 }
 public function checkUser($userId)
 {
     $this->usersChecked++;
     $user = new UserModel($userId);
     if ($this->makeChanges) {
         $user->write();
     }
 }
 public static function getProjectId(Application $app, Website $website)
 {
     $projectId = $app['session']->get('projectId');
     if (!$projectId) {
         $userId = self::getUserId($app);
         $user = new UserModel($userId);
         $projectId = $user->getCurrentProjectId($website);
     }
     return $projectId;
 }
 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 getProjectMember($projectId, $userName)
 {
     $userId = $this->createUser($userName, $userName, '*****@*****.**');
     $user = new UserModel($userId);
     $user->addProject($projectId);
     $user->write();
     $project = new ProjectModel($projectId);
     $project->addUser($userId, ProjectRoles::CONTRIBUTOR);
     $project->write();
     return $userId;
 }
 public function run($mode = 'test')
 {
     $testMode = $mode == 'test';
     $message = "";
     $userlist = new UserListModel();
     $userlist->read();
     $badUserRoles = 0;
     foreach ($userlist->entries as $userParams) {
         // foreach existing user
         $userId = $userParams['id'];
         $user = new UserModel($userId);
         if (!$user->role) {
             $user->role = SystemRoles::USER;
             if (!$testMode) {
                 $user->write();
             }
             $badUserRoles++;
             $message .= "Fixed role of user {$userId}\n";
         }
     }
     if ($badUserRoles > 0) {
         $message .= "\n\nFixed {$badUserRoles} non-existent user roles from the users collection\n\n";
     } else {
         $message .= "\n\nNo non-existent user roles found in the users collection\n\n";
     }
     $projectlist = new ProjectListModel();
     $projectlist->read();
     $badProjectUserRoles = 0;
     foreach ($projectlist->entries as $projectParams) {
         // foreach existing project
         $projectId = $projectParams['id'];
         $project = new ProjectModel($projectId);
         $projectUserRefs = array_keys($project->users);
         foreach ($projectUserRefs as $ref) {
             // foreach user that is a member of this project
             if (!isset($project->users[$ref]->role)) {
                 $project->users[$ref]->role = ProjectRoles::CONTRIBUTOR;
                 $badProjectUserRoles++;
                 $message .= "Fixed role of user {$ref} for project {$projectId}\n";
             }
         }
         if (!$testMode) {
             $project->write();
         }
     }
     if ($badProjectUserRoles > 0) {
         $message .= "\n\nFixed {$badProjectUserRoles} non-existent user roles from the projects collection\n\n";
     } else {
         $message .= "\n\nNo non-existent user roles found in the projects collection\n\n";
     }
     return $message;
 }
 public function encodeIdReference($key, $model)
 {
     if ($key == 'createdByUserRef' || $key == 'modifiedByUserRef') {
         $user = new UserModel();
         if ($user->exists($model->asString())) {
             $user->read($model->asString());
             return array('id' => $user->id->asString(), 'avatar_ref' => $user->avatar_ref, 'name' => $user->name, 'username' => $user->username);
         } else {
             return '';
         }
     } else {
         return $model->asString();
     }
 }
 public function encodeIdReference($key, $model)
 {
     if ($key == 'ownerRef') {
         $user = new UserModel();
         if ($user->exists($model->asString())) {
             $user->read($model->asString());
             return array('id' => $user->id->asString(), 'username' => $user->username);
         } else {
             return '';
         }
     } else {
         return $model->asString();
     }
 }
 public function forgotPassword(Request $request, Application $app)
 {
     $usernameOrEmail = $request->request->get('_username');
     $user = new UserModel();
     if (!$user->readByUsernameOrEmail($usernameOrEmail)) {
         $app['session']->getFlashBag()->add('errorMessage', 'User not found.');
         return $this->view($request, $app, 'forgot_password');
     }
     $identityCheck = UserCommands::checkIdentity($user->username, $user->email, $this->website);
     if (!$identityCheck->usernameExistsOnThisSite) {
         $user->siteRole[$this->website->domain] = $this->website->userDefaultSiteRole;
     }
     Communicate::sendForgotPasswordVerification($user, $this->website);
     $app['session']->getFlashBag()->add('infoMessage', 'Password Reset email sent for username "' . $usernameOrEmail . '"');
     return $app->redirect('/auth/login');
 }
 public function encodeIdReference($key, $model)
 {
     // TODO ownerRef is declared in ProjectModel as an IdReference.  Here, it gets encoded as an Array 2014-08 DDW
     // Trello: https://trello.com/c/Zw0aLLYv
     if ($key == 'ownerRef') {
         $user = new UserModel();
         if ($user->exists($model->asString())) {
             $user->read($model->asString());
             return array('id' => $user->id->asString(), 'username' => $user->username);
         } else {
             return '';
         }
     } else {
         return $model->asString();
     }
 }
 public function testUserCanAccessMethod_projectSettings_projectMember_false()
 {
     $userId = self::$environ->createUser('user', 'user', '*****@*****.**', SystemRoles::USER);
     $user = new UserModel($userId);
     $project = self::$environ->createProject('projectForTest', 'projTestCode');
     $projectId = $project->id->asString();
     $project->addUser($userId, ProjectRoles::CONTRIBUTOR);
     $project->appName = 'sfchecks';
     $project->write();
     $user->addProject($projectId);
     $user->write();
     $project = ProjectModel::getById($projectId);
     $rh = new RightsHelper($userId, $project, self::$environ->website);
     $result = $rh->userCanAccessMethod('project_settings', array());
     $this->assertFalse($result);
 }
 public static function run($mode = 'test')
 {
     $testMode = $mode != 'run';
     print "Remove users who have no siteRole AND are not system admins AND never logged in\n\n";
     $userlist = new CustomUserListModel();
     $userlist->read();
     print "Found " . count($userlist->entries) . " users in the userlist\n";
     $usersMissingSiteRole = 0;
     $now = new \DateTime();
     foreach ($userlist->entries as $userParams) {
         // foreach user from the custom list
         // if last_login has any valid meaning, we need UserProfileModel.  Otherwise, can use UserModel
         $user = new UserModel($userParams['id']);
         // Since UserProfileModel::last_login isn't being populated, we use the following criteria that a user never logged in:
         // emailPending (account never activated), no username, and validationExpirationDate expired
         if ($user->role != SystemRoles::SYSTEM_ADMIN && count(array_keys($user->siteRole->getArrayCopy())) == 0 && (!empty($user->emailPending) && empty($user->username) && $user->validationExpirationDate < $now)) {
             if (!$testMode) {
                 $user->remove();
             }
             $usersMissingSiteRole++;
             print "Removed [id: {$user->id} ";
             // Some of these criteria are never printed because of newer checks for empty
             if (!empty($user->username)) {
                 print "username: {$user->username}; ";
             }
             if (!empty($user->email)) {
                 print "email: {$user->email}; ";
             }
             if (!empty($user->emailPending)) {
                 print "emailPending: {$user->emailPending}; ";
             }
             if (!empty($user->last_login)) {
                 print "lastLogin: {$user->last_login}; ";
             }
             if (!empty($user->role)) {
                 print "role: {$user->role}; ";
             }
             print "]\n";
         }
     }
     if ($usersMissingSiteRole > 0) {
         print "\n\nRemoved {$usersMissingSiteRole} users missing siteRole from the users collection\n\n";
     } else {
         print "\n\nNo user missing siteRoles found in the users collection\n\n";
     }
 }
 /**
  * @param string $userId
  * @param Website $website
  * @param boolean $isArchivedList - set true to list archived projects
  * @return array - the DTO array
  */
 public static function encode($userId, $website, $isArchivedList = false)
 {
     $user = new UserModel($userId);
     $canListAllProjects = $user->hasRight(Domain::PROJECTS + Operation::VIEW, $website);
     $projectList = new ProjectList_UserModel($website->domain);
     if ($canListAllProjects) {
         $projectList->readAll($isArchivedList);
     } else {
         $projectList->readUserProjects($userId);
     }
     $data = array();
     $data['entries'] = array();
     $count = 0;
     foreach ($projectList->entries as $entry) {
         $project = new ProjectModel($entry['id']);
         $role = ProjectRoles::NONE;
         if (count($project->users) > 0) {
             if (isset($project->users[$userId]) && isset($project->users[$userId]->role)) {
                 $role = $project->users[$userId]->role;
             }
         }
         $entry['role'] = $role;
         if (array_key_exists('ownerRef', $entry) and $entry['ownerRef']) {
             $entry['ownerId'] = strval($entry['ownerRef']);
         } else {
             $entry['ownerId'] = '';
             // for legacy projects that don't have an owner
         }
         unset($entry['ownerRef']);
         $entry['dateModified'] = $project->dateModified->asDateTimeInterface()->format(\DateTime::RFC2822);
         $data['entries'][] = $entry;
         $count++;
     }
     $data['count'] = $count;
     // Default sort list on project names
     usort($data['entries'], function ($a, $b) {
         $sortOn = 'projectName';
         if (array_key_exists($sortOn, $a) && array_key_exists($sortOn, $b)) {
             return strtolower($a[$sortOn]) > strtolower($b[$sortOn]) ? 1 : -1;
         } else {
             return 0;
         }
     });
     return $data;
 }
 public function testEncode_ProjectWithUser_DtoCorrect()
 {
     $environ = new MongoTestEnvironment();
     $environ->clean();
     $userId = $environ->createUser("User", "Name", "*****@*****.**");
     $user = new UserModel($userId);
     $user->role = SystemRoles::USER;
     $project = $environ->createProject(SF_TESTPROJECT, SF_TESTPROJECTCODE);
     $projectId = $project->id->asString();
     $project->addUser($userId, ProjectRoles::CONTRIBUTOR);
     $user->addProject($projectId);
     $user->write();
     $project->write();
     $dto = ManageUsersDto::encode($projectId);
     $this->assertEquals(1, $dto['userCount']);
     $this->assertInternalType('array', $dto['users']);
     $this->assertEquals($userId, $dto['users'][0]['id']);
     $this->assertEquals('Name', $dto['users'][0]['name']);
     $this->assertEquals(ProjectRoles::CONTRIBUTOR, $dto['users'][0]['role']);
 }
 public function __construct($id = '')
 {
     $this->id = new Id();
     $this->projectsProperties = new MapOf(function () {
         return new ProjectProperties();
     });
     $this->projectUserProfiles = new MapOf(function () {
         return new SfchecksUserProfile();
     });
     parent::__construct($id);
 }
 public function testEncode_ProjectWith2Users1Unvalidated_DtoCorrect1User()
 {
     $environ = new MongoTestEnvironment();
     $environ->clean();
     $user1Id = $environ->createUser('', '', '');
     $user1 = new UserModel($user1Id);
     $user1->role = SystemRoles::USER;
     $user2Id = $environ->createUser('User', 'Name', '*****@*****.**');
     $user2 = new UserModel($user2Id);
     $user2->role = SystemRoles::USER;
     $project = $environ->createProject(SF_TESTPROJECT, SF_TESTPROJECTCODE);
     $projectId = $project->id->asString();
     $project->addUser($user1Id, ProjectRoles::CONTRIBUTOR);
     $user1->addProject($projectId);
     $user1->write();
     $project->addUser($user2Id, ProjectRoles::CONTRIBUTOR);
     $user2->addProject($projectId);
     $user2->write();
     $project->write();
     $text1 = new TextModel($project);
     $text1->title = 'Some Title';
     $text1->write();
     $text2 = new TextModel($project);
     $text2->title = 'Archived Title';
     $text2->isArchived = true;
     $text2->write();
     $dto = ProjectSettingsDto::encode($projectId, $user2Id);
     $this->assertEquals(1, $dto['count']);
     $this->assertInternalType('array', $dto['entries']);
     $this->assertEquals($user2Id, $dto['entries'][0]['id']);
     $this->assertEquals('Name', $dto['entries'][0]['name']);
     $this->assertEquals(ProjectRoles::CONTRIBUTOR, $dto['entries'][0]['role']);
     $this->assertCount(1, $dto['archivedTexts']);
     $this->assertEquals('Archived Title', $dto['archivedTexts'][0]['title']);
     $this->assertTrue(count($dto['rights']) > 0, 'No rights in dto');
     $this->assertEquals('settings', $dto['bcs']['op']);
     $this->assertEquals(array('id' => $projectId, 'crumb' => SF_TESTPROJECT), $dto['bcs']['project']);
     $this->assertFalse(isset($dto['project']['users']));
     $this->assertEquals($projectId, $dto['project']['id']);
 }
 public function testUpdateProject_ReadOnlyProperties_PropertiesNotChanged()
 {
     $environ = new MongoTestEnvironment();
     $environ->clean();
     $userId = $environ->createUser('User', 'Name', '*****@*****.**');
     $user = new UserModel($userId);
     $user->role = SystemRoles::USER;
     $hackerId = $environ->createUser('Hacker', 'Hacker', '*****@*****.**');
     $hacker = new UserModel($hackerId);
     $hacker->role = SystemRoles::USER;
     $hacker->write();
     $project = $environ->createProject(SF_TESTPROJECT, SF_TESTPROJECTCODE);
     $projectId = $project->id->asString();
     $project->addUser($userId, ProjectRoles::MANAGER);
     $project->ownerRef = $user->id->asString();
     $user->addProject($projectId);
     $user->write();
     $project->write();
     $hackedData = 'hacked';
     $params = ProjectCommands::readProject($projectId);
     $params['projectName'] = 'new project name';
     $params['id'] = $hackedData;
     $params['ownerRef'] = $hacker->id->asString();
     $params['users'][$hacker->id->asString()]['role'] = ProjectRoles::MANAGER;
     $params['projectCode'] = $hackedData;
     $params['siteName'] = $hackedData;
     $params['appName'] = $hackedData;
     $params['userProperties']['userProfilePickLists']['city']['name'] = $hackedData;
     SfchecksProjectCommands::updateProject($projectId, $userId, $params);
     $updatedProject = ProjectCommands::readProject($projectId);
     $this->assertEquals('new project name', $updatedProject['projectName']);
     $this->assertNotEquals($hackedData, $updatedProject['id']);
     $this->assertNotEquals($hacker->id->asString(), $updatedProject['ownerRef']);
     $this->assertFalse(isset($updatedProject['users'][$hacker->id->asString()]));
     $this->assertNotEquals($hackedData, $updatedProject['projectCode']);
     $this->assertNotEquals($hackedData, $updatedProject['siteName']);
     $this->assertNotEquals($hackedData, $updatedProject['appName']);
     $this->assertNotEquals($hackedData, $updatedProject['userProperties']['userProfilePickLists']['city']['name']);
 }
 public function testWrite_TwoModels_ReadBackBothModelsOk()
 {
     $model = new UserModel();
     $model->email = '*****@*****.**';
     $model->username = '******';
     $id = $model->write();
     $this->assertNotNull($id);
     $this->assertInternalType('string', $id);
     $otherModel = new UserModel($id);
     $this->assertEquals($id, $otherModel->id->asString());
     $this->assertEquals('*****@*****.**', $otherModel->email);
     $this->assertEquals('SomeUser', $otherModel->username);
     $model = new ProjectModel();
     $model->language = 'SomeLanguage';
     $model->projectName = 'SomeProject';
     $id = $model->write();
     $this->assertNotNull($id);
     $this->assertInternalType('string', $id);
     $otherModel = new ProjectModel($id);
     $this->assertEquals($id, $otherModel->id->asString());
     $this->assertEquals('SomeLanguage', $otherModel->language);
     $this->assertEquals('SomeProject', $otherModel->projectName);
 }
 public function testEncode_ProjectWithSendReceive_DtoCorrect()
 {
     $userId = self::$environ->createUser('User', 'Name', '*****@*****.**');
     $user = new UserModel($userId);
     $user->role = SystemRoles::USER;
     $project = self::$environ->createProject(SF_TESTPROJECT, SF_TESTPROJECTCODE);
     $projectId = $project->id->asString();
     $project->interfaceLanguageCode = 'en';
     $project->projectCode = 'lf';
     $project->featured = true;
     $project->sendReceiveProjectIdentifier = 'test-sr-identifier';
     $project->sendReceiveProject = new SendReceiveProjectModel('test-sr-name', '', 'manager');
     $project->addUser($userId, ProjectRoles::CONTRIBUTOR);
     $user->addProject($projectId);
     $user->write();
     $project->write();
     $dto = LexProjectDto::encode($projectId);
     // test for a few default values
     $this->assertEquals('en', $dto['project']['interfaceLanguageCode']);
     $this->assertEquals('lf', $dto['project']['projectCode']);
     $this->assertTrue($dto['project']['featured']);
     $this->assertEquals('test-sr-identifier', $dto['project']['sendReceive']['project']['identifier']);
 }
 public function testEncode_ProjectWithUser_DtoCorrect()
 {
     $environ = new MongoTestEnvironment();
     $environ->clean();
     $userId = $environ->createUser("User", "Name", "*****@*****.**");
     $user = new UserModel($userId);
     $project = $environ->createProject(SF_TESTPROJECT, SF_TESTPROJECTCODE, 'sfchecks');
     $project->ownerRef->id = $userId;
     $projectId = $project->id->asString();
     $project->addUser($userId, ProjectRoles::CONTRIBUTOR);
     $user->addProject($projectId);
     $user->write();
     $project->write();
     $dto = ProjectManagementDto::encode($projectId);
     $this->assertTrue(count($dto['reports']) > 0);
     $foundUserEngagementReport = false;
     foreach ($dto['reports'] as $report) {
         if ($report['id'] == 'sfchecks_userEngagementReport') {
             $foundUserEngagementReport = true;
         }
     }
     $this->assertTrue($foundUserEngagementReport);
 }
 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);
 }
 /**
  * @param string $projectId
  * @param string $userId
  * @param Website $website
  * @param string $appName - refers to the application being used by the user
  * @return array
  */
 public static function getSessionData($projectId, $userId, $website, $appName = '')
 {
     $sessionData = array();
     $sessionData['userId'] = (string) $userId;
     $sessionData['baseSite'] = $website->base;
     // Rights
     $user = new UserModel($userId);
     $sessionData['userSiteRights'] = $user->getRightsArray($website);
     $sessionData['username'] = $user->username;
     if ($projectId) {
         $project = ProjectModel::getById($projectId);
         $sessionData['project'] = array();
         $sessionData['project']['id'] = (string) $projectId;
         $sessionData['project']['projectName'] = $project->projectName;
         if ($project->isArchived) {
             $sessionData['project']['projectName'] .= " [ARCHIVED]";
         }
         $sessionData['project']['appName'] = $project->appName;
         $sessionData['project']['appLink'] = "/app/{$project->appName}/{$projectId}/";
         $sessionData['project']['ownerRef'] = $project->ownerRef->asString();
         $sessionData['project']['userIsProjectOwner'] = $project->isOwner($userId);
         $sessionData['project']['slug'] = $project->databaseName();
         $sessionData['project']['isArchived'] = $project->isArchived;
         $sessionData['userProjectRights'] = $project->getRightsArray($userId);
         $sessionData['projectSettings'] = $project->getPublicSettings($userId);
     }
     if ($appName) {
         $sessionData['helps'] = HelpContentCommands::getSessionData($appName, $website);
     }
     // File Size
     $postMax = self::fromValueWithSuffix(ini_get("post_max_size"));
     $uploadMax = self::fromValueWithSuffix(ini_get("upload_max_filesize"));
     $fileSizeMax = min(array($postMax, $uploadMax));
     $sessionData['fileSizeMax'] = $fileSizeMax;
     //return JsonEncoder::encode($sessionData);  // This is handled elsewhere
     return $sessionData;
 }
 public function testEncode_2Questions1Archived_DtoCorrect1ArchivedQuestion()
 {
     $environ = new MongoTestEnvironment();
     $environ->clean();
     $userId = $environ->createUser("User", "Name", "*****@*****.**");
     $user = new UserModel($userId);
     $user->role = SystemRoles::USER;
     $project = $environ->createProject(SF_TESTPROJECT, SF_TESTPROJECTCODE);
     $projectId = $project->id->asString();
     $project->addUser($userId, ProjectRoles::MANAGER);
     $user->addProject($projectId);
     $user->write();
     $project->write();
     $text = new TextModel($project);
     $text->title = "Text Title";
     $textId = $text->write();
     $question1 = new QuestionModel($project);
     $question1->title = "Some Title";
     $question1->textRef->id = $textId;
     $question1->write();
     $question2 = new QuestionModel($project);
     $question2->title = "Archived Title";
     $question2->textRef->id = $textId;
     $question2->isArchived = true;
     $question2->write();
     $dto = TextSettingsDto::encode($projectId, $textId, $userId);
     $this->assertInternalType('array', $dto['text']);
     $this->assertEquals($textId, $dto['text']['id']);
     $this->assertEquals('Text Title', $dto['text']['title']);
     $this->assertInternalType('array', $dto['archivedQuestions']);
     $this->assertCount(1, $dto['archivedQuestions']);
     $this->assertEquals('Archived Title', $dto['archivedQuestions'][0]['title']);
     $this->assertTrue(count($dto['rights']) > 0, "No rights in dto");
     $this->assertEquals('settings', $dto['bcs']['op']);
     $this->assertEquals(array('id' => $projectId, 'crumb' => SF_TESTPROJECT), $dto['bcs']['project']);
 }
 protected function populateHeaderMenuViewdata()
 {
     $this->data['isAdmin'] = false;
     // setup specific variables for header
     $this->data['isLoggedIn'] = $this->_isLoggedIn;
     $this->data['showHelpButton'] = $this->_showHelp;
     $featuredProjectList = new FeaturedProjectListModel();
     $featuredProjectList->read();
     $this->data['featuredProjects'] = $featuredProjectList->entries;
     if ($this->_isLoggedIn) {
         if ($this->_user->role) {
             $this->data['isAdmin'] = SystemRoles::hasRight($this->_user->role, Domain::USERS + Operation::CREATE);
         }
         $this->data['userName'] = $this->_user->username;
         $this->data['smallAvatarUrl'] = '/Site/views/shared/image/avatar/' . $this->_user->avatar_ref;
         $projects = $this->_user->listProjects($this->website->domain);
         $this->data['projects_count'] = $projects->count;
         $this->data['projects'] = $projects->entries;
     }
 }
 public function __construct($id = '')
 {
     $this->fruitsMap = new MapOf(function ($data) {
         if (array_key_exists('numOfSlices', $data)) {
             return new Apple();
         } elseif (array_key_exists('peelThickness', $data)) {
             return new Orange();
         } else {
             return new Fruit();
         }
     });
     $this->fruitsArray = new ArrayOf(function ($data) {
         if (array_key_exists('numOfSlices', $data)) {
             return new Apple();
         } elseif (array_key_exists('peelThickness', $data)) {
             return new Orange();
         } else {
             return new Fruit();
         }
     });
     parent::__construct($id);
 }
 public function run($mode = 'test')
 {
     $testMode = $mode == 'test';
     $message = "";
     $userlist = new UserListModel();
     $userlist->read();
     $userIds = array_map(function ($e) {
         return $e['id'];
     }, $userlist->entries);
     $projectlist = new ProjectListModel();
     $projectlist->read();
     $projectIds = array_map(function ($e) {
         return $e['id'];
     }, $projectlist->entries);
     $deadProjectLinks = 0;
     foreach ($userlist->entries as $userParams) {
         // foreach existing user
         $userId = $userParams['id'];
         $user = new UserModel($userId);
         $userProjectRefs = $user->projects->refs;
         foreach ($userProjectRefs as $ref) {
             // foreach project the user belongs to
             if (!in_array($ref, $projectIds)) {
                 $user->removeProject($ref);
                 // remove dead project link
                 $deadProjectLinks++;
                 $message .= "Removed dead project link {$ref} from user {$userId}\n";
             }
         }
         if (!$testMode) {
             $user->write();
         }
     }
     if ($deadProjectLinks > 0) {
         $message .= "\n\nRemoved {$deadProjectLinks} dead project links from the users collection\n\n";
     } else {
         $message .= "\n\nNo dead project links were found\n\n";
     }
     $deadUserLinks = 0;
     foreach ($projectlist->entries as $projectParams) {
         // foreach existing project
         $projectId = $projectParams['id'];
         $project = new ProjectModel($projectId);
         $projectUserRefs = array_keys($project->users);
         foreach ($projectUserRefs as $ref) {
             // foreach user that is a member of this project
             if (!in_array($ref, $userIds)) {
                 $project->removeUser($ref);
                 // remove dead user link
                 $deadUserLinks++;
                 $message .= "Removed dead user link {$ref} for project {$projectId}\n";
             }
         }
         if (!$testMode) {
             $project->write();
         }
     }
     if ($deadUserLinks > 0) {
         $message .= "\n\nRemoved {$deadUserLinks} dead user links from the projects collection\n\n";
     } else {
         $message .= "\n\nNo dead user links were found\n\n";
     }
     return $message;
 }
 /**
  *
  * @param UserModel $user
  * @param UserModel $admin
  * @param ProjectModel $projectModel
  * @param Website $website
  * @param DeliveryInterface $delivery
  */
 public static function sendJoinRequest($user, $admin, $projectModel, $website, DeliveryInterface $delivery = null)
 {
     $user->setValidation(7);
     $user->write();
     $to = array($admin->email => $admin->name);
     $subject = $user->name . ' join request';
     $vars = array('user' => $user, 'admin' => $admin, 'project' => $projectModel, 'link' => $website->baseUrl() . '/app/usermanagement/' . $projectModel->id->asString() . '#/joinRequests');
     self::sendTemplateEmail($to, $subject, 'JoinRequest', $vars, $website, $delivery);
 }
 public function testMultipleUnreadModels_multipleUsers_multipleUpdates_multipleVisitsToQuestionPage_usersHaveDifferentUnreadStates()
 {
     $project = self::$environ->createProject("unread_test", "unreadCode");
     $projectId = $project->id->asString();
     $userId1 = self::$environ->createUser('user1', 'user1', 'user1');
     $user1 = new UserModel($userId1);
     $user1->addProject($project->id->asString());
     $user1->write();
     $userId2 = self::$environ->createUser('user2', 'user2', 'user2');
     $user2 = new UserModel($userId2);
     $user2->addProject($project->id->asString());
     $user2->write();
     $userId3 = self::$environ->createUser('user3', 'user3', 'user3');
     $user3 = new UserModel($userId3);
     $user3->addProject($project->id->asString());
     $user3->write();
     $answer1 = array('content' => "test answer 1", 'id' => '');
     $answer2 = array('content' => "test answer 2", 'id' => '');
     $text = new TextModel($project);
     $text->title = "Text 1";
     $usx = MongoTestEnvironment::usxSample();
     $text->content = $usx;
     $textId = $text->write();
     $question = new QuestionModel($project);
     $question->title = "test question";
     $question->textRef->id = $textId;
     $questionId = $question->write();
     QuestionCommands::updateAnswer($projectId, $questionId, $answer1, $userId1);
     QuestionCommands::updateAnswer($projectId, $questionId, $answer2, $userId2);
     // the answer author does NOT get their answer marked as unread
     $unreadModel = new UnreadAnswerModel($userId1, $projectId, $questionId);
     $this->assertCount(1, $unreadModel->unreadItems());
     // the answer author does NOT get their answer marked as unread
     $unreadModel = new UnreadAnswerModel($userId2, $projectId, $questionId);
     $this->assertCount(1, $unreadModel->unreadItems());
     $unreadModel = new UnreadAnswerModel($userId3, $projectId, $questionId);
     $this->assertCount(2, $unreadModel->unreadItems());
     // user1 visits question page
     QuestionCommentDto::encode($projectId, $questionId, $userId1);
     $unreadModel = new UnreadAnswerModel($userId1, $projectId, $questionId);
     $this->assertCount(0, $unreadModel->unreadItems());
     $unreadModel = new UnreadAnswerModel($userId2, $projectId, $questionId);
     $this->assertCount(1, $unreadModel->unreadItems());
     $unreadModel = new UnreadAnswerModel($userId3, $projectId, $questionId);
     $this->assertCount(2, $unreadModel->unreadItems());
     // user2 visits question page
     QuestionCommentDto::encode($projectId, $questionId, $userId2);
     $unreadModel = new UnreadAnswerModel($userId1, $projectId, $questionId);
     $this->assertCount(0, $unreadModel->unreadItems());
     $unreadModel = new UnreadAnswerModel($userId2, $projectId, $questionId);
     $this->assertCount(0, $unreadModel->unreadItems());
     $unreadModel = new UnreadAnswerModel($userId3, $projectId, $questionId);
     $this->assertCount(2, $unreadModel->unreadItems());
     // user2 visits question page
     QuestionCommentDto::encode($projectId, $questionId, $userId3);
     $unreadModel = new UnreadAnswerModel($userId1, $projectId, $questionId);
     $this->assertCount(0, $unreadModel->unreadItems());
     $unreadModel = new UnreadAnswerModel($userId2, $projectId, $questionId);
     $this->assertCount(0, $unreadModel->unreadItems());
     $unreadModel = new UnreadAnswerModel($userId3, $projectId, $questionId);
     $this->assertCount(0, $unreadModel->unreadItems());
 }
 /**
  * Removes users from the project (two-way unlink)
  * @param string $projectId
  * @param array<string> $userIds
  * @return string $projectId
  * @throws \Exception
  */
 public static function removeUsers($projectId, $userIds)
 {
     $project = new ProjectModel($projectId);
     foreach ($userIds as $userId) {
         // Guard against removing project owner
         if ($userId != $project->ownerRef->id) {
             $user = new UserModel($userId);
             $project->removeUser($user->id->asString());
             $user->removeProject($project->id->asString());
             $project->write();
             $user->write();
         } else {
             throw new \Exception("Cannot remove project owner");
         }
     }
     return $projectId;
 }
 public function encodeIdReference($key, $model)
 {
     if ($model->asString() == '') {
         return '';
     }
     if ($key == 'userRef' || $key == 'userRef2') {
         $user = new UserModel();
         if ($user->exists($model->asString())) {
             $user->read($model->asString());
             return array('id' => $user->id->asString(), 'avatar_ref' => $user->avatar_ref, 'username' => $user->username);
         } else {
             return '';
         }
     } elseif ($key == 'projectRef') {
         $project = new ProjectModel($model->asString());
         return array('id' => $project->id->asString(), 'type' => $project->appName);
     } elseif ($key == 'textRef') {
         $text = new TextModel($this->_project);
         if ($text->exists($model->asString())) {
             return $model->asString();
         } else {
             return '';
         }
     } elseif ($key == 'questionRef') {
         $question = new QuestionModel($this->_project);
         if ($question->exists($model->asString())) {
             return $model->asString();
         } else {
             return '';
         }
     } elseif ($key == 'entryRef') {
         $entry = new LexEntryModel($this->_project);
         if ($entry->exists($model->asString())) {
             return $model->asString();
         } else {
             return '';
         }
     } else {
         return $model->asString();
     }
 }