This file is part of Garden. Garden is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Garden is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Garden. If not, see . Contact Vanilla Forums Inc. at support [at] vanillaforums [dot] com
Inheritance: extends Gdn_Model
コード例 #1
0
ファイル: Admin.php プロジェクト: FlynnFang/cyfyy
 /**
  *
  * 过滤器
  * @param unknown_type $filterChain
  */
 public function filterCheckAdmin($filterChain)
 {
     //未登录,跳转
     if (!($uid = $this->isAdmin())) {
         $this->redirect(Yii::app()->baseUrl . "/");
     }
     //获取用户详细资料
     $adminModel = new AdminModel();
     $this->_userInfo = $adminModel->getInfoByUid($uid);
     $this->username = $this->_userInfo['username'];
     $this->hospital = $this->_userInfo['hospital'];
     $this->role = $this->_userInfo['role'];
     //账号错误
     if (!$this->_userInfo) {
         $this->_output("302", 'access deny', 'text');
     }
     $roleModel = new RoleModel();
     $role = $roleModel->getInfoByCode($this->_userInfo['role']);
     if ($role && $role['permission']) {
         $permission = explode(',', $role['permission']);
         //生成菜单
         $menuModel = new MenuModel();
         $this->menus = $menuModel->getInfoByGroup($permission);
         foreach ($this->menus as $key => $value) {
             $this->menuGroup[$value['group']] = $value['group'];
         }
     } else {
         header("HTTP/1.1 401");
         exit;
     }
     $filterChain->run();
 }
コード例 #2
0
 public function dadosAction()
 {
     $this->_helper->layout->disableLayout();
     $page = $this->_request->getParam("page", 1);
     $limit = $this->_request->getParam("rows");
     $sidx = $this->_request->getParam("sidx", 1);
     $sord = $this->_request->getParam("sord");
     $roleModel = new RoleModel();
     $role = $roleModel->fetchAll();
     $count = count($role);
     if ($count > 0) {
         $total_pages = ceil($count / $limit);
     } else {
         $total_pages = 0;
     }
     if ($page > $total_pages) {
         $page = $total_pages;
     }
     //$role = $roleModel->fetchAll(null, "$sidx $sord", $limit, ($page*$limit-$limit));
     $responce = new stdClass();
     $responce->page = $page;
     $responce->total = $total_pages;
     $responce->records = $count;
     $i = 0;
     foreach ($role as $row) {
         $responce->rows[$i]['cell'] = array($row->cdrole, $row->nmrole);
         $i++;
     }
     $this->view->dados = $responce;
 }
コード例 #3
0
 public function toString()
 {
     $Form = $this->_Sender->Form;
     $this->_Sender->addJsFile('condition.js');
     if ($Form->authenticatedPostBack()) {
         // Grab the conditions from the form and convert them to the conditions array.
         $this->Conditions($this->_FromForm());
     } else {
     }
     $this->Types = array_merge(array('' => '(' . sprintf(t('Select a %s'), t('Condition Type', 'Type')) . ')'), Gdn_Condition::AllTypes());
     //die(print_r($this->Types));
     // Get all of the permissions that are valid for the permissions dropdown.
     $PermissionModel = new PermissionModel();
     $Permissions = $PermissionModel->GetGlobalPermissions(0);
     $Permissions = array_keys($Permissions);
     sort($Permissions);
     $Permissions = array_combine($Permissions, $Permissions);
     $Permissions = array_merge(array('' => '(' . sprintf(t('Select a %s'), t('Permission')) . ')'), $Permissions);
     $this->Permissions = $Permissions;
     // Get all of the roles.
     $RoleModel = new RoleModel();
     $Roles = $RoleModel->getArray();
     $Roles = array_merge(array('-' => '(' . sprintf(t('Select a %s'), t('Role')) . ')'), $Roles);
     $this->Roles = $Roles;
     $this->Form = $Form;
     return parent::ToString();
 }
コード例 #4
0
 /**
  * 添加规则
  * @param  string  $resName
  * @param  string  $privName
  */
 protected function _add($resName, $privName)
 {
     $data = array('res_name' => $resName, 'priv_name' => $privName);
     $this->db->insert('acl_rule', $data);
     $ruleId = $this->db->lastInsertId();
     $roleModel = new RoleModel($this->_modName);
     $roleList = $roleModel->getAll();
     $data = array();
     foreach ($roleList as $role) {
         $data = array('rule_id' => $ruleId, 'role_id' => $role['role_id'], 'permit' => 0);
         $this->db->insert('acl', $data);
     }
 }
コード例 #5
0
 /**
  * 权限列表
  */
 public function assignAction()
 {
     $this->view->roles = $this->role->getAll();
     $this->view->roleId = (int) $this->_request->getParam('role_id');
     if ($this->view->roleId == 0) {
         $this->view->roleId = $this->view->roles[0]['role_id'];
         //获取第一个角色
     } elseif (!$this->role->idExists($this->view->roleId)) {
         $this->view->feedback(array('title' => '发生错误', 'message' => '指定的角色 ID 不存在或者已经被删除'));
     }
     $this->view->layout = array('title' => '管理后台 - 添加规则');
     $this->view->ruleGroup = $this->rule->getRuleGroup();
     $this->view->allowRules = $this->acl->getRoleAllowRule($this->view->roleId);
 }
コード例 #6
0
ファイル: ManageModel.php プロジェクト: arkuuu/publin
 /**
  * @param array $input
  *
  * @return bool
  */
 public function updatePermissions(array $input)
 {
     $roles = $this->getRoles();
     $model = new RoleModel($this->db);
     foreach ($roles as $role) {
         if (isset($input[$role->getId()])) {
             $permissions = array_keys($input[$role->getId()]);
             $model->updatePermissions($role->getId(), $permissions);
         } else {
             $model->updatePermissions($role->getId(), array());
         }
     }
     return true;
 }
コード例 #7
0
 /**
  * Select content based on author RoleID
  * 
  * @param array $Parameters
  * @return boolean
  */
 protected function SelectByRole($Parameters)
 {
     if (!is_array($Parameters)) {
         $RoleID = $Parameters;
     } else {
         $RoleID = GetValue('RoleID', $Parameters, NULL);
     }
     // Lookup role name -> roleID
     if (is_string($RoleID)) {
         $RoleModel = new RoleModel();
         $Roles = explode(',', $RoleID);
         $RoleID = array();
         foreach ($Roles as $TestRoleID) {
             $TestRoleID = trim($TestRoleID);
             $Role = $RoleModel->GetByName($TestRoleID);
             if (!$Role) {
                 continue;
             } else {
                 $Role = array_shift($Role);
                 $RoleID[] = GetValue('RoleID', $Role);
             }
         }
     }
     if (empty($RoleID) || !sizeof($RoleID)) {
         return FALSE;
     }
     // Check cache
     $SelectorRoleCacheKey = "modules.promotedcontent.role.{$RoleID}";
     $Content = Gdn::Cache()->Get($SelectorRoleCacheKey);
     if ($Content == Gdn_Cache::CACHEOP_FAILURE) {
         // Get everyone with this Role
         $UserIDs = Gdn::SQL()->Select('ur.UserID')->From('UserRole ur')->Where('ur.RoleID', $RoleID)->GroupBy('UserID')->Get()->Result(DATASET_TYPE_ARRAY);
         $UserIDs = ConsolidateArrayValuesByKey($UserIDs, 'UserID');
         // Get matching Discussions
         $Discussions = Gdn::SQL()->Select('d.*')->From('Discussion d')->WhereIn('d.InsertUserID', $UserIDs)->OrderBy('DateInserted', 'DESC')->Limit($this->Limit)->Get()->Result(DATASET_TYPE_ARRAY);
         // Get matching Comments
         $Comments = Gdn::SQL()->Select('c.*')->From('Comment c')->WhereIn('InsertUserID', $UserIDs)->OrderBy('DateInserted', 'DESC')->Limit($this->Limit)->Get()->Result(DATASET_TYPE_ARRAY);
         $this->JoinCategory($Comments);
         // Interleave
         $Content = $this->Union('DateInserted', array('Discussion' => $Discussions, 'Comment' => $Comments));
         $this->Prepare($Content);
         // Add result to cache
         Gdn::Cache()->Store($SelectorRoleCacheKey, $Content, array(Gdn_Cache::FEATURE_EXPIRY => $this->Expiry));
     }
     $this->Security($Content);
     $this->Condense($Content, $this->Limit);
     return $Content;
 }
