I am new to yii frame work I am trying to create an ldap configuration for user authentication
The following steps which I taken to create but it throws eerro as below
include(Controller.php) [function.include]: failed to open stream: No such file or directory
C:\xampp\htdocs\yiif\framework\YiiBase.php(418)
steps:
1. I have included the following ldaprecord/
extension in C:\xampp\htdocs\seed2\protected\extensions\ldaprecord
2. I have included the following code in config/main.php
`'components'=>array(
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
),
'ldap'=>array(
'class' => 'ext.ldaprecord.LdapComponent',
'server' => 'ldap://192.168.x.xxxx',
'port' => 389,
//'bind_rdn' => 'cn=suren diran,cn=Users,dc=xxxx,dc=demo,dc=com',
//'bind_pwd' => 'pass#123',
'base_dn' => 'dc=rsales,dc=demo,dc=com'),);
'params'=>array(
// this is used in contact page
'adminEmail'=>'sundarapandian#rsalesarm.com',
),
'ldap'=>array(
'class' => 'ext.ldaprecord.LdapComponent',
'server' => 'ldap://192.168.x.xxx',
'port' => 389,
//'bind_rdn' => 'cn=xxxx xxxx,cn=Users,dc=xxxx,dc=demo,dc=com',
//'bind_pwd' => 'pass#123',
'base_dn' => 'dc=xxxxx,dc=demo,dc=com'),
);`
included this line in the index.php
$config=dirname(__FILE__).'/protected/extensions/ldaprecord/CLdapRecord.php';
and I have changed the useridentity authentication function as
`
public function authenticate()
{
$username=$this->username;
$password=$this->password;
$dname= 'xxxxxxx';
$options['host']='ldap://192.168.x.xxx';
$options['port']=389;
$ldap_username = "CN=".$username.",CN=Users,DC=xxxx,DC=demo,DC=com";
$options = Yii::app()->params['ldap'];
print_r($options);
$connection = ldap_connect($options['host'], $options['port']);
//print_r($connection);
ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($connection, LDAP_OPT_REFERRALS, 0);
if($connection)
{
echo "success";
//exit;
try
{
//echo $connection.$ldap_username.$this->password;
//print_r(ldap_bind($connection,$dname."\\". $ldap_username, $password));
//exit;
#$bind = ldap_bind($connection,$dname."\\". $ldap_username, $password);
print_r(#$bind);
if(#$bind)
{
echo "successfully logedin";
}
}
catch (Exception $e){
echo $e->getMessage();
}
if(!$bind) $this->errorCode = self::ERROR_PASSWORD_INVALID;
else $this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
};`
I am stucked here can any one help me hw to resolve this issue .please help me ,Thanks in advance..........
controller.php file was exists in the protected/components
even I check that it was included in the main .php
'import'=>array(
'application.models.*',
'application.components.*',
'ext.ldaprecord.*',
),
if I remove the following line the following error will shown
code:
$config=dirname(__FILE__).'/protected/extensions/ldaprecord/CLdapRecord.php'
error:
Property "CWebApplication.ldap" is not defined.
yes I am using that extension only which u given link above([http://www.yiiframework.com/extension/ldaprecord/]),if u have any other extension please can u provide that link and what the steps need to be taken for that to implement .........thanks in advance..........
HIIIIII
I done mistake in the params now I have changed that as below , and I removed the
$config=dirname(__FILE__).'/protected/extensions/ldaprecord/CLdapRecord.php';
it was not throwing any error .
I am including the my main.php full code below:
<?php
return array(
'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
'name'=>'xxxxxx',
// preloading 'log' component
'preload'=>array('log'),
// autoloading model and component classes
'import'=>array(
'application.models.*',
'application.components.*',
//ldap config added code
'ext.ldaprecord.*',
),
'defaultController' => 'site/login',
'modules'=>array(
// uncomment the following to enable the Gii tool
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'pass',
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters'=>array('127.0.0.1','::1'),
),
),
// application components
'components'=>array(
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
),
// uncomment the following to enable URLs in path-format
/*'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
),
),*/
/*'db'=>array(
'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
),*/
// uncomment the following to use a MySQL database
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=xxxxx',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'tablePrefix' => '',
),
'errorHandler'=>array(
// use 'site/error' action to display errors
'errorAction'=>'site/error',
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning',
),
// uncomment the following to show log messages on web pages
/*
array(
'class'=>'CWebLogRoute',
),
*/
),
),
'ldap'=>array(
'class' => 'ext.ldaprecord.LdapComponent',
'server' => 'ldap://192.168.x.xxx',
'port' => 389,
//'bind_rdn' => 'cn=suren diran,cn=Users,dc=xxxxxx,dc=demo,dc=com',
//'bind_pwd' => 'pass#123',
'base_dn' => 'dc=xxxxx,dc=demo,dc=com'),
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params'=>array(
// this is used in contact page
'adminEmail'=>'xxx#xxxx.com',
'ldap'=>array(
'class' => 'ext.ldaprecord.LdapComponent',
'server' => 'ldap://192.168.x.xxx',
'port' => 389,
//'bind_rdn' => 'cn=suren diran,cn=Users,dc=xxxxx,dc=demo,dc=com',
//'bind_pwd' => 'pass#123',
'base_dn' => 'dc=xxxx,dc=demo,dc=com'),
),
);
I am including my useridentity function below:
<?php
public function authenticate()
{
$options = Yii::app()->params['ldap'];
//print_r($options);
$connection = ldap_connect($options['host'], $options['port']);
ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($connection, LDAP_OPT_REFERRALS, 0);
if($connection)
{
// try
// {
//echo $options['domain']."\\".$this->username. $this->password;
//exit;
$ldap_username = "CN=".$this->username.",CN=xxxx,DC=xxxx,DC=demo,DC=com";
$ldap_password=$this->password;
echo $connection.$ldap_username.$ldap_password;
//$bind=ldap_bind($connection, $ldap_username, $ldap_password)
//exit;
//print_r(ldap_bind($connection,$ldap_username,$ldap_password));
$bind = #ldap_bind($connection,$ldap_username, $ldap_password);
print_r($bind);
//exit;
//#$bind = ldap_bind($connection,$ldap_username, $ldap_password);
// $abc=#$bind;
//print_r($abc);
//exit;
/*}
catch (Exception $e){
echo $e->getMessage();
}*/
if(!$bind) $this->errorCode = self::ERROR_PASSWORD_INVALID;
else $this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
But in the above one the ldap_bind is not working can u help on this ........
Please help me I how to overcome this .........thanks alot.....
I've just been reading this:
$config=dirname(__FILE__).'/protected/extensions/ldaprecord/CLdapRecord.php'
Why have you done that? I assume you're using this extension: It doesn't advise anywhere in thedocumentation to do so. This is pretty much emptying your application's config - including the import-stanza which is ultimately letting the include of the Controller.php fail.
Since you asked for another extension I would point you to this blog post. It's not an extension but is fairly detailed on how to set it up and looks like it will accomplish the same end goal for you.
Related
I'm working on a project with zf2, and the zfcuser module with doctrine. I have created a custom user module that extends zfcuser, also a custom entity for the user table, and make all the necessary changes for the integration. But my problem is when trying to authenticate myself, I get this error:
An alias "Zend\Db\Adapter\Adapter" was requested but no service could be found.
This happens when zfcuser_user_mapper attempts to change the adapter.
Note: I am not very clear why I need to use the Zend \ Db \ Adapter \ Adapter, since I am working with doctrine.
This is the code in the module.php of the custom user module.
public function getServiceConfig() {
return [
'aliases' => array(
'zfcuser_zend_db_adapter' => 'Zend\Db\Adapter\Adapter',
),
'factories' => [
'usuario_login_form' => 'Usuario\Factory\Form\Login',
'usuario_registro_form' => 'Usuario\Factory\Form\Register',
'usuario_user_service' => 'Usuario\Factory\Service\UserFactory',
//'usuario_user_mapper' => 'Usuario\Factory\Mapper\User',
'usuario_auth_service' => 'Usuario\Factory\AuthenticationService',
'Usuario\Authentication\Adapter\Db' => 'Usuario\Factory\Authentication\Adapter\DbFactory',
'Usuario\Authentication\Storage\Db' => 'Usuario\Factory\Authentication\Storage\DbFactory',
//'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\Adapter',
'usuario_user_mapper' => function ($sm) {
$mapper = new Mapper\User();
$mapper->setDbAdapter($sm->get('zfcuser_zend_db_adapter'));
$mapper->setEntityPrototype(new ORM\Entity\Usuarios());
$mapper->setHydrator(new \ZfcUser\Mapper\UserHydrator());
return $mapper;
},
]
];
}
This is my global.php file
return array(
'doctrine' => array(
'connection' => array(
'orm_default' => array(
'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
'params' => array(
'host' => 'localhost',
'port' => '3306',
'user' => 'root',
'password' => 'toor',
'dbname' => 'deporte',
)
)
)
),
);
This is my module.config.php file:
'controllers' => array(
),
'doctrine' => array(
'driver' => array(
// overriding zfc-user-doctrine-orm's config
'usuario_entity' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'paths' => __DIR__ . '/../src/Usuario/ORM/Entity',
),
'orm_default' => array(
'drivers' => array(
'Usuario\ORM\Entity' => 'usuario_entity',
),
),
),
),
'zfcuser' => array(
'auth_adapters' => array(100 => 'Usuario\Authentication\Adapter\Db'),
// telling ZfcUser to use our own class
'user_entity_class' => 'Usuario\ORM\Entity\Usuarios',
// telling ZfcUserDoctrineORM to skip the entities it defines
'enable_default_entities' => false,
),
I thank you for the help, I have already been with this error for days. Thank you very much, and excuse my English.
If you want to change the Entity and want to use your then use following steps:
if the zfcuser.global.php file which is placed in config/autoload folder (if not then you can copy if from zfcuser module.
In this global file search for "user_entity_class" key and define your own entity class.By default it uses
'user_entity_class' => 'ZfcUser\Entity\User',
Like I am using it for Employee entity
'user_entity_class' => 'Employee\Entity\Employee',
In this entity you need to implement UserInterface.
use ZfcUser\Entity\UserInterface;
/**
* Employee
*
* #ORM\Table(name="employee")
* #ORM\Entity(repositoryClass="Employee\Repository\EmployeeRepository")
*/
class Employee implements UserInterface {
}
If you want to override db adapter then you need to do following steps:
'service_manager' => array(
'invokables' => array(
'ZfcUser\Authentication\Adapter\Db' => 'Employee\Authentication\Adapter\Db',
),
),
In this file you need to extend and implements.
namespace Employee\Authentication\Adapter;
use InvalidArgumentException;
use Zend\Authentication\Result as AuthenticationResult;
use Zend\Crypt\Password\Bcrypt;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use Zend\Session\Container as SessionContainer;
use ZfcUser\Authentication\Adapter\AdapterChainEvent as AuthenticationEvent;
use ZfcUser\Entity\UserInterface as UserEntity;
use ZfcUser\Mapper\HydratorInterface as Hydrator;
use ZfcUser\Mapper\UserInterface as UserMapper;
use ZfcUser\Authentication\Adapter\AbstractAdapter;
use ZfcUser\Options\AuthenticationOptionsInterface as AuthenticationOptions;
class Db extends AbstractAdapter implements ServiceManagerAwareInterface
{
}
For more information you can follow zfcuser wiki here:
https://github.com/ZF-Commons/ZfcUser/wiki
Fatal error: Call to undefined method Rights::t()
Getting this error when ever i want to go in any controller or in any controller's action. I am using yii user and rights. for instance when i type localhost/business/address/create i get the above error.
Yii user is working fine, even rights too. But i cannot access any controller.
'bootstrap',
'basePath'=>dirname(FILE).DIRECTORY_SEPARATOR.'..',
'name'=>'My Web Application',
// preloading 'log' component
'preload'=>array('log'),
'aliases' => array(
'bootstrap' => 'ext.bootstrap' ),
// autoloading model and component classes
'import'=>array(
//addedd these lines
'application.modules.user.models.*',
'application.modules.user.components.*',
'application.modules.rights.*',
'application.modules.rights.components.*',
'application.models.*',
'application.components.*',
'bootstrap.behaviors.*',
'bootstrap.helpers.*',
'bootstrap.widgets.*'
),
'modules'=>array(
// uncomment the following to enable the Gii tool
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'centangle',
'generatorPaths' => array( 'bootstrap.gii', ),
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters'=>array('127.0.0.1','::1'),
),
'user'=>array(
'tableUsers' => 'user',
'tableProfiles' => 'profiles',
'tableProfileFields' => 'profiles_fields',
# encrypting method (php hash function)
'hash' => 'md5',
# send activation email
'sendActivationMail' => true,
# allow access for non-activated users
'loginNotActiv' => false,
# activate user on registration (only sendActivationMail = false)
'activeAfterRegister' => false,
# automatically login from registration
'autoLogin' => true,
# registration path
'registrationUrl' => array('/user/registration'),
# recovery password path
'recoveryUrl' => array('/user/recovery'),
# login form path
'loginUrl' => array('/user/login'),
# page after login
'returnUrl' => array('/user/profile'),
# page after logout
'returnLogoutUrl' => array('/user/login'),
),
'rights'=>array(
'install'=>true,
'superuserName'=>'admin', // Name of the role with super user privileges.
'authenticatedName'=>'Authenticated', // Name of the authenticated user role.
'userIdColumn'=>'id', // Name of the user id column in the database.
'userNameColumn'=>'username', // Name of the user name column in the database.
'enableBizRule'=>true, // Whether to enable authorization item business rules.
'enableBizRuleData'=>true, // Whether to enable data for business rules.
'displayDescription'=>true, // Whether to use item description instead of name.
'flashSuccessKey'=>'RightsSuccess', // Key to use for setting success flash messages.
'flashErrorKey'=>'RightsError', // Key to use for setting error flash messages.
'baseUrl'=>'/rights', // Base URL for Rights. Change if module is nested.
'layout'=>'rights.views.layouts.main', // Layout to use for displaying Rights.
'appLayout'=>'application.views.layouts.main', // Application layout.
'cssFile'=>'rights.css', // Style sheet file to use for Rights.
'install'=>false, // Whether to enable installer.
'debug'=>false,
),
),
// application components
'components'=>array(
'user'=>array(
'class'=>'WebUser',
// enable cookie-based authentication
'allowAutoLogin'=>true,
'loginUrl'=>array('/user/login'),
),
'authManager'=>array(
'class'=>'RDbAuthManager',
'connectionID'=>'db',
'itemTable'=>'authitem',
'itemChildTable'=>'authitemchild',
'assignmentTable'=>'authassignment',
'rightsTable'=>'rights',
'defaultRoles'=>array('Authenticated', 'Guest'),
),
'bootstrap' => array(
'class' => 'bootstrap.components.BsApi', ),
// uncomment the following to enable URLs in path-format
'urlManager'=>array(
'urlFormat'=>'path',
'showScriptName' => false,
'rules'=>array(
'user/registration/<id:\w+>' => 'user/registration',
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
),
/*'db'=>array(
'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
),*/
// uncomment the following to use a MySQL database
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=copy',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
),
'errorHandler'=>array(
// use 'site/error' action to display errors
'errorAction'=>'site/error',
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning',
),
// uncomment the following to show log messages on web pages
/*
array(
'class'=>'CWebLogRoute',
),
*/
),
),
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params'=>array(
// this is used in contact page
'adminEmail'=>'webmaster#example.com',
),
);
and this is my controller business
class BusinessController extends RController
{
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
'rights',
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* #param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Business;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Business']))
{
$model->attributes=$_POST['Business'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Business']))
{
$model->attributes=$_POST['Business'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* #param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Business');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Business('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Business']))
$model->attributes=$_GET['Business'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* #param integer $id the ID of the model to be loaded
* #return Business the loaded model
* #throws CHttpException
*/
public function loadModel($id)
{
$model=Business::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* #param Business $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='business-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
it is because of this mistake.the problem lies in the writing of the code, make sure you must write your code in config.main like this
'import' => array(
'application.models.*',
'application.components.*',
'bootstrap.behaviors.*',
'bootstrap.helpers.*',
'bootstrap.widgets.*',
//add this code after the above code and thats it, a small stupid mistake may cost you 3 days of hard debugging.
'application.modules.user.models.*',
'application.modules.user.components.*',
'application.modules.rights.*',
'application.modules.rights.components.*'
),
access rules of pages controller:
public function accessRules()
{
$isadmin = User::loadUser(Yii::app()->user->id)->adminUser;
return array(
array('allow',
'actions'=>array('index','view','create','update'),
'expression'=>"{$isadmin}==1",
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
main config:
'user' => array( // Webuser for the admin area (admin)
'class' => 'WebUser',
'allowAutoLogin' => true,
'loginUrl' => array('/user/login'),
'stateKeyPrefix' => 'admin_',
),
Problem:
When I visit pages/create, it not redirected to user/login but throws the exception:
Error 404
The requested page does not exist.
How Can I redirect to login pages for unauthorized user?
You can use 'deniedCallback' to do this.
Method 1
'deniedCallback' => function() {Yii::app()->controller->redirect(array ('actionName'));},
//It will come As
array('allow',
'actions' => array('actionName1,actionName2,actionName3'),
'deniedCallback' => function() {Yii::app()->controller->redirect(array ('actionName'));},
'users' => array('#'),
),
Method 2:
You can also do the same by calling a function, see bellow code.
array('allow',
'deniedCallback' => array($this, 'goToLogin'),
'actions' => array('actionName1,actionName2,actionName3'),
'users' => array('#'),
),
Code for goToLogin method
public function goToLogin()
{
$this->redirect('/controller/actionName');
//For your program
//$this->redirect('/site/login');
}
Yii::app()->user->loginRequired();
add this funtion in every controller.
public function beforeAction($action) {
if (Yii::app()->user->isGuest && Yii::app()->controller->action->id != "login") {
Yii::app()->user->loginRequired();
}
//something code right here if user valid
return true;
}
site controller only needs Yii::app()->controller->action->id != "login" this condition. remove it for another controllers
Can anyone please help and advice how to install yii user management module into yii boilerplate?
I downloaded auth module and place in common/modules folder, and edit backend/config/main.php as below:
$backendConfigDir = dirname(__FILE__);
$root = $backendConfigDir . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..';
$params = require_once($backendConfigDir . DIRECTORY_SEPARATOR . 'params.php');
// Setup some default path aliases. These alias may vary from projects.
Yii::setPathOfAlias('root', $root);
Yii::setPathOfAlias('common', $root . DIRECTORY_SEPARATOR . 'common');
Yii::setPathOfAlias('backend', $root . DIRECTORY_SEPARATOR . 'backend');
Yii::setPathOfAlias('www', $root . DIRECTORY_SEPARATOR . 'backend' . DIRECTORY_SEPARATOR . 'www');
/* uncomment if you need to use frontend folders */
/* Yii::setPathOfAlias('frontend', $root . DIRECTORY_SEPARATOR . 'frontend'); */
$mainLocalFile = $backendConfigDir . DIRECTORY_SEPARATOR . 'main-local.php';
$mainLocalConfiguration = file_exists($mainLocalFile) ? require($mainLocalFile) : array();
$mainEnvFile = $backendConfigDir . DIRECTORY_SEPARATOR . 'main-env.php';
$mainEnvConfiguration = file_exists($mainEnvFile) ? require($mainEnvFile) : array();
return CMap::mergeArray(
array(
'name' => '',
'basePath' => 'backend',
// set parameters
'params' => $params,
// preload components required before running applications
'preload' => array('bootstrap', 'log'),
'language' => 'en',
'import' => array(
'common.components.*',
'common.extensions.*',
/* uncomment if required */
/* 'common.extensions.behaviors.*', */
/* 'common.extensions.validators.*', */
'common.models.*',
// uncomment if behaviors are required
// you can also import a specific one
/* 'common.extensions.behaviors.*', */
// uncomment if validators on common folder are required
/* 'common.extensions.validators.*', */
'application.components.*',
'application.controllers.*',
'application.models.*',
'application.helpers.*',
),
/* uncomment and set if required */
'modules' => array(
'gii' => array(
'class' => 'system.gii.GiiModule',
'password' => 'clevertech',
'generatorPaths' => array(
'bootstrap.gii'
)
),
'auth' => array(
'strictMode' => true, // when enabled authorization items cannot be assigned children of the same type.
'userClass' => 'User', // the name of the user model class.
'userIdColumn' => 'id', // the name of the user id column.
'userNameColumn' => 'username', // the name of the user name column.
'appLayout' => 'application.views.layouts.main', // the layout used by the module.
),
),
'components' => array(
'clientScript' => array(
'class' => 'application.extensions.minify.EClientScript',
'combineScriptFiles' => !YII_DEBUG, // By default this is set to true, set this to true if you'd like to combine the script files
'combineCssFiles' => !YII_DEBUG, // By default this is set to true, set this to true if you'd like to combine the css files
'optimizeScriptFiles' => !YII_DEBUG, // #since: 1.1
'optimizeCssFiles' => !YII_DEBUG, // #since: 1.1
),
'request' => array(
'enableCsrfValidation' => true,
'enableCookieValidation' => true,
),
'authManager' => array(
'class' => 'CDbAuthManager',
'connectionID' => 'db',
'itemTable' => 'AuthItem',
'itemChildTable' => 'AuthItemChild',
'assignmentTable' => 'AuthAssignment',
'behaviors' => array(
'auth' => array(
'class' => 'auth.components.AuthBehavior',
'admins' => array('admin', 'foo', 'bar'), // users with full access
),
),
// 'behaviors' => array(
// 'auth' => array(
// 'class' => 'auth.components.AuthBehavior',
// ),
// ),
),
'image' => array(
'class' => 'application.extensions.image.CImageComponent',
// GD or ImageMagick
'driver' => 'GD',
// ImageMagick setup path
//'params' => array('directory' => '/opt/local/bin'),
),
'email' => array(
'class' => 'application.extensions.email.Email',
'delivery' => 'php', //Will use the php mailing function.
//May also be set to 'debug' to instead dump the contents of the email into the view
),
'user' => array(
// 'class' => 'WebUser',
'class' => 'auth.components.AuthWebUser',
// 'admins' => array('admin', 'foo', 'bar'), // users with full access
'allowAutoLogin' => true,
),
/* load bootstrap components */
'bootstrap' => array(
'class' => 'common.extensions.bootstrap.components.Bootstrap',
'responsiveCss' => true,
),
'cache' => array(
'class' => 'CApcCache',
// 'class' => 'CFileCache',
),
'errorHandler' => array(
'errorAction' => 'site/error'
),
'urlManager' => array(
'urlFormat' => 'path',
'showScriptName' => false,
'urlSuffix' => '/',
'rules' => $params['url.rules']
),
/* make sure you have your cache set correctly before uncommenting */
'cache' => $params['cache.core'],
'contentCache' => $params['cache.content']
),
), CMap::mergeArray($mainEnvConfiguration, $mainLocalConfiguration)
);
but it doesn't work error msg says:
Alias "auth.AuthModule" is invalid. Make sure it points to an existing PHP file and the file is readable.
Also, i have no idea what is the perfect path for uploaded files from both frontend and backend?
Change code as following under module
auth' => array(
'strictMode' => true, // when enabled authorization items cannot be assigned children of the same type.
'class'=>'common.modules.auth.AuthModule', // add this line.. and change AuthModule according to the auth module class name
'userClass' => 'User', // the name of the user model class.
'userIdColumn' => 'id', // the name of the user id column.
'userNameColumn' => 'username', // the name of the user name column.
'appLayout' => 'application.views.layouts.main', // the layout used by the module.
),
Hope this will work..
I'm trying to implement a multiple file upload using CMultiFileUpload with CUploadedFile, but it doesn't work. Specifically, _POST is not working even considering that I'm using 'enctype' => 'multipart/form-data' in the options in the view:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'examen-form',
'enableAjaxValidation'=>false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
and this is the widget and parameters used for CMultiFileUpload:
<div class="row">
<?php echo $form->labelEx($model,'archivo_foto')?>
<?php //echo CHtml::activeFileField($model,'archivo_foto')?>
<?php $this->widget('CMultiFileUpload', array(
'model' => $model,
'name' => 'archivo_foto',
'accept' => 'jpeg|jpg|gif|png|txt', // useful for verifying files
'duplicate' => 'Duplicate file!', // useful, i think
'denied' => 'Invalid file type', // useful, i think
'max' => 10,
'htmlOptions' => array( 'multiple' => 'multiple', 'size' => 25 ),
)); ?>
<?php echo $form->error($model,'archivo_foto')?>
</div>
On the other hand, the controller action is implemented this way:
public function actionUpdateam($id)
{
$model=$this->loadModel($id);
$dir=Yii::getPathOfAlias('application.uploads');
$model->archivo_documento='funciona 0';
if(isset($_POST['Examen'])) {
$model->attributes=$_POST['Examen'];
// THIS is how you capture those uploaded images: remember that in your CMultiFile widget, you set 'name' => 'archivo_foto'
$images = CUploadedFile::getInstancesByName('archivo_foto');
// proceed if the images have been set
$model->archivo_documento='funciona uno';
if (isset($images) && count($images) > 0) {
$model->archivo_documento='funciona dos';
// go through each uploaded image
foreach ($images as $image) {
echo $image->name.'<br />';
$image->saveAs($dir.'/'.$image->name);
$model->archivo_foto = $model->archivo_foto."+".$image->name;
}
// save the rest of your information from the form
if ($model->save()) {
$this->redirect(array('view','id'=>$model->id));
}
}
}
$this->render('update_am',array(
'model'=>$model,
));
}
And at last, I think that is important to mention the rule used for the model (it might be the cause of the problem as well):
array('archivo_foto','file','allowEmpty'=>true,'maxFiles'=>10),
I think that the problem is in post method, because the controller is not uploading the files and is not making any changes in the database. But I'm not sure.
Try changing to 'htmlOptions'=>array('multiple'=>true).
Add following code in the Form
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
),
Like
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>true,
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
),
)); ?>
I am using the same extension and it is wokring for me with these codes
In the view file
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'adpost-form',
'enableClientValidation'=>true,
'clientOptions' => array(
'validateOnSubmit'=>true,
'validateOnChange'=>false,
'afterValidate'=>'js:submiAjaxForm'
),
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
<?php
$this->widget('CMultiFileUpload', array(
'name' => 'photo_name',
'accept' => 'jpeg|jpg|gif|png',
'duplicate' => 'File is not existed!',
'denied' => 'Not images', // useful,
'htmlOptions' => array(
'style' =>'color: transparent;',
),
));
?>
And in the contoller
$images = CUploadedFile::getInstancesByName('photo_name');
foreach ($images as $image => $pic) {
//----------------- Renaming image before uploading
$extension = $pic->getExtensionName();
$newName = "image_".$adModel->id;
$newName .= "_".$imgCount.".".$extension;
$imgCount++;
if ($pic->saveAs($newPath.$newName)) {
// add it to the main model now
$img_add = new AdsPhotosTbl;
$img_add->photo_name = $newName;
$img_add->ad_id = $adModel->id;
$img_add->status = 1;
if(!$img_add->save()){
$error = true;
$upload_error = true;
break;
}
}else{
$upload_error = true;
$error = true;
break;
}
}