Example #1
0
 static function isAllowed($resource, $module = "default", $username = null)
 {
     $users_roles_table = new UsersRoles();
     $user_roles = array();
     $roles_table = new Roles();
     if (!is_null($username)) {
         $users_roles_db = $users_roles_table->fetchAll($users_roles_table->select()->where("username = ?", $username));
         $user_roles = array();
         if (count($users_roles_db) > 0) {
             foreach ($users_roles_db as $role) {
                 $user_roles[] = $role->role_id;
             }
         }
     } else {
         $user_roles = array($roles_table->getIdByShortname("guest"));
     }
     $resource_name = $module . "-@@EXTRA-" . $resource;
     $out = false;
     if (Zend_Registry::isRegistered('acl')) {
         $acl = Zend_Registry::get('acl');
         if ($acl->has($resource_name)) {
             foreach ($user_roles as $role) {
                 if ($acl->isAllowed($role, $resource_name)) {
                     $out = true;
                 }
             }
         }
     }
     return $out;
 }
Example #2
0
 public function searchClients()
 {
     // @todo Please modify the following code to remove attributes that should not be searched.
     $criteria = new CDbCriteria();
     if ($this->keyword != null) {
         $criteria->addCondition('t.name LIKE "%' . $this->keyword . '%"', "OR");
         $criteria->addCondition('t.email_1 LIKE "%' . $this->keyword . '%"', "OR");
         $criteria->addCondition('t.phone_1 LIKE "%' . $this->keyword . '%"', "OR");
     }
     $this->responsable_id != null && $this->responsable_id != 'all' && $this->responsable_id != 'no' ? $criteria->addCondition('t.responsable_id=' . $this->responsable_id) : '';
     $this->responsable_id == 'no' ? $criteria->addCondition('t.responsable_id=null') : '';
     $this->priority_id != null && $this->priority_id != 0 ? $criteria->addCondition('t.priority_id=' . $this->priority_id) : '';
     $this->source_id != null && $this->source_id != 0 ? $criteria->addCondition('t.source_id=' . $this->source_id) : '';
     $this->goal_id != null && $this->goal_id != 0 ? $criteria->addCondition('t.goal_id=' . $this->goal_id) : '';
     $this->city_id != null && $this->city_id != 0 ? $criteria->addCondition('t.city_id=' . $this->city_id) : '';
     $this->group_id != null && $this->group_id != 0 ? $criteria->addCondition('t.group_id=' . $this->group_id) : '';
     $criteria->addCondition('t.company_id=' . Users::model()->findByPk(Yii::app()->user->id)->company_id);
     $role = UsersRoles::model()->find('user_id=' . Yii::app()->user->id)->itemname;
     if ($role == 'director') {
         $users = new Users();
         $users_ids = $users->takeDirectorUsers(Yii::app()->user->id);
         $criteria->addInCondition('t.responsable_id', $users_ids);
     } elseif ($role == 'manager') {
         $criteria->addCondition('t.responsable_id=' . Yii::app()->user->id);
     }
     return new CActiveDataProvider($this, array('criteria' => $criteria, 'sort' => array('defaultOrder' => 't.id DESC')));
 }
Example #3
0
 public function searchDeals($id = null)
 {
     // @todo Please modify the following code to remove attributes that should not be searched.
     $criteria = new CDbCriteria();
     $criteria->with = array('client');
     $this->keyword != null ? $criteria->addCondition('t.text LIKE "%' . $this->keyword . '%"') : '';
     $id != null ? $criteria->addCondition('t.client_id=' . $id) : '';
     $criteria->addCondition('t.company_id=' . Users::model()->findByPk(Yii::app()->user->id)->company_id);
     $this->client_group_id != null && $this->client_group_id != 0 ? $criteria->addCondition('client.group_id=' . $this->client_group_id) : '';
     $this->responsable_id != null && $this->responsable_id != 'all' && $this->responsable_id != 'no' ? $criteria->addCondition('t.responsable_id=' . $this->responsable_id) : '';
     $this->responsable_id == 'no' ? $criteria->addCondition('t.responsable_id is null') : '';
     $this->deal_category_id != null && $this->deal_category_id != 0 ? $criteria->addCondition('t.deal_category_id=' . $this->deal_category_id) : '';
     $this->text != null ? $criteria->addCondition('t.text LIKE "%' . $this->text . '%"') : '';
     $this->deal_status_id != null && $this->deal_status_id != 0 ? $criteria->addCondition('t.deal_status_id=' . $this->deal_status_id) : '';
     $this->deal_priority_id != null && $this->deal_priority_id != 0 ? $criteria->addCondition('t.deal_priority_id=' . $this->deal_priority_id) : '';
     $this->paid != null && $this->paid != 0 ? $criteria->addCondition('t.paid>=' . $this->paid) : '';
     $this->balance != null && $this->balance != 0 ? $criteria->addCondition('t.balance>=' . $this->balance) : '';
     // поиск только по нулевым значениям
     $this->paid === "0" ? $criteria->addCondition('t.paid=0') : '';
     $this->balance === "0" ? $criteria->addCondition('t.balance=0') : '';
     // поиск в интервале дат
     $this->start_date != null ? $criteria->addCondition('UNIX_TIMESTAMP(t.creation_date)>=' . strtotime($this->start_date)) : '';
     $this->stop_date != null ? $criteria->addCondition('UNIX_TIMESTAMP(t.creation_date)<=' . strtotime($this->stop_date . ':59')) : '';
     // поиск по ролям
     $role = UsersRoles::model()->find('user_id=' . Yii::app()->user->id)->itemname;
     if ($role == 'director') {
         $users = new Users();
         $users_ids = $users->takeDirectorUsers(Yii::app()->user->id);
         $criteria->addInCondition('t.responsable_id', $users_ids);
     } elseif ($role == 'manager') {
         $criteria->addCondition('t.responsable_id=' . Yii::app()->user->id);
     }
     return new CActiveDataProvider($this, array('criteria' => $criteria, 'sort' => array('defaultOrder' => 't.id DESC')));
 }