コード例 #8
0
 public function GetMembersListEnh($Limit = 5, $Offset = 0, $SortOrder, $UserField)
 {
     $RoleAction = $RoleActionID = "";
     $RemoveRoleArray = C('Plugins.MembersListEnh.RoleID');
     if (isset($RemoveRoleArray)) {
         $RoleAction = $RemoveRoleArray[0];
         $RoleActionID = $RemoveRoleArray[1];
     }
     $MembersListEnhModel = new Gdn_Model('User');
     $SQL = $MembersListEnhModel->SQL->Select('*')->From('User u')->LeftJoin('UserRole ur', 'u.UserID = ur.UserID');
     if (C('EnabledPlugins.KarmaBank') == TRUE) {
         $SQL->LeftJoin('KarmaBankBalance kb', 'u.UserID = kb.UserID');
     }
     if ($UserField != "Balance") {
         $SQL->OrderBy("u.{$UserField}", $SortOrder);
     }
     if (C('EnabledPlugins.KarmaBank') == TRUE && $UserField == "Balance") {
         $SQL->OrderBy("kb.Balance", $SortOrder);
     }
     $SQL->Where('Deleted', false);
     if ($RoleAction == "Exclude") {
         $SQL->Where('ur.RoleID<>', $RoleActionID);
     }
     if ($RoleAction == "Include") {
         $SQL->Where('ur.RoleID', $RoleActionID);
     }
     // Only show user once if in more than one role.
     $SQL->GroupBy('ur.UserID');
     $Sender->UserData = $SQL->Limit($Limit, $Offset)->Get();
     RoleModel::SetUserRoles($Sender->UserData->Result());
     return $Sender->UserData;
 }
 public function down()
 {
     $role = RoleModel::findBy('first', 'roleDescription', 'Administrators');
     if ($role !== null) {
         $role->deny('compare');
         $role->save();
     }
 }
コード例 #10
0
 public function getFormCadastre()
 {
     $departmentModel = new DepartmentModel();
     $departmentData = $departmentModel->fetchAll($departmentModel->getAllActiveDepartment());
     $roleModel = new RoleModel();
     $roleData = $roleModel->fetchAll($roleModel->select());
     $departmentSupervisorModel = new DepartmentsupervisorModel();
     $departmentSupervisorData = $departmentSupervisorModel->fetchAll($departmentSupervisorModel->getAllSupervisor());
     $companyModel = new CompanyModel();
     $companyData = $companyModel->fetchAll();
     $Arraycompany = array();
     $Arraycompany['0'] = 'Selecione';
     foreach ($companyData as $company) {
         $Arraycompany[$company->cdcompany] = $company->nmfantasyname;
     }
     $this->_nmagenda = new Zend_Form_Element_Text('nmagenda');
     $this->_nmagenda->setLabel("Nome da Agenda");
     $this->_nmagenda->setRequired(true);
     $this->_nmagenda->setDecorators($this->_decoratorsRequired);
     $this->_nmagenda->setAttrib("id", "agenda_nmagendas");
     $this->_nmagenda->setAttrib("class", "alpha nameagenda");
     $this->_nmagenda->setRequired(true);
     $this->_cdcompany = new Zend_Form_Element_Select('cdcompany');
     $this->_cdcompany->setRegisterInArrayValidator(false);
     $this->_cdcompany->addMultiOptions($Arraycompany);
     $this->_cdcompany->setLabel("Empresa");
     $this->_cdcompany->setDecorators($this->_decoratorsRequired);
     $this->_cdcompany->setAttrib("id", "user_cdcompany");
     $this->_cdcompany->setAttrib("class", "alpha");
     $this->_cdcompany->setRequired(true);
     $this->_cdphysicallocation = new Zend_Form_Element_Select('cdphysicallocation');
     $this->_cdphysicallocation->setRegisterInArrayValidator(false);
     $this->_cdphysicallocation->setLabel("Localização Física");
     $this->_cdphysicallocation->addMultiOptions(array('0' => 'Selecione'));
     $this->_cdphysicallocation->setDecorators($this->_decoratorsRequired);
     $this->_cdphysicallocation->setAttrib("id", "company_physicallocation");
     $this->_cdphysicallocation->setAttrib("class", "alpha");
     $this->_cdphysicallocation->setRequired(true);
     $this->_gridhours = new Zend_Form_Element_Select('gridhours');
     $this->_gridhours->setRegisterInArrayValidator(false);
     $this->_gridhours->addMultiOptions(array('1' => 'Sim', '2' => 'Não'));
     $this->_gridhours->setLabel("Grade de Horário");
     $this->_gridhours->setDecorators($this->_decoratorsDefault);
     $this->_gridhours->setAttrib("id", "user_gridhours");
     $this->_gridhours->setRequired(false);
 }
コード例 #11
0
ファイル: class.rolecontroller.php プロジェクト: R-J/vanilla
 /**
  * Do permission check.
  *
  * @since 2.0.0
  * @access protected
  */
 protected function _permission($RoleID = null)
 {
     $this->permission(array('Garden.Settings.Manage', 'Garden.Roles.Manage'), false);
     if ($RoleID && !checkPermission('Garden.Settings.Manage')) {
         // Make sure the user can assign this role.
         $Assignable = $this->RoleModel->getAssignable();
         if (!isset($Assignable[$RoleID])) {
             throw permissionException('@' . t("You don't have permission to modify this role."));
         }
     }
     return true;
 }
コード例 #12
0
   public function Index($Keywords = '', $Page = '') {
      $this->Permission(
         array(
            'Garden.Users.Add',
            'Garden.Users.Edit',
            'Garden.Users.Delete'
         ),
         '',
         FALSE
      );
      $this->AddJsFile('jquery.gardenmorepager.js');
      $this->AddJsFile('user.js');
      $this->Title(T('Users'));

      $this->AddSideMenu('dashboard/user');

      $this->Form->Method = 'get';

      // Input Validation.
      list($Offset, $Limit) = OffsetLimit($Page, PagerModule::$DefaultPageSize);
      if (!$Keywords) {
         $Keywords = $this->Form->GetFormValue('Keywords');
         if ($Keywords)
            $Offset = 0;
      }

      // Put the Keyword back in the form
      if ($Keywords)
         $this->Form->SetFormValue('Keywords', $Keywords);

      $UserModel = new UserModel();
      //$Like = trim($Keywords) == '' ? FALSE : array('u.Name' => $Keywords, 'u.Email' => $Keywords);
      list($Offset, $Limit) = OffsetLimit($Page, 30);

      $Filter = $this->_GetFilter();
      if ($Filter)
         $Filter['Keywords'] = $Keywords;
      else
         $Filter = $Keywords;

      $this->SetData('RecordCount', $UserModel->SearchCount($Filter));
      $this->UserData = $UserModel->Search($Filter, 'u.Name', 'asc', $Limit, $Offset);
      RoleModel::SetUserRoles($this->UserData->Result());
      
      // Deliver json data if necessary
      if ($this->_DeliveryType != DELIVERY_TYPE_ALL) {
         $this->SetJson('LessRow', $this->Pager->ToString('less'));
         $this->SetJson('MoreRow', $this->Pager->ToString('more'));
         $this->View = 'users';
      }

      $this->Render();
   }
