Not authorized to perform this action when admin login - yii

in file Controller:
class Controller extends CController
{
public function filters()
{
return array('accessControl');
}
public function accessRules()
{
return array(
array('allow',
'actions' => array('login', 'logout'),
'users' => array('*'),
),
array('allow',
'actions' => array('*'),
'roles' => array('admin'),
),
array('deny',
'users' => array('*'),
),
);
}
}
in file WebUser:
class WebUser extends CWebUser
{
public function checkAccess($operation, $params = array())
{
if (empty($this->id)) {
return false;
}
$role = $this->getState("roles");
if ($role === 'admin') {
return true;
}
return ($operation === $role);
}
}
in file UserIdentity:
class UserIdentity extends CUserIdentity
{
private $id;
public function authenticate()
{
$record = AdminModel::model()->findByAttributes(array(
'username'=>$this->username));
if ($record == null) {
$this->errorCode = 'Username invalid';
} elseif($record->password !== $this->password) {
$this->errorCode = 'Password invalid';
} elseif($record->level == 'banned') {
$this->errorCode = 'Account being banned or not enabled';
} else {
$this->id = $record->id;
$this->setState('nameDisplay', $record->display_name);
$this->setState('roles', $record->level);
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->id;
}
}
when login, i check: Yii::app()->user->checkAccess('admin'); //return true
but this is error: You are not authorized to perform this action. somebody can help me?

I think this part of code is the problem:
array('deny',
'users' => array('*'),
),
It sais "Deny access to all pages for all users".
try to remove this part of code

Related

Yii2 Login failed to validate password

As the title says, i have a little bit of trouble in this area of the application. So basically, in my UserController i hash the password & in the login page it's verified with the standard security tool. Everything from the form to the user is good, but the check fails to return true. I don't have any interactions with the password in beforeSave/beforeValidate. Any ideas?
UserController:
public function actionRegister()
{
$model = new User(['scenario' => 'register']);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->password_usr = Yii::$app->security->generatePasswordHash($model->password_usr);
if ($model->save()) {
Yii::$app->session->setFlash('success', 'User created');
return $this->redirect('/site/login');
} else {
die(print_r($model->getErrors()));
}
}
return $this->render('register', [
'model' => $model,
]);
}
SiteController:
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->login();
return $this->goBack();
}
$model->password = '';
return $this->render('login', [
'model' => $model,
]);
}
User model:
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_usr);
}
Login form is the default as the yii2 generates
Maybe this is a problem
die(print_r($model->getErrors()));
login
public function actionLogin()
{
$this->layout = "login";
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
$model->password = '';
}
return $this->render('login', [
'model' => $model,
]);
}
signup
public function actionSignup()
{
$this->layout = "login";
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
the problem was the password field in the database, it was varchar(30) whilst generatePasswordHash returns a 60 char string

Yii1 - Declaration of model::validate() should be compatible with CModel::validate($attributes = NULL, $clearErrors = true)

I am getting this error when I try to run the index method inside the controller:
Declaration of OneTokenAuth::validate() should be compatible with CModel::validate($attributes = NULL, $clearErrors = true)
My controller:
<?php
/**
* Class is used for
*/
class OneTokenAuthController extends Controller
{
public function init()
{
$this->attachbehavior('restBehavior', new RestBehavior());
parent::init();
}
public function filters()
{
return ['accessControl',];
}
public function accessRules()
{
return [
[
'deny',
'actions' => [
'index',
],
'users' => ['#']
]
];
}
/**
* Entry point for validating JWT token
* If the token is valid, user will be logged in as an admin
* and redirected to the admin dashboard
*
* #param [string] $t
* #return void
*/
function actionIndex($t){
$token = CHtml::encode(strip_tags($t));
$auth = new OneTokenAuth($token);
if(!$auth->verify())
die('Token is not valid');
if(!$auth->validate())
die('Token is not valid');
$this->redirect('admin/jobs/dashboardNewest');
}
}
My model:
<?php
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Token;
use Lcobucci\JWT\ValidationData as JWTValidation;
/**
* This is the model class for table "jwt_access_log".
*
* The followings are the available columns in table 'jwt_access_log':
* #property integer $id
* #property text $token
* #property integer $token_status
* #property timespamp $created_at
*/
class OneTokenAuth extends CActiveRecord
{
const VALID = 100;
const UNVERIFIED = 200;
const NONVALID = 300;
private $_singkey;
private $_token;
private $_signer;
private $_data;
function __construct ($token){
$this->_singkey = '1234xxxx';
$this->_signer = new Sha256();
$this->_token =(new Parser())->parse((string) $token);
$this->_token->getHeaders(); // Retrieves the token header
$this->_token->getClaims(); // Retrieves the token claims
$this->_data = new JWTValidation;
$this->_data->setIssuer('http://example.com');
$this->_data->setAudience($this->_token->getClaim('iss'));
}
public function tableName()
{
return 'jwt_access_log';
}
public function rules()
{
return [
['token_status', 'numerical', 'integerOnly' => true],
['token', 'length', 'max' => 1024],
['created_at', 'safe'],
];
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'token' => 'Token',
'token_status' => 'Token Status',
'created_at' => 'Created At'
);
}
public function verify(){
if($this->_token->verify($this->_signer, $this->_singkey))
return true;
$this->makeLog(self::NONVALID);
return false;
}
public function validate(){
if($this->_token->validate($this->_data)){
$this->adminLogin();
return true;
}
$this->makeLog(self::UNVERIFIED);
return false;
}
public function makeLog($status)
{
$model = new self();
var_dump('<pre>', $model, '</pre>');die;
$model->setAttributes([
'token' => $this->_token,
'token_status' => $status,
]);
$model->save();
}
private function adminLogin()
{
$this->makeLog(self::VALID);
$login = new LoginComponent([
'email' => 'admin#admin.com',
'password' => 'u4ci_7aM%pigRe]Vp9B',
]);
$login->login();
}
}
What is going here?
The method in the derived class must have the same parameters as the parent class, you must specify parameters $attributes and $clearErrors
public function validate($attributes=null,$clearErrors=true){
if($this->_token->validate($this->_data)){
$this->adminLogin();
return true;
}
$this->makeLog(self::UNVERIFIED);
return false;
}