Example #4
0
	static function isAllowed($resource,$module = "default",$username = null,$controller = null){
		$users_roles_table = new UsersRoles();
		$roles_table = new Roles();
		if(!is_null($username)){
			$users_roles_db = $users_roles_table->fetchAll($users_roles_table->select()->where("username = ?",$username));
			
			if(count($users_roles_db) > 0){
				$user_roles = array();
				$users_roles_db = $users_roles_db->toArray();
				
				foreach($users_roles_db as $role){
					$ancs = $roles_table->getAllAncestors($role['role_id']);
					
					foreach ($ancs as $anc => $value) {
						$user_roles[] = $value;
					}
					
					array_push($user_roles, $role['role_id']);
				}
				$user_roles = array_unique($user_roles);
			}
		} else {
			$user_roles = array($roles_table->getIdByShortname("guest"));			
		}
		if (is_null($controller)) {
			$controller = "@@EXTRA";
		} 
		$resource_name = $module ."-". $controller ."-". $resource;
		$out = array();
		
		
		if(Zend_Registry::isRegistered('acl')){
			$acl = Zend_Registry::get('acl');
			if($acl->has($resource_name)){
				
				foreach($user_roles as $role){
					if($acl->isAllowed($role, $resource_name)){
						$out[] = $role;
					}
				}
				
			}
		}	
		return $out;	
	}
Example #5
0
 public function searchActions($id = null)
 {
     // @todo Please modify the following code to remove attributes that should not be searched.
     $criteria = new CDbCriteria();
     $criteria->with = array('client');
     $id != null ? $criteria->addCondition('t.client_id=' . $id) : '';
     $this->client_group_id != null && $this->client_group_id != 0 ? $criteria->addCondition('client.group_id=' . $this->client_group_id) : '';
     $this->responsable_id != null && $this->responsable_id != 'all' && $this->responsable_id != 'no' ? $criteria->addCondition('t.responsable_id=' . $this->responsable_id) : '';
     $this->responsable_id == 'no' ? $criteria->addCondition('t.responsable_id is null') : '';
     $this->action_type_id != null && $this->action_type_id != 0 ? $criteria->addCondition('t.action_type_id=' . $this->action_type_id) : '';
     $this->action_status_id != null && $this->action_status_id != 0 ? $criteria->addCondition('t.action_status_id=' . $this->action_status_id) : '';
     $this->action_priority_id != null && $this->action_priority_id != 0 ? $criteria->addCondition('t.action_priority_id=' . $this->action_priority_id) : '';
     $this->text != null ? $criteria->addCondition('t.text LIKE "%' . $this->text . '%"') : '';
     $criteria->addCondition('t.company_id=' . Users::model()->findByPk(Yii::app()->user->id)->company_id);
     //хуйнуть поиск по интервалу дат
     if ($this->term) {
         $date_to_sql_req = strtotime(date('d.m.Y'));
         switch ($this->term) {
             case 4:
                 $criteria->addCondition("t.action_status_id=1 AND " . $date_to_sql_req . ">UNIX_TIMESTAMP(t.action_date) AND DATE_FORMAT(CURRENT_TIMESTAMP(), '%d.%m.%Y')!=DATE_FORMAT(t.action_date,'%d.%m.%Y')");
                 break;
             case 1:
                 $criteria->addCondition("DATE_FORMAT(CURRENT_TIMESTAMP(), '%d.%m.%Y')=DATE_FORMAT(t.action_date,'%d.%m.%Y')");
                 break;
             case 2:
                 $criteria->addCondition("t.action_status_id!=2 AND " . $date_to_sql_req . "<=UNIX_TIMESTAMP(t.action_date) AND DATE_FORMAT(CURRENT_TIMESTAMP(), '%d.%m.%Y')!=DATE_FORMAT(t.action_date,'%d.%m.%Y')");
                 break;
             case 3:
                 $criteria->addCondition("t.action_status_id=2 OR t.action_status_id=3");
                 break;
         }
     }
     // поиск в интервале дат
     $this->start_date != null ? $criteria->addCondition('UNIX_TIMESTAMP(t.action_date)>=' . strtotime($this->start_date)) : '';
     $this->stop_date != null ? $criteria->addCondition('UNIX_TIMESTAMP(t.action_date)<=' . strtotime($this->stop_date . ':59')) : '';
     // поиск по ролям
     $role = UsersRoles::model()->find('user_id=' . Yii::app()->user->id)->itemname;
     if ($role == 'director') {
         $users = new Users();
         $users_ids = $users->takeDirectorUsers(Yii::app()->user->id);
         $criteria->addInCondition('t.responsable_id', $users_ids);
     } elseif ($role == 'manager') {
         $criteria->addCondition('t.responsable_id=' . Yii::app()->user->id);
     }
     return new CActiveDataProvider($this, array('criteria' => $criteria, 'sort' => array('defaultOrder' => 't.id DESC')));
 }