コード例 #13
0
 public function up()
 {
     $this->createTable('role', array('primary' => 'roleID'), array(array('roleID', 'integer'), array('roleDescription', 'string', array('limit' => 128, 'null' => true)), array('ACLstring', 'text', array('null' => true, 'limit' => '1M'))));
     $this->createTable('assignment', array('primary' => 'assignmentID'), array(array('dbUserID', 'integer'), array('roleID', 'integer'), array('assignmentID', 'integer'), array('comments', 'text', array('null' => true))));
     $this->createIndex('assignment', array('dbUserID', 'roleID'));
     // reset db metadata cache
     QFrame_Db_Table::scanDb();
     // give the admin user full global rights
     $adminRole = RoleModel::create(array('roleDescription' => 'Administrators'));
     $adminRole->grant('view');
     $adminRole->grant('edit');
     $adminRole->grant('approve');
     $adminRole->grant('administer');
     $adminRole->save();
     DbUserModel::findByUsername('admin')->addRole($adminRole)->save();
 }
コード例 #14
0
ファイル: HasRole.php プロジェクト: NablusTechMeetups/web
 /**
  * Assign the given role to the user.
  *
  * @param string $role
  *
  * @return mixed
  */
 public function assignRole($role, $save = true)
 {
     // if we passed a role name, find it
     if (is_string($role)) {
         $role = RoleModel::whereName($role)->first();
     }
     // if user already has the role, return true.
     if ($save and $this->roles()->find([$role->id])->count()) {
         return $role;
     }
     // assign role
     if ($save) {
         return $this->roles()->save($role);
     } else {
         return $this->roles()->detach($role);
     }
 }
コード例 #15
0
ファイル: ModelModelTest.php プロジェクト: humansky/qframe
 private function auth()
 {
     // perform mock authentication
     $auth_adapter = new QFrame_Auth_Adapter('sample1', 'password');
     $auth = Zend_Auth::getInstance();
     $auth->authenticate($auth_adapter);
     // authorize the sample1 user with the admin role and give the admin role
     // all possible global rights
     $adminRole = RoleModel::find(4);
     $adminRole->grant('view');
     $adminRole->grant('edit');
     $adminRole->grant('approve');
     $adminRole->grant('administer');
     $adminRole->save();
     $user = new DbUserModel(array('dbUserID' => 1));
     $user->addRole($adminRole);
 }
コード例 #16
0
 /**
  * Configuration of registration settings.
  */
 public function Registration($RedirectUrl = '')
 {
     $this->Permission('Garden.Registration.Manage');
     if (!C('Garden.Registration.Manage', TRUE)) {
         return Gdn::Dispatcher()->Dispatch('Default404');
     }
     $this->AddSideMenu('dashboard/settings/registration');
     $this->AddJsFile('registration.js');
     $this->Title(T('Registration'));
     // Create a model to save configuration settings
     $Validation = new Gdn_Validation();
     $ConfigurationModel = new Gdn_ConfigurationModel($Validation);
     $ConfigurationModel->SetField(array('Garden.Registration.Method' => 'Captcha', 'Garden.Registration.CaptchaPrivateKey', 'Garden.Registration.CaptchaPublicKey', 'Garden.Registration.InviteExpiration'));
     // Set the model on the forms.
     $this->Form->SetModel($ConfigurationModel);
     // Load roles with sign-in permission
     $RoleModel = new RoleModel();
     $this->RoleData = $RoleModel->GetByPermission('Garden.SignIn.Allow');
     // Get the currently selected default roles
     // $this->ExistingRoleData = Gdn::Config('Garden.Registration.DefaultRoles');
     // if (is_array($this->ExistingRoleData) === FALSE)
     //    $this->ExistingRoleData = array();
     // Get currently selected InvitationOptions
     $this->ExistingRoleInvitations = Gdn::Config('Garden.Registration.InviteRoles');
     if (is_array($this->ExistingRoleInvitations) === FALSE) {
         $this->ExistingRoleInvitations = array();
     }
     // Get the currently selected Expiration Length
     $this->InviteExpiration = Gdn::Config('Garden.Registration.InviteExpiration', '');
     // Registration methods.
     $this->RegistrationMethods = array('Captcha' => "New users fill out a simple form and are granted access immediately.", 'Approval' => "New users are reviewed and approved by an administrator (that's you!).", 'Invitation' => "Existing members send invitations to new members.");
     // Options for how many invitations a role can send out per month.
     $this->InvitationOptions = array('0' => T('None'), '1' => '1', '2' => '2', '5' => '5', '-1' => T('Unlimited'));
     // Options for when invitations should expire.
     $this->InviteExpirationOptions = array('-1 week' => T('1 week after being sent'), '-2 weeks' => T('2 weeks after being sent'), '-1 month' => T('1 month after being sent'), 'FALSE' => T('never'));
     if ($this->Form->AuthenticatedPostBack() === FALSE) {
         $this->Form->SetData($ConfigurationModel->Data);
     } else {
         // Define some validation rules for the fields being saved
         $ConfigurationModel->Validation->ApplyRule('Garden.Registration.Method', 'Required');
         // if($this->Form->GetValue('Garden.Registration.Method') != 'Closed')
         //    $ConfigurationModel->Validation->ApplyRule('Garden.Registration.DefaultRoles', 'RequiredArray');
         // Define the Garden.Registration.RoleInvitations setting based on the postback values
         $InvitationRoleIDs = $this->Form->GetValue('InvitationRoleID');
         $InvitationCounts = $this->Form->GetValue('InvitationCount');
         $this->ExistingRoleInvitations = ArrayCombine($InvitationRoleIDs, $InvitationCounts);
         $ConfigurationModel->ForceSetting('Garden.Registration.InviteRoles', $this->ExistingRoleInvitations);
         // Save!
         if ($this->Form->Save() !== FALSE) {
             $this->StatusMessage = T("Your settings have been saved.");
             if ($RedirectUrl != '') {
                 $this->RedirectUrl = $RedirectUrl;
             }
         }
     }
     $this->Render();
 }
コード例 #17
0
 /**
  *
  *
  * @throws Exception
  * @throws Gdn_UserException
  */
 public function save()
 {
     $this->permission('Garden.Users.Edit');
     if (!Gdn::request()->isAuthenticatedPostBack()) {
         throw new Exception('Requires POST', 405);
     }
     $Form = new Gdn_Form();
     if ($SSOString = $Form->getFormValue('SSOString')) {
         $Parts = explode(' ', $SSOString);
         $String = $Parts[0];
         $Data = json_decode(base64_decode($String), true);
         $User = arrayTranslate($Data, array('name' => 'Name', 'email' => 'Email', 'photourl' => 'Photo', 'client_id' => 'ClientID', 'uniqueid' => 'UniqueID'));
     } else {
         $User = $Form->formValues();
     }
     if (!isset($User['UserID']) && isset($User['UniqueID'])) {
         // Try and find the user based on SSO.
         $Auth = Gdn::userModel()->getAuthentication($User['UniqueID'], $User['ClientID']);
         if ($Auth) {
             $User['UserID'] = $Auth['UserID'];
         }
     }
     if (!isset($User['UserID'])) {
         // Add some default values to make saving easier.
         if (!isset($User['RoleID'])) {
             $DefaultRoles = RoleModel::getDefaultRoles(RoleModel::TYPE_MEMBER);
             $User['RoleID'] = $DefaultRoles;
         } elseif (is_numeric($User['RoleID'])) {
             // UserModel->save() demands an array for RoleID.
             $User['RoleID'] = array($User['RoleID']);
         }
         if (!isset($User['Password'])) {
             $User['Password'] = md5(microtime());
             $User['HashMethod'] = 'Random';
         }
     }
     $UserID = Gdn::userModel()->save($User, array('SaveRoles' => isset($User['RoleID']), 'NoConfirmEmail' => true));
     if ($UserID) {
         if (!isset($User['UserID'])) {
             $User['UserID'] = $UserID;
         }
         if (isset($User['ClientID']) && isset($User['UniqueID'])) {
             Gdn::userModel()->saveAuthentication(array('UserID' => $User['UserID'], 'Provider' => $User['ClientID'], 'UniqueID' => $User['UniqueID']));
         }
         $this->setData('User', $User);
     } else {
         throw new Gdn_UserException(Gdn::userModel()->Validation->resultsText());
     }
     $this->render('Blank', 'Utility');
 }