Basic Auth Laravel4 How to use it?

I try to protect my restAPI with credentials and reading about basic-auth laravel I try to implement a basic authentication sytem
User tabel already exists and populated with data
in filter.php I set
Route::filter('auth.basic', function() {
return Auth::basic(); });
than in api Route
// =============================================
// API ROUTES ==================================
// =============================================
Route::group(array('prefix' => 'api', 'before' => 'auth.basic'), function() {
Route::resource('products', 'ProductController', array('only' => array('index', 'store', 'destroy', 'update', 'show', 'edit')));
Route::get('products/{id}', 'ProductController#get', array('only' => array('show')));
});
the controller is quite simple
<?php
use App\Models\Product;
class ProductController extends \BaseController {
private $model;
function __construct() {
$this->model = new Product();
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index() {
$model = new Product();
$page = Input::get('pageNumber');
$limit = Input::get('pageNumber');
$ram = Input::get('limit');
$cpu = Input::get('cpu');
$price_range = Input::get('price_range');
$keyword = Input::get('keyword');
return Response::json($model->getProducts($page));
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store() {
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id) {
}
public function get($id) {
$model = new Product();
return Response::json($model->getProduct($id));
}
public function show($id) {
return Response::json($this->model->getProduct($id));
}
public function update($id) {
return Response::json($this->model->getProduct($id));
}
public function pause($id) {
var_dump('pause');
}
public function create(){
}
public function edit(){
var_dump('test_edit');
}
}
calling domain.com/api/products pop up login window. populating fields and submit datas can't log in
How do I check Users credentials?
For backend I use Sentry and it's working
filter.php
Route::filter('auth.admin', function() {
if (!Sentry::check()) {
return Redirect::route('admin.login');
}
});
Route
Route::get('admin/login', array('as' => 'admin.login', 'uses'
=> 'App\Controllers\Admin\AuthController#getLogin'));
Controller
<?php namespace App\Controllers\Admin;
use Auth, BaseController, Form, Input, Redirect, Sentry, View;
class AuthController extends BaseController {
/**
* Display the login page
* #return View
*/
public function getLogin()
{
return View::make('admin.auth.login');
}
/**
* Login action
* #return Redirect
*/
public function postLogin()
{
$credentials = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
try
{
$user = Sentry::authenticate($credentials, false);
if ($user)
{
return Redirect::route('admin.pages.index');
}
}
catch(\Exception $e)
{
return Redirect::route('admin.login')->withErrors(array('login' => $e->getMessage()));
}
}
/**
* Logout action
* #return Redirect
*/
public function getLogout()
{
Sentry::logout();
return Redirect::route('admin.login');
}
}
It seems that you don't have a login function defined.
by the way, you should change:
Route::group(array('prefix' => 'api', 'before' => 'auth.basic'), function() {
Route::resource('products', 'ProductController', array('only' => array('index', 'store', 'destroy', 'update', 'show', 'edit')));
Route::get('products/{id}', 'ProductController#get', array('only' => array('show')));
});
to:
Route::group(array('prefix' => 'api', 'before' => 'auth.basic'), function(){
Route::get('products/{id}', 'ProductController#get'));
Route::resource('products', 'ProductController', array('except' => array('show')));
});

call model in zend form using dependencies + zend framework 2

I am trying to fetch my category model in zend form for working out with select element with zend framework 2.
after lot of code searching I found I can either inject or pull dependencies.
Following code I did in my module.php
I want categoryTable.php(model) file in my CategoryForm.php
public function getServiceConfig()
{
return array(
'factories' => array(
'Category\Model\CategoryTable' => function($sm) {
$tableGateway = $sm->get('CategoryTableGateway');
$table = new CategoryTable($tableGateway);
//echo "<pre>";print_r($table);echo "</pre>";
return $table;
},
'CategoryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Category());
return new TableGateway('Of_Restaurants_Category', $dbAdapter, null, $resultSetPrototype);
},
'Category\Form\CategoryForm' => function ($sm) {
$service = $sm->get('Category\Model\CategoryTable');
$form = new Form;
$form->setService($service);
return $form;
}
),
);
}
then I put following code in my controller.
$form = $this->getServiceLocator()->get("Category\Form\CategoryForm");
Then I Put following code in my CategoryForm.php
public function getCategoryTable()
{
if (!$this->categoryTable) {
$sm = $this->getServiceLocator();
$this->categoryTable = $sm->get('Category\Model\CategoryTable');
}
return $this->categoryTable;
}
And then I call it in same file like this way
public function __construct($name = null)
{
parent::__construct('category');
echo "<pre>";print_r($this->getCategoryTable());die;
.... other code
I found this error
Fatal error: Call to undefined method Category\Form\CategoryForm::getServiceLocator() in D:\wamp\www\zendapp\module\Category\src\Category\Form\CategoryForm.php on line 120
please help. and am I missing something?
I found the solution
Step :1
Here is my module.php code
public function getServiceConfig()
{
return array(
'invokables' => array(
'Category\Form\CategoryForm' => 'Category\Form\CategoryForm',
),
'factories' => array(
'Category\Model\CategoryTable' => function($sm) {
$tableGateway = $sm->get('CategoryTableGateway');
$table = new CategoryTable($tableGateway);
//echo "<pre>";print_r($table);echo "</pre>";
return $table;
},
'CategoryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Category());
return new TableGateway('Of_Restaurants_Category', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
Step :2
Then in controller I made this change
// $form = new CategoryForm();
// Service locator now injected
$form = $this->getServiceLocator()->get('Category\Form\CategoryForm');
Step :3
Then In my categoryForm.php I made below changes
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
protected $serviceManager;
public function getCategoryTable()
{
if (!$this->categoryTable) {
$sm = $this->getServiceManager();
$this->categoryTable = $sm->get('Category\Model\CategoryTable');
}
return $this->categoryTable;
}
protected function getCatList()
{
$groups = $this->getCategoryTable()->fetchAll();
return $groups;
}
public function getServiceManager()
{
if ( is_null($this->serviceManager) ) {
throw new Exception('The ServiceManager has not been set.');
}
return $this->serviceManager;
}
public function setServiceManager(ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
// Call the init function of the form once the service manager is set
$this->init();
return $this;
}
public function __construct($name = null) // constructor I finished immediately
{
parent::__construct('category');
}
I add INIT() function to fetch servicemanager
public function init()
{
$this->setAttribute('method', 'post');
$options = array();
foreach ($this->getCatList() as $cat) {
$options[$cat->id] = $cat->title;
}
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'parent_id',
'options' => array(
'label' => 'Parent Category',
'empty_option' => 'Please choose Parent Category',
'value_options' => $options,
),
));
}
Hope this will help who are new ZF2.

yii user-management edit field

I have managed to set-up yii-user-management. Thanks to help from here.
However, when I am in profile/fields/admin .
I click on edit field and then change the field from required 'no' to 'yes' in the dropdown, then save, but nothing happens.
I also get :
CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(0) NOT NULL DEFAULT 0' at line 1. The SQL statement executed was: ALTER TABLE profile ADD `` (0) NOT NULL DEFAULT 0
When creating a field.
Let me know if you need some code or files. Any help appreciated.
Here is the profile/models/YumProfileField.php
class YumProfileField extends YumActiveRecord
{
const VISIBLE_HIDDEN=0;
const VISIBLE_ONLY_OWNER=1;
const VISIBLE_REGISTER_USER=2;
const VISIBLE_USER_DECISION=3;
const VISIBLE_PUBLIC=4; // Field is public even if the user decides to hide it
/**
* Returns the static model of the specified AR class.
* #param string $className
* #return YumProfileField
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function isPublic($user = null) {
if($user == null)
$user = Yii::app()->user->id;
if(!$this->visible)
return false;
if($privacy = YumUser::model()->findByPk($user)->privacy) {
if($privacy->public_profile_fields & pow(2, $this->id))
return true;
}
return false;
}
public function tableName()
{
$this->_tableName = Yum::module('profile')->profileFieldTable;
return $this->_tableName;
}
public function scopes()
{
return array(
'forAll'=>array(
'condition'=>'visible='.self::VISIBLE_PUBLIC,
),
'forUser'=>array(
'condition'=>'visible>='.self::VISIBLE_REGISTER_USER,
),
'forOwner'=>array(
'condition'=>'visible>='.self::VISIBLE_ONLY_OWNER,
),
);
}
public static function itemAlias($type,$code=NULL) {
$_items = array(
'field_type' => array(
'INTEGER' => Yum::t('INTEGER'),
'VARCHAR' => Yum::t( 'VARCHAR'),
'TEXT'=> Yum::t( 'TEXT'),
'DATE'=> Yum::t( 'DATE'),
'DROPDOWNLIST' => Yum::t('DROPDOWNLIST'),
'FLOAT'=> Yum::t('FLOAT'),
'BOOL'=> Yum::t('BOOL'),
'BLOB'=> Yum::t('BLOB'),
'BINARY'=> Yum::t('BINARY'),
'FILE'=> 'FILE',
),
'required' => array(
'0' => Yum::t('No'),
'1' => Yum::t('Yes'),
),
'visible' => array(
self::VISIBLE_USER_DECISION => Yum::t('Let the user choose in privacy settings'),
self::VISIBLE_PUBLIC => Yum::t('For all'),
self::VISIBLE_REGISTER_USER => Yum::t('Registered users'),
self::VISIBLE_ONLY_OWNER => Yum::t('Only owner'),
self::VISIBLE_HIDDEN => Yum::t('Hidden'),
),
);
if (isset($code))
return isset($_items[$type][$code]) ? $_items[$type][$code] : false;
else
return isset($_items[$type]) ? $_items[$type] : false;
}
}
The YumFieldsController:
class YumFieldsController extends YumController
{
const PAGE_SIZE=10;
public function accessRules()
{
return array(
array('allow',
'actions'=>array('index', 'create', 'update', 'view', 'admin','delete'),
'users'=>array(Yii::app()->user->name),
'expression' => 'Yii::app()->user->isAdmin()'
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
public function actionView()
{
$this->layout = Yum::module()->adminLayout;
$this->render('view',array(
'model'=>$this->loadModel('YumProfileField'),
));
}
public function actionCreate() {
$this->layout = Yum::module()->adminLayout;
$model = new YumProfileField;
// add to group?
if(isset($_GET['in_group']))
$model->field_group_id=$_GET['in_group'];
if(isset($_POST['YumProfileField'])) {
$model->attributes = $_POST['YumProfileField'];
$field_type = $model->field_type;
if($field_type == 'DROPDOWNLIST')
$field_type = 'INTEGER';
if($model->validate()) {
$sql = 'ALTER TABLE '.YumProfile::model()->tableName().' ADD `'.$model->varname.'` ';
$sql .= $field_type;
if ($field_type!='TEXT' && $field_type!='DATE')
$sql .= '('.$model->field_size.')';
$sql .= ' NOT NULL ';
if ($model->default)
$sql .= " DEFAULT '".$model->default."'";
else
$sql .= (($field_type =='TEXT' || $model->field_type=='VARCHAR')?" DEFAULT ''":" DEFAULT 0");
$model->dbConnection->createCommand($sql)->execute();
$model->save();
$this->redirect(array('view','id'=>$model->id));
}
}
$this->render('create',array(
'model'=>$model,
));
}
public function actionUpdate()
{
$this->layout = Yum::module()->adminLayout;
$model = $this->loadModel('YumProfileField');
if(isset($_POST['YumProfileField']))
{
$model->attributes=$_POST['YumProfileField'];
// ALTER TABLE `test` CHANGE `profiles` `field` INT( 10 ) NOT NULL
// ALTER TABLE `test` CHANGE `profiles` `description` INT( 1 ) NOT NULL DEFAULT '0'
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
public function actionDelete()
{
$this->layout = Yum::module()->adminLayout;
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request
$model = $this->loadModel('YumProfileField');
$sql = 'ALTER TABLE '.YumProfile::model()->tableName().' DROP `'.$model->varname.'`';
if ($model->dbConnection->createCommand($sql)->execute()) {
$model->delete();
}
if(!isset($_POST['ajax']))
$this->redirect(array('index'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
public function actionIndex()
{
$this->layout = Yum::module()->adminLayout;
$dataProvider=new CActiveDataProvider('YumProfileField', array(
'pagination'=>array(
'pageSize'=>self::PAGE_SIZE,
),
'sort'=>array(
'defaultOrder'=>'position',
),
));
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
public function actionAdmin()
{
$this->layout = Yum::module()->adminLayout;
$dataProvider=new CActiveDataProvider('YumProfileField', array(
'pagination'=>array(
'pageSize'=>self::PAGE_SIZE,
),
'sort'=>array(
'defaultOrder'=>'position',
),
));
$this->render('admin',array(
'dataProvider'=>$dataProvider,
));
}
}
YumProfile.php model
class YumProfile extends YumActiveRecord
{
const PRIVACY_PRIVATE = 'private';
const PRIVACY_PUBLIC = 'public';
/**
* #var array of YumProfileFields
*/
static $fields=null;
public function init()
{
parent::init();
// load profile fields only once
$this->loadProfileFields();
}
public function afterSave() {
if($this->isNewRecord)
Yii::log(Yum::t( 'A profile been created: {profile}', array(
'{profile}' =>json_encode($this->attributes))));
else
Yii::log(Yum::t( 'A profile been update: {profile}', array(
'{profile}' => json_encode($this->attributes))));
return parent::afterSave();
}
public function recentComments($count = 3) {
$criteria = new CDbCriteria;
$criteria->condition = 'id = ' .$this->id;
$criteria->order = 'createtime DESC';
$criteria->limit = $count;
return YumProfileComment::model()->findAll($criteria);
}
public function beforeValidate() {
if($this->isNewRecord)
$this->timestamp = time();
return parent::beforeValidate();
}
/**
* #param string $className
* #return YumProfile
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
// All fields that the user has activated in his privacy settings will
// be obtained and returned for the use in the profile view
public function getPublicFields() {
if(!Yum::module('profile')->enablePrivacySetting)
return false;
$fields = array();
if($privacy = YumUser::model()
->cache(500)
->with('privacy')
->findByPk($this->user_id)
->privacy->public_profile_fields) {
$i = 1;
foreach(YumProfileField::model()->cache(3600)->findAll() as $field) {
if(
(($i & $privacy)
&& $field->visible != YumProfileField::VISIBLE_HIDDEN)
|| $field->visible == YumProfileField::VISIBLE_PUBLIC)
$fields[] = $field;
$i*=2;
}
}
return $fields;
}
/**
* Returns resolved table name
* #return string
*/
public function tableName()
{
$this->_tableName = Yum::module('profile')->profileTable;
return $this->_tableName;
}
public function rules()
{
$required = array();
$numerical = array();
$rules = array();
$safe = array();
foreach (self::$fields as $field) {
$field_rule = array();
if ($field->required == 1)
array_push($required, $field->varname);
if ($field->field_type == 'int'
|| $field->field_type == 'FLOAT'
|| $field->field_type =='INTEGER'
|| $field->field_type =='BOOLEAN')
array_push($numerical, $field->varname);
if ($field->field_type == 'DROPDOWNLIST')
array_push($safe, $field->varname);
if ($field->field_type == 'VARCHAR' || $field->field_type == 'TEXT') {
$field_rule = array($field->varname,
'length',
'max'=>$field->field_size,
'min' => $field->field_size_min);
if ($field->error_message)
$field_rule['message'] = Yum::t($field->error_message);
array_push($rules,$field_rule);
}
if ($field->match) {
$field_rule = array($field->varname,
'match',
'pattern' => $field->match);
if ($field->error_message)
$field_rule['message'] = Yum::t( $field->error_message);
array_push($rules,$field_rule);
}
if ($field->range) {
// allow using commas and semicolons
$range=explode(';',$field->range);
if(count($range)===1)
$range=explode(',',$field->range);
$field_rule = array($field->varname,'in','range' => $range);
if ($field->error_message)
$field_rule['message'] = Yum::t( $field->error_message);
array_push($rules,$field_rule);
}
if ($field->other_validator) {
$field_rule = array($field->varname,
$field->other_validator);
if ($field->error_message)
$field_rule['message'] = Yum::t( $field->error_message);
array_push($rules, $field_rule);
}
}
array_push($rules,
array(implode(',',$required), 'required'));
array_push($rules,
array(implode(',',$numerical), 'numerical', 'integerOnly'=>true));
array_push($rules,
array(implode(',',$safe), 'safe'));
$rules[] = array('allow_comments, show_friends', 'numerical');
$rules[] = array('email', 'unique');
$rules[] = array('email', 'CEmailValidator');
$rules[] = array('privacy', 'safe');
return $rules;
}
public function relations()
{
$relations = array(
'user' => array(self::BELONGS_TO, 'YumUser', 'user_id'),
'comments' => array(self::HAS_MANY, 'YumProfileComment', 'profile_id'),
);
$fields = Yii::app()->db->cache(3600)->createCommand(
"select * from ".YumProfileField::model()->tableName()." where field_type = 'DROPDOWNLIST'")->queryAll();
foreach($fields as $field) {
$relations[ucfirst($field['varname'])] = array(
self::BELONGS_TO, ucfirst($field['varname']), $field['varname']);
}
return $relations;
}
// Retrieve a list of all users that have commented my profile
// Do not show my own profile visit
public function getProfileCommentators() {
$commentators = array();
foreach($this->comments as $comment)
if($comment->user_id != Yii::app()->user->id)
$commentators[$comment->user_id] = $comment->user;
return $commentators;
}
public function getProfileFields() {
$fields = array();
if(self::$fields)
foreach(self::$fields as $field) {
$varname = $field->varname;
$fields[$varname] = Yum::t($varname);
}
return $fields;
}
public function name() {
return sprintf('%s %s', $this->firstname, $this->lastname);
}
public function attributeLabels()
{
$labels = array(
'id' => Yum::t('Profile ID'),
'user_id' => Yum::t('User ID'),
'privacy' => Yum::t('Privacy'),
'show_friends' => Yum::t('Show friends'),
'allow_comments' => Yum::t('Allow profile comments'),
);
if(self::$fields)
foreach (self::$fields as $field)
$labels[$field->varname] = Yum::t($field->title);
return $labels;
}
/**
* Load profile fields.
* Overwrite this method to get another set of fields
* Makes use of cache so the amount of sql queries per request is reduced
* #since 0.6
* #return array of YumProfileFields or empty array
*/
public function loadProfileFields()
{
if(self::$fields===null)
{
self::$fields=YumProfileField::model()->cache(3600)->findAll();
if(self::$fields==null)
self::$fields=array();
}
return self::$fields;
}
}
looks like you're trying to add a column with no name or type? MySQL ALTER TABLE examples.
Also, check your db user has permissions to ALTER TABLE.