Example #6
0
                                    border-bottom: 1px solid #d9d9d9;
                                    padding: 8px 11px;
                                    text-align:left;
                                    font-size: 11px;
                                    color: #222;
                                    line-height: 12px;'), 'value' => function ($data) {
    return CHtml::submitButton($data->first_name, array("class" => "button_to_link", 'onClick' => 'ActionEdit(' . $data->id . ',"user")'));
}), array('name' => 'parent_id', 'header' => 'Тип пользователя', 'headerHtmlOptions' => array('class' => 'w8', 'style' => '   height: 12px;
                                    border-right: 1px solid #d9d9d9;
                                    border-bottom: 1px solid #d9d9d9;
                                    padding: 8px 11px;
                                    text-align:left;
                                    font-size: 11px;
                                    color: #222;
                                    line-height: 12px;'), 'value' => function ($data) {
    return UsersRoles::model()->find('user_id=' . $data->id)->itemname;
}), array('name' => 'email', 'header' => 'Email', 'headerHtmlOptions' => array('class' => 'w7', 'style' => '   height: 12px;
                                    border-right: 1px solid #d9d9d9;
                                    border-bottom: 1px solid #d9d9d9;
                                    padding: 8px 11px;
                                    text-align:left;
                                    font-size: 11px;
                                    color: #222;
                                    line-height: 12px;')), array('name' => 'phone', 'header' => 'Телефон', 'headerHtmlOptions' => array('class' => 'w7', 'style' => '   height: 12px;
                                    border-right: 1px solid #d9d9d9;
                                    border-bottom: 1px solid #d9d9d9;
                                    padding: 8px 11px;
                                    text-align:left;
                                    font-size: 11px;
                                    color: #222;
                                    line-height: 12px;')), array('name' => 'status', 'header' => 'Статус', 'headerHtmlOptions' => array('class' => 'w8', 'style' => '   height: 12px;
Example #7
0
 function assignUserToRole($aData)
 {
     /*find the system uid for this role */
     require_once 'classes/model/Users.php';
     $c = new Criteria();
     $c->add(RolesPeer::ROL_UID, $aData['ROL_UID']);
     $result = RolesPeer::doSelectRS($c);
     $result->setFetchmode(ResultSet::FETCHMODE_ASSOC);
     $result->next();
     $row = $result->getRow();
     $sSystemId = $row['ROL_SYSTEM'];
     //updating the role into users table
     $oCriteria1 = new Criteria('workflow');
     $oCriteria1->add(UsersPeer::USR_UID, $aData['USR_UID'], Criteria::EQUAL);
     $oCriteria2 = new Criteria('workflow');
     $oCriteria2->add(UsersPeer::USR_ROLE, $row['ROL_CODE']);
     BasePeer::doUpdate($oCriteria1, $oCriteria2, Propel::getConnection('workflow'));
     //delete roles for the same System
     $c = new Criteria();
     $c->addSelectColumn(UsersRolesPeer::USR_UID);
     $c->addSelectColumn(RolesPeer::ROL_UID);
     $c->addSelectColumn(RolesPeer::ROL_CODE);
     $c->addSelectColumn(RolesPeer::ROL_SYSTEM);
     $c->add(UsersRolesPeer::USR_UID, $aData['USR_UID']);
     $c->add(RolesPeer::ROL_SYSTEM, $sSystemId);
     $c->addJoin(RolesPeer::ROL_UID, UsersRolesPeer::ROL_UID);
     $result = RolesPeer::doSelectRS($c);
     $result->setFetchmode(ResultSet::FETCHMODE_ASSOC);
     $result->next();
     while ($row = $result->getRow()) {
         $crit = new Criteria();
         $crit->add(UsersRolesPeer::USR_UID, $row['USR_UID']);
         $crit->add(UsersRolesPeer::ROL_UID, $row['ROL_UID']);
         UsersRolesPeer::doDelete($crit);
         $result->next();
     }
     //save the unique role for this system
     $oUsersRoles = new UsersRoles();
     $oUsersRoles->setUsrUid($aData['USR_UID']);
     $oUsersRoles->setRolUid($aData['ROL_UID']);
     $oUsersRoles->save();
     $rol = $this->load($aData['ROL_UID']);
     $oUsersRbac = new RbacUsers();
     $user = $oUsersRbac->load($aData['USR_UID']);
     G::auditLog("AssignUserToRole", "Assign user " . $user['USR_USERNAME'] . " (" . $aData['USR_UID'] . ") to Role " . $rol['ROL_NAME'] . " (" . $aData['ROL_UID'] . ") ");
 }
                                    border-bottom: 1px solid #d9d9d9;
                                    padding: 8px 11px;
                                    text-align:left;
                                    font-size: 11px;
                                    color: #222;
                                    line-height: 12px;'), 'value' => function ($data) {
    return '<span class="square ' . $data->dealPriority->color . '">square</span>' . CHtml::submitButton($data->text, array("class" => "button_to_link", 'onClick' => 'ActionEdit(' . $data->id . ',"deal", "dealings_page")'));
}), array('name' => 'client_id', 'header' => 'Клиент', 'headerHtmlOptions' => array('class' => 'w56_5', 'style' => '   height: 12px;
                                    border-right: 1px solid #d9d9d9;
                                    border-bottom: 1px solid #d9d9d9;
                                    padding: 8px 11px;
                                    text-align:left;
                                    font-size: 11px;
                                    color: #222;
                                    line-height: 12px;'), 'type' => 'raw', 'value' => function ($data) {
    $role = UsersRoles::model()->find('user_id=' . Yii::app()->user->id)->itemname;
    $client_info = Clients::model()->findByPk($data->client_id);
    $responsible = Users::model()->findByPk($client_info->responsable_id);
    if ($client_info->responsable_id == Yii::app()->user->id || $responsible->parent_id == Yii::app()->user->id || $role == 'admin') {
        return CHtml::link($data->client->name, Yii::app()->createUrl("page/client_profile", array("id" => $data->client->id)));
    } else {
        return $data->client->name;
    }
}), array('name' => 'paid', 'header' => 'Уплачено / Остаток', 'headerHtmlOptions' => array('class' => 'w57_5', 'style' => '   height: 12px;
                                    border-right: 1px solid #d9d9d9;
                                    border-bottom: 1px solid #d9d9d9;
                                    padding: 8px 11px;
                                    text-align:left;
                                    font-size: 11px;
                                    color: #222;
                                    line-height: 12px;'), 'type' => 'raw', 'value' => function ($data) {
Example #9
0
 function testdataAction()
 {
     $request = new Bolts_Request($this->getRequest());
     if ($this->getRequest()->isPost()) {
         $errors = array();
         $data_path = $request->data_path;
         $data_file = $data_path . "/users.dat";
         $image_dir = $data_path . "/images";
         $users_table = new Users();
         $users_roles_table = new UsersRoles();
         if ($request->has("email_domain")) {
             $email_domain = $request->email_domain;
         } else {
             $email_domain = "nowhere.com";
         }
         if (!file_exists($data_file)) {
             $errors[] = $this->_T("Data file missing. Check path.");
         } else {
             $users = unserialize(file_get_contents($data_file));
             if (!is_array($users)) {
                 $errors[] = $this->_T("Data file is corrupt or something.");
             }
         }
         if (count($errors) == 0) {
             $old_users = $users_table->fetchAll();
             foreach ($old_users as $old_user) {
                 if ($users_table->getMetaData($old_user->username, "is_test_user") == "true") {
                     $where = $users_table->getAdapter()->quoteInto("username = ?", $old_user->username);
                     $users_table->delete($where);
                     $users_roles_table->delete($where);
                 }
             }
             $count = 0;
             foreach ($users as $user) {
                 $tmp_user = array();
                 foreach ($user as $key => $value) {
                     if ($key != "avatar") {
                         $tmp_user[$key] = $value;
                     }
                 }
                 $tmp_user['email'] = strtolower($tmp_user['username'] . "@" . $email_domain);
                 $tmp_user['password'] = "******";
                 $destination_path = $users_table->getAvatarPath($user['username']);
                 $destination_filename = $users_table->getAvatarPath($user['username'], true);
                 if (!is_dir($destination_path)) {
                     mkdir($destination_path, 0777, true);
                 }
                 if (file_exists($destination_filename)) {
                     unlink($destination_filename);
                 }
                 $source_image = $image_dir . "/" . $user['avatar'];
                 copy($source_image, $destination_filename);
                 $role_data = array("username" => $tmp_user['username'], "role_id" => $tmp_user['role_id']);
                 $users_roles_table->insert($role_data);
                 unset($tmp_user['role_id']);
                 $users_table->insert($tmp_user);
                 $users_table->setMetaData($tmp_user['username'], "is_test_user", "true");
                 $save_users[] = $user;
                 $count++;
             }
             $this->view->success = "User data loaded. Created " . $count . " users.";
             Bolts_Registry::set('test_data_path', $request->data_path);
             $this->view->data_path = Bolts_Registry::get('test_data_path');
             $this->view->email_domain = $email_domain;
         } else {
             $this->view->errors = $errors;
             $this->view->data_path = Zend_Registry::get('basepath') . "/tmp/testdata";
             $this->view->email_domain = $request->email_domain;
         }
     } else {
         $this->view->data_path = Zend_Registry::get('basepath') . "/tmp/testdata";
         $this->view->email_domain = "nowhere.com";
         $this->view->notice = $this->_T("Warning: If you are reinstalling the test data, the old test data will be overwritten. Users created outside the test data should not be affected.");
     }
 }
    $managers_array = Users::model()->with('roles')->findAll('company_id=' . $user->company_id . ' and status="active" and roles.name="manager" and parent_id=' . Yii::app()->user->id);
} elseif ($role == 'manager') {
    unset($responsible_options['director'], $responsible_options['manager']);
} else {
    unset($responsible_options['no']);
}
$directors_array = Users::model()->with('roles')->findAll('company_id=' . $user->company_id . ' and status="active" and roles.name="director"');
$managers_array = Users::model()->with('roles')->findAll('company_id=' . $user->company_id . ' and status="active" and roles.name="manager"');
if (count($directors_array) <= 0) {
    unset($responsible_options['director']);
}
if (count($managers_array) <= 0) {
    unset($responsible_options['manager']);
}
// выбор значения в селекторе
$client_resp_role = UsersRoles::model()->find('user_id=' . $client->responsable_id);
if ($client->responsable_id == Yii::app()->user->id) {
    $selected_option = array('i' => array('selected' => true));
} elseif ($client_resp_role->itemname == 'director') {
    $selected_option = array('director' => array('selected' => true));
} elseif ($client_resp_role->itemname == 'manager') {
    $selected_option = array('manager' => array('selected' => true));
} else {
    $selected_option = array('no' => array('selected' => true));
}
$directors_block_to_display = $client_resp_role->itemname == 'director' ? 'style="display:block"' : '';
$managers_block_to_display = $client_resp_role->itemname == 'manager' ? 'style="display:block"' : '';
?>
                <?php 
echo $form->dropDownList($client, 'responsable_id', $responsible_options, array('options' => $selected_option, 'class' => 'styled permis editable typeAccess', 'name' => 'type'));
?>
Example #11
0
	function registerAction()
	{
		$errors = array();
		$request = new RivetyCore_Request($this->getRequest());

		if ($this->_auth->hasIdentity()) $this->_redirect('/default/user/profile/username/' . $this->_identity->username);
		$users_table = new Users();
		$user = array();

		$pre_register_params = array();

		if ($request->has('url'))
		{
			$this->view->url_param = $request->url;
			$pre_register_params['return_url'] = $request->url;
		}
		else
		{
			$pre_register_params['return_url'] = false;
		}

		$pre_register_params = $this->_rivety_plugin->doFilter('default_pre_register', $pre_register_params); // FILTER HOOK
		foreach ($pre_register_params as $key=>$value)
		{
			if ($key == 'return_url') $this->view->url_param = $value;
			else $this->view->$key = $value;
		}

		if ($this->getRequest()->isPost())
		{
			$request->addValidator('username', 'Username is required.');
			$request->addValidator('email', 'Email address is required.');
			$request->addValidator('password', 'Password is required.');
			$request->addValidator('confirm', 'Password confirmation is required.');
			if (!$request->isValid()) $errors = array_merge($errors, $request->getValidationErrors());
			if (count($errors) == 0)
			{
				$user['username'] = $request->username;
				// if ($request->has('full_name'))
				// {
				// 	if (strlen($request->full_name) < 1) $user['full_name'] = $this->_T("Anonymous");
				// 	else $user['full_name'] = $request->full_name;
				// }
				// else
				// {
				// 	$user['full_name'] = $this->_T("Anonymous");
				// }
				$user['email'] = $request->email;
				$user['password'] = $request->password;
				$user['confirm'] = $request->confirm;

				// TODO: remove anything relating to birthday

				// if ($request->has('Birthday_Day') && $request->has('Birthday_Month') && $request->has('Birthday_Year'))
				// {
				// 	$user['birthday'] = strtotime($request->Birthday_Day ." ". $request->Birthday_Month ." ". $request->Birthday_Year);
				// }
				// else
				// {
				// 	$user['birthday'] = null;
				// }

				// validate username
				$username_validator = new Zend_Validate();
				$username_validator->addValidator(new Zend_Validate_StringLength(1, RivetyCore_Registry::get('username_length')));
				$username_validator->addValidator(new Zend_Validate_Alnum());

				if (!$username_validator->isValid($user['username']))
				{
					$show_username = "******".$user['username']."'";
					if (trim($user['username']) == "") $show_username = "******".$this->_T("empty")."]";
					$errors[] = $this->_T("%s is not a valid username. (Between %d and %d characters, only letters and numbers)",array($show_username,1,RivetyCore_Registry::get('username_length')));
					$this->screenAlert('error', $this->_T("%s is not a valid username. (Between %d and %d characters, only letters and numbers)",array($show_username,1,RivetyCore_Registry::get('username_length'))));
				}

				$user_where = $users_table->getAdapter()->quoteInto('username = ?', $user['username']);
				if ($users_table->getCountByWhereClause($user_where) > 0)
				{
					$errors[] = $this->_T("The username '%s' is already in use",$user['username']);
					$this->screenAlert('error', $this->_T("The username '%s' is already in use",$user['username']));
				}

				// validate email
				$email_validator = new Zend_Validate_EmailAddress();
				if (!$email_validator->isValid($user['email']))
				{
					$show_email = "'" . $user['email']."'";
					if (trim($user['email']) == "") $show_email = "[" . $this->_T("empty") . "]";
					$errors[] = $show_email . ' ' . $this->_T('is not a valid email.');
					$this->screenAlert('error', $show_email . ' ' . $this->_T('is not a valid email.'));
				}

				// make sure no one is using this email already
				$email_where = $users_table->getAdapter()->quoteInto('email = ?',$user['email']);
				if ($users_table->getCountByWhereClause($email_where) > 0)
				{
					$errors[] = $this->_T("Email is already in use.");
					$this->screenAlert('error', 'This email address is already in use.');
				}

				$password_validator = new Zend_Validate();
				$password_validator->addValidator(new Zend_Validate_StringLength(6, 32));
				// make sure password is at least six chars
				if (!$password_validator->isValid($user['password']))
				{
					$errors[] = $this->_T("Password must be between %d and %d characters", array(6, RivetyCore_Registry::get('password_length')));
					$this->screenAlert('error', $this->_T("Password must be between %d and %d characters", array(6, RivetyCore_Registry::get('password_length'))));
				}
				// if password is set, make sure it matches confirm
				if ($user['password'] != $user['confirm'])
				{
					$errors[] = $this->_T("Passwords don't match");
					$this->screenAlert('error', $this->_T("Passwords don't match"));
				}

				// // do we meet the minimum age?
				// $minimum_age = RivetyCore_Registry::get('minimum_registration_age', '13') ;
				// $years_ago = strtotime($minimum_age . ' years ago');
				// if ($user['birthday'] > $years_ago)
				// {
				// 	$errors[] = $this->_T("You must be at least %d years old to register.", $minimum_age);
				// }

				$params = array(
					'request' => $this->getRequest(),
					'user' => $user,
					'errors' => $errors,
				);
				$additional = $this->_rivety_plugin->doFilter($this->_mca, $params); // FILTER HOOK
				$errors = $additional['errors'];
				$user = $additional['user'];

				// convert birthday_ts to mysql date
				// $birthday_db = date(DB_DATETIME_FORMAT, $user['birthday']);
				if (count($errors) == 0)
				{
					$roles_table = new Roles();
					$users_roles_table = new UsersRoles();
					$default_role_shortname = RivetyCore_Registry::get('default_role_shortname');
					$role_data = array("username" => $user['username'], "role_id" => $roles_table->getIdByShortname($default_role_shortname));
					$users_roles_table->insert($role_data);

					$user_data = array(
						'username' => $user['username'],
						'email' => $user['email'],
						// 'full_name' => $user['full_name'],
						// 'birthday' => $birthday_db,
						'password' => $user['password'],
						'created_on' => date("Y-m-d H:i:s"),
						'ip' => getenv('REMOTE_ADDR'),
					);

					// if (array_key_exists('about_me', $additional['user']))
					// {
					// 	$user_data['about_me'] = $additional['user']['about_me'];
					// }

					// MAKE IT OFFICIAL
					$users_table->insert($user_data);

					// DO SOME PLUGINS
					$params = array(
						'user' => $user_data,
						'request' => $request,
						'username' => $user['username'],
						'autologin' => true,
						'autologin_username' => $user['username'],
						'autologin_password' => $user['password'],
						'autologin_password_hash' => md5($user['password']),
						'locale_code' => $this->locale_code,
					);
					$params = $this->_rivety_plugin->doFilter("default_post_register", $params); // FILTER HOOK
					$this->_rivety_plugin->doAction($this->_mca . "_post_register", $params); // ACTION HOOK (deprecated)

					// SET UP AUTO-LOGIN, OR DON'T
					if ($params['autologin'])
					{
						$appNamespace = new Zend_Session_Namespace('RivetyCore_Temp');
						$appNamespace->autoLogin = $params['autologin'];
						$appNamespace->autoLoginUsername = $params['autologin_username'];
						$appNamespace->autoLoginPassword = $params['autologin_password'];
						$appNamespace->autoLoginPasswordHash = $params['autologin_password_hash'];
					}

					// SEND THE USER ON THEIR WAY
					$url = '/default/user/postregister';
					// if there was a URL passed in then add that encoded URL as a param to the default redirect
					if ($request->has('url')) $url .= '/url/' . $request->url;
					$this->_redirect($url);
				}
			}
		}
		$this->view->user = $user;
		$this->view->pagetitle = $this->_T("Register");

		foreach ($errors as $error)
		{
			$this->screenAlert('error', $error);
		}
		$errors = null;

		switch ($this->format)
		{
			case 'json': die(!empty($this->screen_alerts) ? json_encode(array('messages' => $this->screen_alerts)) : '200 OK');
			default: break;
		}
	}
Example #12
0
 public function getAdminId()
 {
     $company_users = Users::model()->findAll('company_id=' . Users::model()->findByPk(Yii::app()->user->id)->company_id);
     foreach ($company_users as $user) {
         $admin = UsersRoles::model()->find('user_id=' . $user->id);
         if ($admin->itemname == 'admin') {
             return $admin->user_id;
         }
     }
 }
Example #13
0
	function fetchRolesByUsername($username){
		$users_roles_table = new UsersRoles();
		$roles_for_user = $users_roles_table->fetchAll($users_roles_table->select()->where("username = ?",$username));
		$select = $this->select();
		if(count($roles_for_user) > 0){
			foreach($roles_for_user as $role_for_user){
				$select->orWhere("id = ?",$role_for_user->role_id); 	
			}			 
		}
		
		return $this->fetchAll($select);
		
	}
    public function actionEdit_user($id)
    {
        $user = Users::model()->findByPk($id);
        $edit_user_role = UsersRoles::model()->find('user_id=' . $user->id);
        $role = UsersRoles::model()->find('user_id=' . Yii::app()->user->id)->itemname;
        if ($_POST['MainUsers']) {
            if (isset($_POST['ajax']) && $_POST['ajax'] == 'edit-user') {
                echo CActiveForm::validate($user);
                Yii::app()->end();
            }
            $edit_user_role->itemname = $_POST['MainUsers']['role'] == 'edit_director' ? 'director' : 'manager';
            $edit_user_role->update();
            $user->attributes = $_POST['MainUsers'];
            if ($user->update()) {
                $this->redirect(array('user_info'));
            }
        }
        // работа с ролями
        $role_array = array('edit_director' => 'Руководитель', 'edit_manager' => 'Менеджер');
        $directors_array = array(Yii::app()->user->id => 'Я руководитель');
        if ($role == 'admin') {
            $directors = Users::model()->with('roles')->findAll('company_id=' . $user->company_id . ' and status="active" and roles.name="director"');
            if (count($directors) > 0) {
                foreach ($directors as $director) {
                    if ($user->id != $director->id) {
                        $directors_array[$director->id] = $director->first_name;
                    }
                }
            }
        } elseif ($role == 'director') {
            unset($role_array['edit_director']);
        }
        $form = $this->beginWidget('CActiveForm', array('id' => 'edit-user', 'enableAjaxValidation' => true, 'clientOptions' => array('validateOnSubmit' => true)));
        $delete_button = CHtml::button("Удалить", array('onClick' => 'window.location.href="' . Yii::app()->createUrl("page/delete_user", array("id" => $id)) . '"', 'class' => 'btn'));
        $change_password = CHtml::button("Изменить пароль", array('onClick' => 'window.location.href="' . Yii::app()->createUrl("page/edit_user_password", array("id" => $id)) . '"', 'class' => 'btn white1'));
        $directors_block_to_display = $edit_user_role->itemname == 'director' ? 'style="display:block"' : '';
        $managers_block_to_display = $edit_user_role->itemname == 'manager' ? 'style="display:block"' : '';
        $admin = new Users();
        $admin_id = $admin->getAdminId();
        $new_responsible = $user->parent_id != null ? $user->parent_id : $admin_id;
        echo '<div class="popup" id="popup-edit-user" style="display: block;">
	<div class="popup__head">
		<div class="title">Редактирование пользователя</div>
	</div>
	<div class="popup__form">
			<div class="form-group">
				<div class="help-dropdown">
					<dl>
						<dt class="dt2"><i class="icon-help">help</i>Показать справку</dt>
						<dd class="dd2">
							<ul>
								<li>
									<strong>Редактирование пользователя</strong> - изменение текущего пользователя. Здесь вы можете изменить контакты пользователя и его пароль (генерируется новый, отправится на указанный email). Также, Создатель компании может изменить тип пользователя или удалить его.
									<br>В случае удаления пользователя руководителем, менеджеры, закрепленные за данным пользователем, будут закреплены за Создателем компании.
								</li>
							</ul>
						</dd>
					</dl>
				</div>
			</div>
			<div class="client_info">
				Информация о пользователе:
			</div>
			<div class="form-group">
				' . $form->textField($user, 'first_name', array('class' => 'form-control', 'placeholder' => 'Имя')) . $form->error($user, 'first_name', array('class' => 'form-error')) . '
				<span class="star">*</span>
			</div>
			<div class="form-group">
				' . $form->textField($user, 'email', array('class' => 'form-control', 'placeholder' => 'E-mail')) . $form->error($user, 'email', array('class' => 'form-error')) . '
				<span class="star">*</span>
			</div>
			<div class="form-group">
				' . $form->textField($user, 'phone', array('class' => 'form-control', 'placeholder' => 'Телефон')) . $form->error($user, 'phone', array('class' => 'form-error')) . '
			</div>
			<div class="form-group">
			<div class="client_info">
				Тип пользователя:
			</div>
			<div class="form-group">
				' . $form->dropDownList($user, 'role', $role_array, array('options' => $edit_user_role->itemname == 'director' ? array('edit_director' => array('selected' => true)) : array('edit_manager' => array('selected' => true)), 'class' => 'styled editable typeAccess')) . '
			</div>
			<div class="access-options access-tab" id="edit_director" ' . $directors_block_to_display . '>
				<div class="access-rights_note left">
					Руководитель:<br>
					- может создавать новых клиентов, действия и сделки.<br>
					- может создавать новых менеджеров.<br>
					- видит своих клиентов, а также, клиентов своих менеджеров.<br>
					- может назначить менеджера ответственным за клиента, действием или сделкой.<br>
					- изменяет свою контактную информацию и своих менеджеров.<br>
					- не доступны настройки.<br>
					- создатель компании видит всю информацию по клиентам руководителя и его менеджеров.
				</div>
			</div>
			<div class="access-options access-tab" id="edit_manager" ' . $managers_block_to_display . '>
			    <div class="form-group">
				<div class="client_info">
					Руководитель:
				</div>
				<div class="form-group">
					' . $form->dropDownList($user, 'parent_id', $directors_array, array('class' => 'styled editable')) . '
				</div>
				<div class="access-rights_note left">
					Менеджер:<br>
					- может создавать новых клиентов, действия и сделки.<br>
					- видит только своих клиентов.<br>
					- видит действия и сделки, если он ответственный по ним.<br>
					- не доступны настройки и изменение пароля.<br>
					- руководитель менеджера видит всю информацию по нему.<br>
				</div>
			</div>
			</div>
			<div class="form-group">
				' . CHtml::submitButton('Редактировать пользователя', array('class' => 'btn')) . '
			</div>
			<div class="form-group">
				' . $change_password . '
			</div>
			<div class="function-delete">
				<a class="delete" href="#">Удалить пользователя</a>
			</div>
			<div class="function-delete-confirm">
				<ul class="horizontal">
					<li class="big">При удалении пользователя все его клиенты, действия и сделки будут закреплены за ' . Users::model()->findByPk($new_responsible)->first_name . '</li>
					<li><a class="delete" href="#">Отмена</a></li>
					<li>' . $delete_button . '</li>
				</ul>
			</div>
	</div>
</div>' . $this->actionGetJSStyle('edit-user', '[{
        "id": "MainUsers_first_name",
        "inputID": "MainUsers_first_name",
        "errorID": "MainUsers_first_name_em_",
        "model": "MainUsers",
        "name": "first_name",
        "enableAjaxValidation": true
    }, {
        "id": "MainUsers_email",
        "inputID": "MainUsers_email",
        "errorID": "MainUsers_email_em_",
        "model": "MainUsers",
        "name": "email",
        "enableAjaxValidation": true
    }, {
        "id": "MainUsers_phone",
        "inputID": "MainUsers_phone",
        "errorID": "MainUsers_phone_em_",
        "model": "MainUsers",
        "name": "phone",
        "enableAjaxValidation": true
    }]');
        $this->endWidget();
    }
Example #15
0
	public function preDispatch(Zend_Controller_Request_Abstract $request)
	{
		$frontController = Zend_Controller_Front :: getInstance();
		$auth = Zend_Auth :: getInstance();
		$roles_table = new Roles();

		$appNamespace = new Zend_Session_Namespace('RivetyCore_Temp');

		if (Zend_Registry :: isRegistered('acl'))
		{
			$acl = Zend_Registry :: get('acl');
		}
		else
		{
			$acl = new RivetyCore_Acl($auth);
			Zend_Registry::set('acl', $acl);
		}

		// determine role
		if ($auth->hasIdentity())
		{
			$user = Zend_Auth :: getInstance()->getIdentity();
			$users_roles_table = new UsersRoles();
			$users_roles_db = $users_roles_table->fetchAll($users_roles_table->select()->where("username = ?", $user->username));
			$user_roles = array();
			if (count($users_roles_db) > 0)
			{
				foreach ($users_roles_db as $role)
				{
					$user_roles[] = $role->role_id;
					$user_roles = array_merge($user_roles, $roles_table->getAllAncestors($role->role_id));
				}
			}
			$user_roles = array_unique($user_roles);
			$user_is_guest = false;
            $defaultNamespace = new Zend_Session_Namespace('Zend_Auth');

			// REFRESH THE SESSION EXPIRATION
	        $defaultNamespace->setExpirationSeconds((int)RivetyCore_Registry::get('session_timeout'));
		}
		else
		{
			$user_roles = array($roles_table->getIdByShortname("guest"));
			$user_is_guest = true;
		}

		$requested = $request->getModuleName() . "-" . ucfirst(strtolower($request->getControllerName())) . "-" . $request->getActionName();
		$url = $frontController->getBaseUrl() . "/";

		if (!$acl->has($requested))
		{
			// this doesn't exist, throw to 404
			$request->setModuleName('default');
			$request->setControllerName('auth');
			$request->setActionName('missing');
		}
		else
		{
			$isAllowed = array();
			foreach ($user_roles as $user_role)
			{
				$isAllowed[$user_role] = $acl->isAllowed($user_role, $requested);

				// if ($acl->isAllowed($user_role, $requested))
				// {
				// 	$isAllowed[$user_role] = true;
				// }
				// else
				// {
				// 	$isAllowed[$user_role] = false;
				// }
			}
			if (!in_array(true, $isAllowed))
			{
				if ($user_is_guest)
				{
					$url .= $request->getModuleName() . "/";
					$url .= $request->getControllerName() . "/";
					$url .= $request->getActionName() . "/";

					$params = $request->getParams();

					while ($param = current($params))
					{
				    	if (key($params) != "module" && key($params) != "controller" && key($params) != "action") $url .= key($params) . '/' . $param . "/";
	    				next($params);
					}
					if (substr($url,strlen($url) - 1, 1) == "/")
					{
						$url = substr($url, 0, strlen($url) - 1);
					}

					// place requested url in the session, unless this is the login controller

					if ($request->getControllerName() != "auth")
					{
						$request->setParam('ourl', base64_encode($url));
						// $appNamespace->requestedUrl = $url;
					}

					$blockedActions = RivetyCore_Registry::get('disable_login_redirect');
					if (!empty($blockedActions)) $blockedActions = explode(',', $blockedActions);
					$mca = $request->getModuleName() . "_" . $request->getControllerName() . "_" . $request->getActionName();
					if (is_array($blockedActions) && in_array($mca, $blockedActions))
					{
						// forward to the 401 Unauthorized page
						$request->setModuleName('default');
						$request->setControllerName('auth');
						$request->setActionName('unauthorized');
					}
					else
					{
						// forward to the login script
						$request->setModuleName('default');
						$request->setControllerName('auth');
						$request->setActionName('login');
					}
				}
				else
				{
					$admin = "default-Admin-index";
					$isAdmin = array();
					foreach($user_roles as $user_role)
					{
						$isAdmin[$user_role] = $acl->isAllowed($user_role, $admin);

						// if ($acl->isAllowed($user_role, $admin))
						// {
						// 	$isAdmin[$user_role] = true;
						// }
						// else
						// {
						// 	$isAdmin[$user_role] = false;
						// }
					}
					if (!in_array(true, $isAdmin))
					{
						$request->setModuleName('default');
						$request->setControllerName('auth');
						$request->setActionName('denied');
					}
					else
					{
						$request->setModuleName('default');
						$request->setControllerName('admin');
						$request->setActionName('index');
					}
				}
			}
		}
	}
Example #16
0
 public function preDispatch(Zend_Controller_Request_Abstract $request)
 {
     $frontController = Zend_Controller_Front::getInstance();
     $auth = Zend_Auth::getInstance();
     $roles_table = new Roles();
     $appNamespace = new Zend_Session_Namespace('Bolts_Temp');
     if (Zend_Registry::isRegistered('acl')) {
         $acl = Zend_Registry::get('acl');
     } else {
         $acl = new Bolts_Acl($auth);
         Zend_Registry::set('acl', $acl);
     }
     // determine role
     if ($auth->hasIdentity()) {
         $user = Zend_Auth::getInstance()->getIdentity();
         $users_roles_table = new UsersRoles();
         $users_roles_db = $users_roles_table->fetchAll($users_roles_table->select()->where("username = ?", $user->username));
         $user_roles = array();
         if (count($users_roles_db) > 0) {
             foreach ($users_roles_db as $role) {
                 $user_roles[] = $role->role_id;
                 $user_roles = array_merge($user_roles, $roles_table->getAllAncestors($role->role_id));
             }
         }
         $user_roles = array_unique($user_roles);
         $user_is_guest = false;
         $defaultNamespace = new Zend_Session_Namespace('Zend_Auth');
         $defaultNamespace->setExpirationSeconds(86400);
     } else {
         $user_roles = array($roles_table->getIdByShortname("guest"));
         $user_is_guest = true;
     }
     $requested = $request->getModuleName() . "-" . ucfirst(strtolower($request->getControllerName())) . "-" . $request->getActionName();
     $url = $frontController->getBaseUrl() . "/";
     if (!$acl->has($requested)) {
         // this doesn't exist, throw to 404
         $request->setModuleName('bolts');
         $request->setControllerName('auth');
         $request->setActionName('missing');
     } else {
         $isAllowed = array();
         foreach ($user_roles as $user_role) {
             if ($acl->isAllowed($user_role, $requested)) {
                 $isAllowed[$user_role] = true;
             } else {
                 $isAllowed[$user_role] = false;
             }
         }
         if (!in_array(true, $isAllowed)) {
             if ($user_is_guest) {
                 $url .= $request->getModuleName() . "/";
                 $url .= $request->getControllerName() . "/";
                 $url .= $request->getActionName() . "/";
                 $params = $request->getParams();
                 while ($param = current($params)) {
                     if (key($params) != "module" and key($params) != "controller" and key($params) != "action") {
                         $url .= key($params) . '/' . $param . "/";
                     }
                     next($params);
                 }
                 if (substr($url, strlen($url) - 1, 1) == "/") {
                     $url = substr($url, 0, strlen($url) - 1);
                 }
                 //Zend_debug::dump($params);
                 //Zend_debug::dump($url);
                 // place requested url in the sesson,
                 // unless this is the login controller
                 if ($request->getControllerName() != "auth") {
                     $request->setParam('url', base64_encode($url));
                     //$appNamespace->requestedUrl = $url;
                 }
                 // send on to the login scipt
                 $request->setModuleName('bolts');
                 $request->setControllerName('auth');
                 $request->setActionName('login');
             } else {
                 $admin = "bolts-Admin-index";
                 $isAdmin = array();
                 foreach ($user_roles as $user_role) {
                     if ($acl->isAllowed($user_role, $admin)) {
                         $isAdmin[$user_role] = true;
                     } else {
                         $isAdmin[$user_role] = false;
                     }
                 }
                 if (!in_array(true, $isAdmin)) {
                     $request->setModuleName('bolts');
                     $request->setControllerName('auth');
                     $request->setActionName('denied');
                 } else {
                     $request->setModuleName('bolts');
                     $request->setControllerName('admin');
                     $request->setActionName('index');
                 }
             }
         }
     }
 }
Example #17
0
 function deleteAction()
 {
     $request = new Bolts_Request($this->getRequest());
     $roles_table = new Roles();
     if ($request->has('id')) {
         $id = $request->id;
         $role = $roles_table->fetchRow("id = " . $id);
         if (is_null($role)) {
             $this->_redirect('/bolts/role');
         }
     } else {
         $this->_redirect('/bolts/role');
     }
     if ($this->getRequest()->isPost() and $request->has("delete")) {
         $errors = array();
         // can't be last admin
         if ((bool) $role->isadmin and $roles_table->getCountByWhereClause("isadmin = 1") == 1) {
             $errors[] = $this->_T("This is the only admin role. It cannot be deleted.");
         }
         // can't be guest
         if ((bool) $role->isguest) {
             $errors[] = $this->_T("This is the guest role. It cannot be deleted.");
         }
         // can't be default
         if ((bool) $role->isdefault) {
             $errors[] = $this->_T("This is the default role. It cannot be deleted.");
         }
         // can't have any users
         $userwhereclause = "role_id = " . $role->id;
         $users_table = new UsersRoles();
         if ($users_table->getCountByWhereClause($userwhereclause) > 0) {
             $errors[] = $this->_T("This role cannot be deleted because there are users assigned to it.");
         }
         // can't have children
         $inherited_by = $roles_table->fetchImmediateChildren($role->id);
         if (count($inherited_by) > 0) {
             $error = $this->_T("This role is inherited by role(s) ");
             $firstpass = true;
             foreach ($inherited_by as $role_i) {
                 if ($firstpass) {
                     $firstpass = false;
                 } else {
                     $error .= ", ";
                 }
                 $error .= $role_i->shortname;
             }
             $error .= $this->_T(". It cannot be deleted.");
             $errors[] = $error;
         }
         if ($request->delete == "Yes") {
             if (count($errors) > 0) {
                 $this->view->errors = $errors;
             } else {
                 $roles_table->delete("id = " . $id);
                 $this->view->success = $this->_T("Role deleted.");
             }
         } else {
             $this->_redirect("/bolts/role");
         }
     }
     $this->view->role = $role->toArray();
 }
Example #18
0
 function create($sUserUID = '', $sRolUID = '')
 {
     $oRole = new UsersRoles();
     $oRole->setUsrUid($sUserUID);
     $oRole->setRolUid($sRolUID);
     $oRole->save();
 }