コード例 #18
0
 /**
  * Connect the user with an external source.
  *
  * This controller method is meant to be used with plugins that set its data array to work.
  * Events: ConnectData
  * 
  * @since 2.0.0
  * @access public
  *
  * @param string $Method Used to register multiple providers on ConnectData event.
  */
 public function Connect($Method)
 {
     $this->AddJsFile('entry.js');
     $this->View = 'connect';
     $IsPostBack = $this->Form->IsPostBack() && $this->Form->GetFormValue('Connect', NULL) !== NULL;
     if (!$IsPostBack) {
         // Here are the initial data array values. that can be set by a plugin.
         $Data = array('Provider' => '', 'ProviderName' => '', 'UniqueID' => '', 'FullName' => '', 'Name' => '', 'Email' => '', 'Photo' => '', 'Target' => $this->Target());
         $this->Form->SetData($Data);
         $this->Form->AddHidden('Target', $this->Request->Get('Target', '/'));
     }
     // The different providers can check to see if they are being used and modify the data array accordingly.
     $this->EventArguments = array($Method);
     // Fire ConnectData event & error handling.
     $CurrentData = $this->Form->FormValues();
     try {
         $this->FireEvent('ConnectData');
     } catch (Gdn_UserException $Ex) {
         $this->Form->AddError($Ex);
         return $this->Render('ConnectError');
     } catch (Exception $Ex) {
         if (Debug()) {
             $this->Form->AddError($Ex);
         } else {
             $this->Form->AddError('There was an error fetching the connection data.');
         }
         return $this->Render('ConnectError');
     }
     if (!UserModel::NoEmail()) {
         if (!$this->Form->GetFormValue('Email') || $this->Form->GetFormValue('EmailVisible')) {
             $this->Form->SetFormValue('EmailVisible', TRUE);
             $this->Form->AddHidden('EmailVisible', TRUE);
             if ($IsPostBack) {
                 $this->Form->SetFormValue('Email', GetValue('Email', $CurrentData));
             }
         }
     }
     $FormData = $this->Form->FormValues();
     // debug
     // Make sure the minimum required data has been provided to the connect.
     if (!$this->Form->GetFormValue('Provider')) {
         $this->Form->AddError('ValidateRequired', T('Provider'));
     }
     if (!$this->Form->GetFormValue('UniqueID')) {
         $this->Form->AddError('ValidateRequired', T('UniqueID'));
     }
     if (!$this->Data('Verified')) {
         // Whatever event handler catches this must Set the data 'Verified' to true to prevent a random site from connecting without credentials.
         // This must be done EVERY postback and is VERY important.
         $this->Form->AddError('The connection data has not been verified.');
     }
     if ($this->Form->ErrorCount() > 0) {
         return $this->Render();
     }
     $UserModel = Gdn::UserModel();
     // Check to see if there is an existing user associated with the information above.
     $Auth = $UserModel->GetAuthentication($this->Form->GetFormValue('UniqueID'), $this->Form->GetFormValue('Provider'));
     $UserID = GetValue('UserID', $Auth);
     // Check to synchronise roles upon connecting.
     if (($this->Data('Trusted') || C('Garden.SSO.SynchRoles')) && $this->Form->GetFormValue('Roles', NULL) !== NULL) {
         $SaveRoles = TRUE;
         // Translate the role names to IDs.
         $Roles = $this->Form->GetFormValue('Roles', NULL);
         $Roles = RoleModel::GetByName($Roles);
         $RoleIDs = array_keys($Roles);
         if (empty($RoleIDs)) {
             // The user must have at least one role. This protects that.
             $RoleIDs = $this->UserModel->NewUserRoleIDs();
         }
         $this->Form->SetFormValue('RoleID', $RoleIDs);
     } else {
         $SaveRoles = FALSE;
     }
     if ($UserID) {
         // The user is already connected.
         $this->Form->SetFormValue('UserID', $UserID);
         if (C('Garden.Registration.ConnectSynchronize', TRUE)) {
             $User = Gdn::UserModel()->GetID($UserID, DATASET_TYPE_ARRAY);
             $Data = $this->Form->FormValues();
             // Don't overwrite the user photo if the user uploaded a new one.
             $Photo = GetValue('Photo', $User);
             if (!GetValue('Photo', $Data) || $Photo && !StringBeginsWith($Photo, 'http')) {
                 unset($Data['Photo']);
             }
             // Synchronize the user's data.
             $UserModel->Save($Data, array('NoConfirmEmail' => TRUE, 'FixUnique' => TRUE, 'SaveRoles' => $SaveRoles));
         }
         // Always save the attributes because they may contain authorization information.
         if ($Attributes = $this->Form->GetFormValue('Attributes')) {
             $UserModel->SaveAttribute($UserID, $Attributes);
         }
         // Sign the user in.
         Gdn::Session()->Start($UserID, TRUE, TRUE);
         Gdn::UserModel()->FireEvent('AfterSignIn');
         //         $this->_SetRedirect(TRUE);
         $this->_SetRedirect($this->Request->Get('display') == 'popup');
     } elseif ($this->Form->GetFormValue('Name') || $this->Form->GetFormValue('Email')) {
         $NameUnique = C('Garden.Registration.NameUnique', TRUE);
         $EmailUnique = C('Garden.Registration.EmailUnique', TRUE);
         $AutoConnect = C('Garden.Registration.AutoConnect');
         // Get the existing users that match the name or email of the connection.
         $Search = FALSE;
         if ($this->Form->GetFormValue('Name') && $NameUnique) {
             $UserModel->SQL->OrWhere('Name', $this->Form->GetFormValue('Name'));
             $Search = TRUE;
         }
         if ($this->Form->GetFormValue('Email') && ($EmailUnique || $AutoConnect)) {
             $UserModel->SQL->OrWhere('Email', $this->Form->GetFormValue('Email'));
             $Search = TRUE;
         }
         if ($Search) {
             $ExistingUsers = $UserModel->GetWhere()->ResultArray();
         } else {
             $ExistingUsers = array();
         }
         // Check to automatically link the user.
         if ($AutoConnect && count($ExistingUsers) > 0) {
             foreach ($ExistingUsers as $Row) {
                 if ($this->Form->GetFormValue('Email') == $Row['Email']) {
                     $UserID = $Row['UserID'];
                     $this->Form->SetFormValue('UserID', $UserID);
                     $Data = $this->Form->FormValues();
                     if (C('Garden.Registration.ConnectSynchronize', TRUE)) {
                         // Don't overwrite a photo if the user has already uploaded one.
                         $Photo = GetValue('Photo', $Row);
                         if (!GetValue('Photo', $Data) || $Photo && !StringBeginsWith($Photo, 'http')) {
                             unset($Data['Photo']);
                         }
                         $UserModel->Save($Data, array('NoConfirmEmail' => TRUE, 'FixUnique' => TRUE, 'SaveRoles' => $SaveRoles));
                     }
                     if ($Attributes = $this->Form->GetFormValue('Attributes')) {
                         $UserModel->SaveAttribute($UserID, $Attributes);
                     }
                     // Save the userauthentication link.
                     $UserModel->SaveAuthentication(array('UserID' => $UserID, 'Provider' => $this->Form->GetFormValue('Provider'), 'UniqueID' => $this->Form->GetFormValue('UniqueID')));
                     // Sign the user in.
                     Gdn::Session()->Start($UserID, TRUE, TRUE);
                     Gdn::UserModel()->FireEvent('AfterSignIn');
                     //         $this->_SetRedirect(TRUE);
                     $this->_SetRedirect($this->Request->Get('display') == 'popup');
                     $this->Render();
                     return;
                 }
             }
         }
         $CurrentUserID = Gdn::Session()->UserID;
         // Massage the existing users.
         foreach ($ExistingUsers as $Index => $UserRow) {
             if ($EmailUnique && $UserRow['Email'] == $this->Form->GetFormValue('Email')) {
                 $EmailFound = $UserRow;
                 break;
             }
             if ($UserRow['Name'] == $this->Form->GetFormValue('Name')) {
                 $NameFound = $UserRow;
             }
             if ($CurrentUserID > 0 && $UserRow['UserID'] == $CurrentUserID) {
                 unset($ExistingUsers[$Index]);
                 $CurrentUserFound = TRUE;
             }
         }
         if (isset($EmailFound)) {
             // The email address was found and can be the only user option.
             $ExistingUsers = array($UserRow);
             $this->SetData('NoConnectName', TRUE);
         } elseif (isset($CurrentUserFound)) {
             $ExistingUsers = array_merge(array('UserID' => 'current', 'Name' => sprintf(T('%s (Current)'), Gdn::Session()->User->Name)), $ExistingUsers);
         }
         if (!isset($NameFound) && !$IsPostBack) {
             $this->Form->SetFormValue('ConnectName', $this->Form->GetFormValue('Name'));
         }
         $this->SetData('ExistingUsers', $ExistingUsers);
         if (UserModel::NoEmail()) {
             $EmailValid = TRUE;
         } else {
             $EmailValid = ValidateRequired($this->Form->GetFormValue('Email'));
         }
         if ($this->Form->GetFormValue('Name') && $EmailValid && (!is_array($ExistingUsers) || count($ExistingUsers) == 0)) {
             // There is no existing user with the suggested name so we can just create the user.
             $User = $this->Form->FormValues();
             $User['Password'] = RandomString(50);
             // some password is required
             $User['HashMethod'] = 'Random';
             $User['Source'] = $this->Form->GetFormValue('Provider');
             $User['SourceID'] = $this->Form->GetFormValue('UniqueID');
             $User['Attributes'] = $this->Form->GetFormValue('Attributes', NULL);
             $User['Email'] = $this->Form->GetFormValue('ConnectEmail', $this->Form->GetFormValue('Email', NULL));
             //            $UserID = $UserModel->InsertForBasic($User, FALSE, array('ValidateEmail' => FALSE, 'NoConfirmEmail' => TRUE, 'SaveRoles' => $SaveRoles));
             $UserID = $UserModel->Register($User, array('CheckCaptcha' => FALSE, 'ValidateEmail' => FALSE, 'NoConfirmEmail' => TRUE, 'SaveRoles' => $SaveRoles));
             $User['UserID'] = $UserID;
             $this->Form->SetValidationResults($UserModel->ValidationResults());
             if ($UserID) {
                 $UserModel->SaveAuthentication(array('UserID' => $UserID, 'Provider' => $this->Form->GetFormValue('Provider'), 'UniqueID' => $this->Form->GetFormValue('UniqueID')));
                 $this->Form->SetFormValue('UserID', $UserID);
                 Gdn::Session()->Start($UserID, TRUE, TRUE);
                 Gdn::UserModel()->FireEvent('AfterSignIn');
                 // Send the welcome email.
                 if (C('Garden.Registration.SendConnectEmail', FALSE)) {
                     try {
                         $UserModel->SendWelcomeEmail($UserID, '', 'Connect', array('ProviderName' => $this->Form->GetFormValue('ProviderName', $this->Form->GetFormValue('Provider', 'Unknown'))));
                     } catch (Exception $Ex) {
                         // Do nothing if emailing doesn't work.
                     }
                 }
                 $this->_SetRedirect(TRUE);
             }
         }
     }
     // Save the user's choice.
     if ($IsPostBack) {
         // The user has made their decision.
         $PasswordHash = new Gdn_PasswordHash();
         $UserSelect = $this->Form->GetFormValue('UserSelect');
         if (!$UserSelect || $UserSelect == 'other') {
             // The user entered a username.
             $ConnectNameEntered = TRUE;
             if ($this->Form->ValidateRule('ConnectName', 'ValidateRequired')) {
                 $ConnectName = $this->Form->GetFormValue('ConnectName');
                 $User = FALSE;
                 if (C('Garden.Registration.NameUnique')) {
                     // Check to see if there is already a user with the given name.
                     $User = $UserModel->GetWhere(array('Name' => $ConnectName))->FirstRow(DATASET_TYPE_ARRAY);
                 }
                 if (!$User) {
                     $this->Form->ValidateRule('ConnectName', 'ValidateUsername');
                 }
             }
         } else {
             // The user selected an existing user.
             $ConnectNameEntered = FALSE;
             if ($UserSelect == 'current') {
                 if (Gdn::Session()->UserID == 0) {
                     // This shouldn't happen, but a use could sign out in another browser and click submit on this form.
                     $this->Form->AddError('@You were uexpectidly signed out.');
                 } else {
                     $UserSelect = Gdn::Session()->UserID;
                 }
             }
             $User = $UserModel->GetID($UserSelect, DATASET_TYPE_ARRAY);
         }
         if (isset($User) && $User) {
             // Make sure the user authenticates.
             if (!$User['UserID'] == Gdn::Session()->UserID) {
                 if ($this->Form->ValidateRule('ConnectPassword', 'ValidateRequired', sprintf(T('ValidateRequired'), T('Password')))) {
                     try {
                         if (!$PasswordHash->CheckPassword($this->Form->GetFormValue('ConnectPassword'), $User['Password'], $User['HashMethod'], $this->Form->GetFormValue('ConnectName'))) {
                             if ($ConnectNameEntered) {
                                 $this->Form->AddError('The username you entered has already been taken.');
                             } else {
                                 $this->Form->AddError('The password you entered is incorrect.');
                             }
                         }
                     } catch (Gdn_UserException $Ex) {
                         $this->Form->AddError($Ex);
                     }
                 }
             }
         } elseif ($this->Form->ErrorCount() == 0) {
             // The user doesn't exist so we need to add another user.
             $User = $this->Form->FormValues();
             $User['Name'] = $User['ConnectName'];
             $User['Password'] = RandomString(50);
             // some password is required
             $User['HashMethod'] = 'Random';
             $UserID = $UserModel->Register($User, array('CheckCaptcha' => FALSE, 'NoConfirmEmail' => TRUE, 'SaveRoles' => $SaveRoles));
             $User['UserID'] = $UserID;
             $this->Form->SetValidationResults($UserModel->ValidationResults());
             if ($UserID) {
                 //               // Add the user to the default roles.
                 //               $UserModel->SaveRoles($UserID, C('Garden.Registration.DefaultRoles'));
                 // Send the welcome email.
                 $UserModel->SendWelcomeEmail($UserID, '', 'Connect', array('ProviderName' => $this->Form->GetFormValue('ProviderName', $this->Form->GetFormValue('Provider', 'Unknown'))));
             }
         }
         if ($this->Form->ErrorCount() == 0) {
             // Save the authentication.
             if (isset($User) && GetValue('UserID', $User)) {
                 $UserModel->SaveAuthentication(array('UserID' => $User['UserID'], 'Provider' => $this->Form->GetFormValue('Provider'), 'UniqueID' => $this->Form->GetFormValue('UniqueID')));
                 $this->Form->SetFormValue('UserID', $User['UserID']);
             }
             // Sign the appropriate user in.
             Gdn::Session()->Start($this->Form->GetFormValue('UserID', TRUE, TRUE));
             Gdn::UserModel()->FireEvent('AfterSignIn');
             $this->_SetRedirect(TRUE);
         }
     }
     $this->Render();
 }
コード例 #19
0
ファイル: class.usermodel.php プロジェクト: vanilla/vanilla
 /**
  *
  *
  * @param array $Roles
  * @return array
  */
 protected function lookupRoleIDs($Roles)
 {
     if (is_string($Roles)) {
         $Roles = explode(',', $Roles);
     } elseif (!is_array($Roles)) {
         $Roles = [];
     }
     $Roles = array_map('trim', $Roles);
     $Roles = array_map('strtolower', $Roles);
     $AllRoles = RoleModel::roles();
     $RoleIDs = [];
     foreach ($AllRoles as $RoleID => $Role) {
         $Name = strtolower($Role['Name']);
         if (in_array($Name, $Roles) || in_array($RoleID, $Roles)) {
             $RoleIDs[] = $RoleID;
         }
     }
     return $RoleIDs;
 }
コード例 #20
0
ファイル: me.php プロジェクト: robhazkes/Garden
$User = $Session->User;
$CssClass = '';
if ($this->CssClass) {
    $CssClass .= ' ' . $this->CssClass;
}
$DashboardCount = 0;
// Spam & Moderation Queue
if ($Session->CheckPermission('Garden.Settings.Manage') || $Session->CheckPermission('Garden.Moderation.Manage')) {
    $LogModel = new LogModel();
    $SpamCount = $LogModel->GetOperationCount('spam');
    $ModerationCount = $LogModel->GetOperationCount('moderate');
    $DashboardCount += $SpamCount + $ModerationCount;
}
// Applicant Count
if ($Session->CheckPermission('Garden.Applicants.Manage')) {
    $RoleModel = new RoleModel();
    $ApplicantCount = $RoleModel->GetApplicantCount();
    $DashboardCount += $ApplicantCount;
}
if ($Session->IsValid()) {
    echo '<div class="MeBox' . $CssClass . '">';
    echo UserPhoto($User);
    echo '<div class="WhoIs">';
    echo UserAnchor($User, 'Username');
    echo '<div class="MeMenu">';
    // Notifications
    $CountNotifications = $User->CountNotifications;
    $CNotifications = is_numeric($CountNotifications) && $CountNotifications > 0 ? '<span class="Alert">' . $CountNotifications . '</span>' : '';
    echo '<span class="ToggleFlyout" rel="/profile/notificationspopin">';
    echo Anchor(Sprite('SpNotifications', 'Sprite Sprite16') . Wrap(T('Notifications'), 'em') . $CNotifications, UserUrl($User), 'MeButton FlyoutButton', array('title' => T('Notifications')));
    echo Sprite('SpFlyoutHandle', 'Arrow');
コード例 #21
0
 public function EditCategory($CategoryID = '')
 {
     $this->Permission('Vanilla.Categories.Manage');
     $RoleModel = new RoleModel();
     $PermissionModel = Gdn::PermissionModel();
     $this->Form->SetModel($this->CategoryModel);
     $this->Category = $this->CategoryModel->GetID($CategoryID);
     $this->AddJsFile('/js/library/jquery.gardencheckboxgrid.js');
     $this->Title(T('Edit Category'));
     $this->AddSideMenu('vanilla/settings/managecategories');
     // Make sure the form knows which item we are editing.
     $this->Form->AddHidden('CategoryID', $CategoryID);
     // Load all roles with editable permissions
     $this->RoleArray = $RoleModel->GetArray();
     if ($this->Form->AuthenticatedPostBack() === FALSE) {
         $this->Form->SetData($this->Category);
     } else {
         if ($this->Form->Save()) {
             // Report success
             $this->StatusMessage = T('The category was saved successfully.');
             $this->RedirectUrl = Url('vanilla/settings/managecategories');
         }
     }
     // Get all of the currently selected role/permission combinations for this junction
     $Permissions = $PermissionModel->GetJunctionPermissions(array('JunctionID' => $CategoryID), 'Category');
     $Permissions = $PermissionModel->UnpivotPermissions($Permissions, TRUE);
     $this->SetData('PermissionData', $Permissions, TRUE);
     $this->Render();
 }
コード例 #22
0
 public function GetResourceAccess($params = null)
 {
     //        $ROLE_ID    =   isset($params[self::ROLE_ID]) ? $params[self::ROLE_ID] : null;
     //        $ROLE_NAME  =   isset($params[A_ACL_RoleModel::ROLE_NAME]) ? $params[A_ACL_RoleModel::ROLE_NAME] : null;
     if (isset(self::$_resource_access_map)) {
         return self::$_resource_access_map;
     }
     $ROLE_TO_BASES = array();
     $szSQL = self::SELECT_FROM(array(RolesRelationModel::tblFldsAll(), RoleModel::ROLE_NAME, self::tblFld(self::MODULE), self::tblFld(self::CONTROLLER), self::tblFld(self::ACTION), self::tblFld(self::ACCESS_PERMISSION)), array(RolesRelationModel::tbl(), RoleModel::tbl(), self::tbl()), array(array(RolesRelationModel::tblFld(RolesRelationModel::ROLE_ID), RoleModel::tblFld(RoleModel::ROLE_ID)), array(RoleModel::tblFld(RoleModel::ROLE_ID), self::tblFld(self::ROLE_ID))), null, null);
     $cDB =& $this->GetDBAdapter();
     $rs = $cDB->Execute($szSQL);
     self::$_resource_access_map = array();
     while ($this->isValid($rs)) {
         self::$_resource_access_map[self::ROLES][$rs->fields[RolesRelationModel::ROLE_ID]] = $rs->fields[RoleModel::ROLE_NAME];
         self::$_resource_access_map[self::RULES][$rs->fields[RolesRelationModel::ROLE_ID]][$rs->fields[self::MODULE]][$rs->fields[self::CONTROLLER]][$rs->fields[self::ACTION]] = (int) $rs->fields[self::ACCESS_PERMISSION];
         $this->_map($ROLE_TO_BASES, $rs->fields);
         $rs->MoveNext();
     }
     self::$_resource_access_map[self::MAP] = $ROLE_TO_BASES;
     echo __METHOD__ . " #" . __LINE__ . " Resource Access map:<br><pre>";
     var_dump(self::$_resource_access_map);
     echo "</pre><br>";
     return self::$_resource_access_map;
 }
コード例 #23
0
 /**
  * Configuration of registration settings.
  *
  * Events: BeforeRegistrationUpdate
  *
  * @since 2.0.0
  * @access public
  * @param string $RedirectUrl Where to send user after registration.
  */
 public function registration($RedirectUrl = '')
 {
     $this->permission('Garden.Settings.Manage');
     $this->addSideMenu('dashboard/settings/registration');
     $this->addJsFile('registration.js');
     $this->title(t('Registration'));
     // Create a model to save configuration settings
     $Validation = new Gdn_Validation();
     $ConfigurationModel = new Gdn_ConfigurationModel($Validation);
     $registrationOptions = array('Garden.Registration.Method' => 'Captcha', 'Garden.Registration.InviteExpiration', 'Garden.Registration.ConfirmEmail');
     if ($manageCaptcha = c('Garden.Registration.ManageCaptcha', true)) {
         $registrationOptions[] = 'Garden.Registration.CaptchaPrivateKey';
         $registrationOptions[] = 'Garden.Registration.CaptchaPublicKey';
     }
     $this->setData('_ManageCaptcha', $manageCaptcha);
     $ConfigurationModel->setField($registrationOptions);
     // Set the model on the forms.
     $this->Form->setModel($ConfigurationModel);
     // Load roles with sign-in permission
     $RoleModel = new RoleModel();
     $this->RoleData = $RoleModel->getByPermission('Garden.SignIn.Allow');
     $this->setData('_Roles', array_column($this->RoleData->resultArray(), 'Name', 'RoleID'));
     // Get currently selected InvitationOptions
     $this->ExistingRoleInvitations = Gdn::config('Garden.Registration.InviteRoles');
     if (is_array($this->ExistingRoleInvitations) === false) {
         $this->ExistingRoleInvitations = array();
     }
     // Get the currently selected Expiration Length
     $this->InviteExpiration = Gdn::config('Garden.Registration.InviteExpiration', '');
     // Registration methods.
     $this->RegistrationMethods = array('Captcha' => "New users fill out a simple form and are granted access immediately.", 'Approval' => "New users are reviewed and approved by an administrator (that's you!).", 'Invitation' => "Existing members send invitations to new members.", 'Connect' => "New users are only registered through SSO plugins.");
     // Options for how many invitations a role can send out per month.
     $this->InvitationOptions = array('0' => t('None'), '1' => '1', '2' => '2', '5' => '5', '-1' => t('Unlimited'));
     // Options for when invitations should expire.
     $this->InviteExpirationOptions = array('1 week' => t('1 week after being sent'), '2 weeks' => t('2 weeks after being sent'), '1 month' => t('1 month after being sent'), 'FALSE' => t('never'));
     if ($this->Form->authenticatedPostBack() === false) {
         $this->Form->setData($ConfigurationModel->Data);
     } else {
         // Define some validation rules for the fields being saved
         $ConfigurationModel->Validation->applyRule('Garden.Registration.Method', 'Required');
         // Define the Garden.Registration.RoleInvitations setting based on the postback values
         $InvitationRoleIDs = $this->Form->getValue('InvitationRoleID');
         $InvitationCounts = $this->Form->getValue('InvitationCount');
         $this->ExistingRoleInvitations = arrayCombine($InvitationRoleIDs, $InvitationCounts);
         $ConfigurationModel->forceSetting('Garden.Registration.InviteRoles', $this->ExistingRoleInvitations);
         // Event hook
         $this->EventArguments['ConfigurationModel'] =& $ConfigurationModel;
         $this->fireEvent('BeforeRegistrationUpdate');
         // Save!
         if ($this->Form->save() !== false) {
             $this->informMessage(t("Your settings have been saved."));
             if ($RedirectUrl != '') {
                 $this->RedirectUrl = $RedirectUrl;
             }
         }
     }
     $this->render();
 }
コード例 #24
0
 /**
  * Edit user account.
  *
  * @since 2.0.0
  * @access public
  * @param mixed $UserReference Username or User ID.
  */
 public function Edit($UserReference = '', $Username = '', $UserID = '')
 {
     $this->Permission('Garden.SignIn.Allow');
     $this->GetUserInfo($UserReference, $Username, $UserID, TRUE);
     $UserID = GetValueR('User.UserID', $this);
     $Settings = array();
     // Set up form
     $User = Gdn::UserModel()->GetID($UserID, DATASET_TYPE_ARRAY);
     $this->Form->SetModel(Gdn::UserModel());
     $this->Form->SetData($User);
     $this->SetData('User', $User);
     // Decide if they have ability to edit the username
     $CanEditUsername = (bool) C("Garden.Profile.EditUsernames") || Gdn::Session()->CheckPermission('Garden.Users.Edit');
     $this->SetData('_CanEditUsername', $CanEditUsername);
     // Decide if they have ability to edit the email
     $EmailEnabled = (bool) C('Garden.Profile.EditEmails', TRUE) && !UserModel::NoEmail();
     $CanEditEmail = $EmailEnabled && $UserID == Gdn::Session()->UserID || CheckPermission('Garden.Users.Edit');
     $this->SetData('_CanEditEmail', $CanEditEmail);
     // Decide if they have ability to confirm users
     $Confirmed = (bool) GetValueR('User.Confirmed', $this);
     $CanConfirmEmail = UserModel::RequireConfirmEmail() && CheckPermission('Garden.Users.Edit');
     $this->SetData('_CanConfirmEmail', $CanConfirmEmail);
     $this->SetData('_EmailConfirmed', $Confirmed);
     $this->Form->SetValue('ConfirmEmail', (int) $Confirmed);
     // Decide if we can *see* email
     $this->SetData('_CanViewPersonalInfo', Gdn::Session()->UserID == GetValue('UserID', $User) || CheckPermission('Garden.PersonalInfo.View') || CheckPermission('Garden.Users.Edit'));
     // Define gender dropdown options
     $this->GenderOptions = array('u' => T('Unspecified'), 'm' => T('Male'), 'f' => T('Female'));
     $this->FireEvent('BeforeEdit');
     // If seeing the form for the first time...
     if ($this->Form->IsPostBack()) {
         $this->Form->SetFormValue('UserID', $UserID);
         if (!$CanEditUsername) {
             $this->Form->SetFormValue("Name", $User['Name']);
         } else {
             $UsernameError = T('UsernameError', 'Username can only contain letters, numbers, underscores, and must be between 3 and 20 characters long.');
             Gdn::UserModel()->Validation->ApplyRule('Name', 'Username', $UsernameError);
         }
         // API
         // These options become available when POSTing as a user with Garden.Settings.Manage permissions
         if (Gdn::Session()->CheckPermission('Garden.Settings.Manage')) {
             // Role change
             $RequestedRoles = $this->Form->GetFormValue('RoleID', NULL);
             if (!is_null($RequestedRoles)) {
                 $RoleModel = new RoleModel();
                 $AllRoles = $RoleModel->GetArray();
                 if (!is_array($RequestedRoles)) {
                     $RequestedRoles = is_numeric($RequestedRoles) ? array($RequestedRoles) : array();
                 }
                 $RequestedRoles = array_flip($RequestedRoles);
                 $UserNewRoles = array_intersect_key($AllRoles, $RequestedRoles);
                 // Put the data back into the forum object as if the user had submitted
                 // this themselves
                 $this->Form->SetFormValue('RoleID', array_keys($UserNewRoles));
                 // Allow saving roles
                 $Settings['SaveRoles'] = TRUE;
             }
             // Password change
             $NewPassword = $this->Form->GetFormValue('Password', NULL);
             if (!is_null($NewPassword)) {
             }
         }
         // Allow mods to confirm emails
         $this->Form->RemoveFormValue('Confirmed');
         $Confirmation = $this->Form->GetFormValue('ConfirmEmail', null);
         $Confirmation = !is_null($Confirmation) ? (bool) $Confirmation : null;
         if ($CanConfirmEmail && is_bool($Confirmation)) {
             $this->Form->SetFormValue('Confirmed', (int) $Confirmation);
         }
         if ($this->Form->Save($Settings) !== FALSE) {
             $User = Gdn::UserModel()->GetID($UserID, DATASET_TYPE_ARRAY);
             $this->SetData('Profile', $User);
             $this->InformMessage(Sprite('Check', 'InformSprite') . T('Your changes have been saved.'), 'Dismissable AutoDismiss HasSprite');
         }
         if (!$CanEditEmail) {
             $this->Form->SetFormValue("Email", $User['Email']);
         }
     }
     $this->Title(T('Edit Profile'));
     $this->_SetBreadcrumbs(T('Edit Profile'), '/profile/edit');
     $this->Render();
 }
コード例 #25
0
 /**
  *
  */
 public function setRoleDefaults()
 {
     if (!$this->importExists('Role', 'RoleID')) {
         return;
     }
     $Data = $this->SQL->get('zRole')->resultArray();
     $RoleDefaults = array('Garden.Registration.ConfirmEmail' => false);
     $RoleTypes = array();
     foreach ($Data as $Row) {
         if ($this->importExists('Role', '_Default')) {
             $Name = $Row['_Default'];
         } else {
             $Name = val('Name', $Row);
         }
         $RoleID = $Row['RoleID'];
         if (preg_match('`anonymous`', $Name)) {
             $Name = 'guest';
         } elseif (preg_match('`admin`', $Name)) {
             $Name = 'administrator';
         }
         switch (strtolower($Name)) {
             case 'email':
             case 'confirm email':
             case 'users awaiting email confirmation':
             case 'pending':
                 $RoleTypes[$RoleID] = RoleModel::TYPE_UNCONFIRMED;
                 $RoleDefaults['Garden.Registration.ConfirmEmail'] = true;
                 break;
             case 'member':
             case 'members':
             case 'registered':
             case 'registered users':
                 $RoleTypes[$RoleID] = RoleModel::TYPE_MEMBER;
                 break;
             case 'guest':
             case 'guests':
             case 'unauthenticated':
             case 'unregistered':
             case 'unregistered / not logged in':
                 $RoleTypes[$RoleID] = RoleModel::TYPE_GUEST;
                 break;
             case 'applicant':
             case 'applicants':
                 $RoleTypes[$RoleID] = RoleModel::TYPE_APPLICANT;
                 break;
         }
     }
     saveToConfig($RoleDefaults);
     $roleModel = new RoleModel();
     foreach ($RoleTypes as $RoleID => $Type) {
         $roleModel->setField($RoleID, 'Type', $Type);
     }
 }
コード例 #26
0
 /**
  * Editing a category.
  * 
  * @since 2.0.0
  * @access public
  *
  * @param int $CategoryID Unique ID of the category to be updated.
  */
 public function EditCategory($CategoryID = '')
 {
     // Check permission
     $this->Permission('Vanilla.Categories.Manage');
     // Set up models
     $RoleModel = new RoleModel();
     $PermissionModel = Gdn::PermissionModel();
     $this->Form->SetModel($this->CategoryModel);
     // Get category data
     $this->Category = $this->CategoryModel->GetID($CategoryID);
     $this->Category->CustomPermissions = $this->Category->CategoryID == $this->Category->PermissionCategoryID;
     // Set up head
     $this->AddJsFile('jquery.alphanumeric.js');
     $this->AddJsFile('categories.js');
     $this->AddJsFile('jquery.gardencheckboxgrid.js');
     $this->Title(T('Edit Category'));
     $this->AddSideMenu('vanilla/settings/managecategories');
     // Make sure the form knows which item we are editing.
     $this->Form->AddHidden('CategoryID', $CategoryID);
     // Load all roles with editable permissions
     $this->RoleArray = $RoleModel->GetArray();
     $this->FireEvent('AddEditCategory');
     if ($this->Form->AuthenticatedPostBack() === FALSE) {
         $this->Form->SetData($this->Category);
     } else {
         if ($this->Form->Save()) {
             Redirect('vanilla/settings/managecategories');
         }
     }
     // Get all of the currently selected role/permission combinations for this junction.
     $Permissions = $PermissionModel->GetJunctionPermissions(array('JunctionID' => $CategoryID), 'Category', '', array('AddDefaults' => !$this->Category->CustomPermissions));
     $Permissions = $PermissionModel->UnpivotPermissions($Permissions, TRUE);
     $this->SetData('PermissionData', $Permissions, TRUE);
     // Render default view
     $this->Render();
 }
コード例 #27
0
 public function PostController_Render_Before($Sender)
 {
     $Data = $Sender->Data('Comments');
     if (is_object($Data)) {
         RoleModel::SetUserRoles($Data->Result(), 'InsertUserID');
     }
 }
コード例 #28
0
ファイル: class.dbamodel.php プロジェクト: sitexa/vanilla
 /**
  * If any role has no permission records, set Member-like permissions on it.
  *
  * @return array
  */
 public function fixPermissions()
 {
     $Roles = RoleModel::roles();
     $RoleModel = new RoleModel();
     $PermissionModel = new PermissionModel();
     // Find roles missing permission records
     foreach ($Roles as $RoleID => $Role) {
         $Permissions = $this->SQL->select('*')->from('Permission p')->where('p.RoleID', $RoleID)->get()->resultArray();
         if (!count($Permissions)) {
             // Set basic permission record
             $DefaultRecord = array('RoleID' => $RoleID, 'JunctionTable' => null, 'JunctionColumn' => null, 'JunctionID' => null, 'Garden.Email.View' => 1, 'Garden.SignIn.Allow' => 1, 'Garden.Activity.View' => 1, 'Garden.Profiles.View' => 1, 'Garden.Profiles.Edit' => 1, 'Conversations.Conversations.Add' => 1);
             $PermissionModel->save($DefaultRecord);
             // Set default category permission
             $DefaultCategory = array('RoleID' => $RoleID, 'JunctionTable' => 'Category', 'JunctionColumn' => 'PermissionCategoryID', 'JunctionID' => -1, 'Vanilla.Discussions.View' => 1, 'Vanilla.Discussions.Add' => 1, 'Vanilla.Comments.Add' => 1);
             $PermissionModel->save($DefaultCategory);
         }
     }
     return array('Complete' => true);
 }
コード例 #29
0
ファイル: structure.php プロジェクト: mcnasby/datto-vanilla
if (!isset($Drop)) {
    $Drop = false;
}
if (!isset($Explicit)) {
    $Explicit = true;
}
$Database = Gdn::database();
$SQL = $Database->sql();
$Construct = $Database->structure();
$Px = $Database->DatabasePrefix;
// Role Table
$Construct->table('Role');
$RoleTableExists = $Construct->tableExists();
$RoleTypeExists = $Construct->columnExists('Type');
$Construct->primaryKey('RoleID')->column('Name', 'varchar(100)')->column('Description', 'varchar(500)', true)->column('Type', array(RoleModel::TYPE_GUEST, RoleModel::TYPE_UNCONFIRMED, RoleModel::TYPE_APPLICANT, RoleModel::TYPE_MEMBER, RoleModel::TYPE_MODERATOR, RoleModel::TYPE_ADMINISTRATOR), true)->column('Sort', 'int', true)->column('Deletable', 'tinyint(1)', '1')->column('CanSession', 'tinyint(1)', '1')->column('PersonalInfo', 'tinyint(1)', '0')->set($Explicit, $Drop);
$RoleModel = new RoleModel();
if (!$RoleTableExists || $Drop) {
    // Define default roles.
    $RoleModel->Database = $Database;
    $RoleModel->SQL = $SQL;
    $Sort = 1;
    $RoleModel->define(array('Name' => 'Guest', 'Type' => RoleModel::TYPE_GUEST, 'RoleID' => 2, 'Sort' => $Sort++, 'Deletable' => '0', 'CanSession' => '0', 'Description' => t('Guest Role Description', 'Guests can only view content. Anyone browsing the site who is not signed in is considered to be a "Guest".')));
    $RoleModel->define(array('Name' => 'Unconfirmed', 'Type' => RoleModel::TYPE_UNCONFIRMED, 'RoleID' => 3, 'Sort' => $Sort++, 'Deletable' => '0', 'CanSession' => '1', 'Description' => t('Unconfirmed Role Description', 'Users must confirm their emails before becoming full members. They get assigned to this role.')));
    $RoleModel->define(array('Name' => 'Applicant', 'Type' => RoleModel::TYPE_APPLICANT, 'RoleID' => 4, 'Sort' => $Sort++, 'Deletable' => '0', 'CanSession' => '1', 'Description' => t('Applicant Role Description', 'Users who have applied for membership, but have not yet been accepted. They have the same permissions as guests.')));
    $RoleModel->define(array('Name' => 'Member', 'Type' => RoleModel::TYPE_MEMBER, 'RoleID' => 8, 'Sort' => $Sort++, 'Deletable' => '1', 'CanSession' => '1', 'Description' => t('Member Role Description', 'Members can participate in discussions.')));
    $RoleModel->define(array('Name' => 'Moderator', 'Type' => RoleModel::TYPE_MODERATOR, 'RoleID' => 32, 'Sort' => $Sort++, 'Deletable' => '1', 'CanSession' => '1', 'Description' => t('Moderator Role Description', 'Moderators have permission to edit most content.')));
    $RoleModel->define(array('Name' => 'Administrator', 'Type' => RoleModel::TYPE_ADMINISTRATOR, 'RoleID' => 16, 'Sort' => $Sort++, 'Deletable' => '1', 'CanSession' => '1', 'Description' => t('Administrator Role Description', 'Administrators have permission to do anything.')));
}
// User Table
$Construct->table('User');
$PhotoIDExists = $Construct->columnExists('PhotoID');
コード例 #30
0
ファイル: RoleModel.php プロジェクト: humansky/qframe
 /**
  * Reload this object's data based on a given key
  *
  * @param integer primary key
  */
 public function _load($key)
 {
     if (!isset(self::$roleTable)) {
         self::$roleTable = QFrame_Db_Table::getTable('role');
     }
     $data = self::$roleTable->find($key)->current()->toArray();
     $this->setAttributes($data, false);
     $this->acl = unserialize($data['ACLstring']);
 }