I am trying to make my way through an inherited Yii Framework site. Very little Object Oriented knowledge previously.
I'm printing some user information to see what is there like this...
print_r(Yii::app()->user);
And that's printing out this...
CWebUser Object (
[allowAutoLogin] => 1
[guestName] => Guest
[loginUrl] => Array
(
[0] => /site/login
)
[identityCookie] =>
[authTimeout] => 7200
[autoRenewCookie] =>
[autoUpdateFlash] => 1
[loginRequiredAjaxResponse] =>
[_keyPrefix:CWebUser:private] => 7c6285462394c9a141b5d66dce54e8f2
[_access:CWebUser:private] => Array
(
[Admin] =>
[Judge] =>
[Student] => 1
)
[behaviors] => Array
(
)
[_initialized:CApplicationComponent:private] => 1
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)
I'm trying to get out the information that this user is a Student. I see it! It's ]there!
[Student] => 1
But how would I get that information out?
UPDATE:
Here's the parts of CWebUser that appear to have something to do with _access
private $_access=array();
public function checkAccess($operation,$params=array(),$allowCaching=true)
{
if($allowCaching && $params===array() && isset($this->_access[$operation]))
return $this->_access[$operation];
$access=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
if($allowCaching && $params===array())
$this->_access[$operation]=$access;
return $access;
}
The following should tell you whether the user has 'Student' access:
$isStudent = Yii::app()->user->checkAccess('Student') == 1;
'student' is part of the $_access array. But $_access is private so you can not access it directly.
But there must be a method (function) to get it!
look in the CWebUser class there should be a method like
getStudent();
isStudent();
or may be
$access = getAccess();
$access['student'];
Edit:
checkAccess
seems to be used someting like this checkAccess('student');
Related
I have seen many questions on StackOverflow and I have this code
use Zend\Session\Container;
class IndexController extends AbstractActionController {
public function indexAction() {
$userSession = new Container('user');
$userSession->username = 'Sandhya';
return new ViewModel();
}
}
When I am printing the $userSession container in the controller it is giving me this output
Zend\Session\Container Object (
[name:protected] => user
[manager:protected] => Zend\Session\SessionManager Object (
[defaultDestroyOptions:protected] => Array (
[send_expire_cookie] => 1
[clear_storage] =>
)
[name:protected] =>
[validatorChain:protected] =>
[config:protected] => Zend\Session\Config\SessionConfig Object (
[phpErrorCode:protected] =>
[phpErrorMessage:protected] =>
[rememberMeSeconds:protected] => 240
[serializeHandler:protected] =>
[validCacheLimiters:protected] => Array (
[0] => nocache
[1] => public
[2] => private
[3] => private_no_expire
)
[validHashBitsPerCharacters:protected] => Array (
[0] => 4
[1] => 5
[2] => 6
)
[validHashFunctions:protected] =>
[name:protected] =>
[savePath:protected] =>
[cookieLifetime:protected] => 2592000
[cookiePath:protected] =>
[cookieDomain:protected] =>
[cookieSecure:protected] =>
[cookieHttpOnly:protected] => 1
[useCookies:protected] => 1
[options:protected] => Array (
[gc_maxlifetime] => 2592000
)
)
[defaultConfigClass:protected] => Zend\Session\Config\SessionConfig
[storage:protected] => Zend\Session\Storage\SessionArrayStorage Object (
)
[defaultStorageClass:protected] => Zend\Session\Storage\SessionArrayStorage
[saveHandler:protected] =>
)
[storage:protected] => Array ( )
[flag:protected] => 2
[iteratorClass:protected] => ArrayIterator
[protectedProperties:protected] => Array (
[0] => name
[1] => manager
[2] => storage
[3] => flag
[4] => iteratorClass
[5] => protectedProperties
)
)
It means there is nothing like username...
But when I am printing the S_SESSION it gives me this output...
Array (
[__ZF] => Array (
[_REQUEST_ACCESS_TIME] => 1429081041.81
)
[user] => Zend\Stdlib\ArrayObject Object (
[storage:protected] => Array (
[username] => Sandhya
)
[flag:protected] => 2
[iteratorClass:protected] => ArrayIterator
[protectedProperties:protected] => Array (
[0] => storage
[1] => flag
[2] => iteratorClass
[3] => protectedProperties
)
)
)
There is a field username...
But when I am trying to get the $_SESSION in view it gives me the same output as above..
The problem is I am not able to get the username in both the container as well as in $_SESSION.
I need it in the controllers.
what can be the problem need help? Thank you.
I think you have to work on your configuration.
You have to setup a common SessionManager to manage handling of your session information.
Something like this:
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions($config);
$sessionManager = new SessionManager($sessionConfig);
$sessionManager->start();
Container::setDefaultManager($sessionManager);
I would suggest registering your SessionManager config in your ServiceManager instance and then use it throughout the application.
'service_manager' => array(
'factories' => array(
'session_manager' => 'My\Factory\SessionManagerFactory'
)
)
You can then get your SessionManager in any controller:
$sessionManager = $this->serviceLocator->get('session_manager');
And if you create a new Container it will use your common/default SessionManager instance automatically so all will be managed in one place.
$userSession = new Container('user');
$userSession->getManager() === $this->serviceLocator->get('session_manager') // true
On how to register your session_manager I will refer to the official ZF2 documentation.
You can use the following code:
$userSession = new Container('user');
//To check the session variable in zf2:
if($userSession->offsetExists('username')){
//Your logic after check condition
}
This will return true or false on the basis of session exist or not.
//To get the value of session:
echo $user->offsetGet('username');
Above code will return the value of session index username.
Instead of $userSession->username = 'Sandhya'; you can use below code:
$user->offsetSet('username','Sandhya');
This is zf2 standard, which is used by session container in zf2.
you can just get your username from session in controllers.
$userSession = new Container('user');
$username = $userSession->username ;
var_dump($username); //Sandhya
it work for me . try it !
I am trying to access the following and need to get the value of [vid] array cell.
FieldCollectionItemEntity Object
(
[fieldInfo:protected] =>
[hostEntity:protected] => stdClass Object
(
**[vid]** => 119
[uid] => 1
[title] => My Page Name
[log] =>
[status] => 1
[comment] => 1
[promote] => 0
[sticky] => 0
[vuuid] => 3304d1cf-e3cf-4c5a-884a-4abb565ddced
[nid] => 119
[type] => subpage
[language] => und
[created] => 1408621327
[changed] => 1408640191
[tnid] => 0
[translate] => 0
[uuid] => 39145013-6637-4062-96e7-1b4589609c4f
[revision_timestamp] => 1408640191
I tried the following, but I guess I don't have a clue from here:-
$mything = new myClass;
print $mything->accessObjectArray();
class myClass {
protected $var;
function accessObjectArray(){
return $this-> $var;
}
//other member functions
}
Update
I actually only have access to the variable $content which has the following multi-dimensional arrays. All I want is to get the array cell's value of [vid].
To do that, I could print $content["field_image_title"]["#object"] but after that it's protected. That's where I am wondering that how can I access this array. I unfortunately do not have access FieldCollectionItemEntity to include in my page.
On doing this:- I get the following output:-
print_r($content);
Array
(
[field_image_title] => Array
(
[#theme] => field
[#weight] => 0
[#title] => Image Title
[#access] => 1
[#label_display] => hidden
[#view_mode] => full
[#language] => und
[#field_name] => field_image_title
[#field_type] => text
[#field_translatable] => 0
[#entity_type] => field_collection_item
[#bundle] => field_image_collection
[#object] => FieldCollectionItemEntity Object
(
[fieldInfo:protected] =>
[hostEntity:protected] => stdClass Object
(
[vid] => 119
[uid] => 1
[title] => My Page Name
[log] =>
[status] => 1
[comment] => 1
[promote] => 0
[sticky] => 0
[vuuid] => 3304d1cf-e3cf-4c5a-884a-4abb565ddced
[nid] => 119
[type] => subpage
[language] => und
[created] => 1408621327
[changed] => 1408640191
[tnid] => 0
[translate] => 0
[uuid] => 39145013-6637-4062-96e7-1b4589609c4f
[revision_timestamp] => 1408640191
[revision_uid] => 1
"$this-> $var;" this mean variable variable, and this throw php notice undefined variable $var,
you have to use
return $this->var;
or
return $this->vid
what your are doing with this:
return $this-> $var;
is accessing a property named after what is contained in your $var variable which does not contain anything in the scope where it is defined. pass it as a function argument:
function accessObjectArray($var){
return $this-> $var;
}
print $mything->accessObjectArray('vid');
but in any event, that won't work either since (as mentioned by #MikeBrant) you have an object in your parent object properties. something like this might work better
$o = new FieldCollectionItemEntity() // assumes this will construct the object in the state you have posted it
$o->accessObjectArray('hostEntity')->accessObjectArray('vid');
note that the method accessObjectArray($var) must be defined in both objects for this to work
the idea of a protected property is to prevent what you want to actually happen. But! protected means that only the class and it's extending classes can access a value. Make your own class that extends the other one:
class myClass extends FieldCollectionItemEntity {
function accessParentProtectedVars($var){
return $this->hostEntity->$var;
}
//other member functions
}
then your accessObjectArray() function will be able to acces the protected property. note that it's hardcoded to access the hostEntity object.
but seriously, you may want to consult the creator of the other class and maybe you will devise a way to best manage this. My proposed solution is not that much of a good practice if I daresay.
Answer for Drupal members as rendered array in the question looks like Drupal array
I believe you don't need a new class at all, you only need to get node's objects. So, below one line will work for you.
$parent_node = menu_get_object();
Now, you can access by $parent_node->vid
i want to make if clause for button. If admin is logged in it will shown otherwise not.
if($this->Session->User['role'] == 'admin') {
echo
'<li> <ul class="pull-right">Admin skiltis</ul></li>';
}
I can't get that role from session and compare if it admin or not..
Using $_SESSION['Auth']['User'] directly is a bad practice, as depending how the AuthComponent is configured, it may not be available.
You should better pass the authenticated user from the controller to the views and then only check his properties:
AppController:
$authenticated_user = $this->Auth->user();
if(isset($authenticated_user))
{
$this->set(compact('authenticated_user'));
}
Views:
if(isset($authenticated_user) && $authenticated_user['role'] == 'admin'){
...
}
By the way you should also use the HtmlHelper in your views to generate links instead of printing <a> tags manually with hardcoded urls to benefit from many Cake features.
Try to make a little debug on your code.
First check if your session was started.
You can do this by executing the command "session_status()" if the result is "PHP_SESSION_NONE" your session isnt started. You can fix it by putting a "session_start()" before any print was made by your page.
If value of print_r($_SESSION); is something like,
Array ( [Config] => Array ( [userAgent] => 4df452d8263aa05ef9324f37499322b0 [time] => 1401090120 [countdown] => 10 ) [Message] => Array ( ) [Auth] => Array ( [User] => Array ( [id] => 8 [username] => aaaaa [email] => aaa#gmail.com [role] => admin [created] => 2014-05-26 02:43:20 [modified] => 2014-05-26 02:43:20 [status] => 1 ) ) )
Thae try this code, I think it will work,
if($_SESSION['Auth']['User']['role'] == 'admin') {
echo
'<li> <ul class="pull-right">Admin skiltis</ul></li>';
}
Calling "get_entry" on the REST webservice returns an empty result in this manner:
Array
(
[entry_list] => Array
(
[0] => stdClass Object
(
[id] => 85a67fbe-ab86-597a-6bca-4f0305719543
[module_name] => Contacts
[name_value_list] => Array
(
)
)
)
[relationship_list] => Array
(
)
)
My call looks like:
$method = 'get_entry';
$params = array(
'module_name' => 'Contacts',
'id' => $sugarbean_id,
);
But I have absolutely no clue why i get an "empty" object as a result.
Can anyone help me or give me some pointers?
Thanks
Jeroen
You need to provide a session id for the get_entry call. You get the session id when calling the login method. See the get_entry documentation for more information.
Found it. It turns out that I had to explicitly specify select_fields.
I have a function that builds a collection of user objects from the database:
public static function GetUsersByGroup($instanceID, $groupID)
{
$col = null;
if($groupID != null)
{
$col = UserGroup::GetCollection("User" ,_DB_GET_ALL_INSTANCE_USERGROUP_MEMBERS,array ($instanceID, $groupID));
}
else
{
$col = UserGroup::GetCollection("User" ,_DB_GET_ALL_INSTANCE_NOGROUP_MEMBERS,$instanceID);
}
echo "this is the collection I am going to return: <pre>";
print_r($col);
echo "</pre>";
return $col;
}
The method has some debug output at the bottom, but the point is if I call that method with a null groupid param i.e it runs the second condition, it prints out a nice indication of the collection that I expected to receive, which is great.
However ..
Here is my calling method:
echo "<br> Collection passed through is: </br>";
$collection = UserGroup::GetUsersByGroup($this->GetInstance()->id,$grouplist->GetCurrentCommandParam());
print_r($collection);
$userlist->UpdateCollection($collection);
$userlist->DeSelect();
The intresting thing is the output:
this is the collection I am going to return:
Collection Object
(
[_valueType:protected] => User
[_isBasicType:protected] =>
[_validateFunc:protected] =>
[_collection:protected] => Array
(
[0] => User Object
(
[valid] =>
[validationMessage] =>
[id] => 29
[table:private] => user
[fields:private] => Array
(
[title] => mrs
[fname] => Kirsty
[lname] => Howden
[email] => kirsty2#softyolk.com
[password] => xxxxxxxx
[lastlogin] => 2009-07-05 15:20:13
[instanceID] => 2
[deliveryAddress] =>
[invoiceAddress] =>
[tel] => 01752848484
[isAdmin] => 0
[disabled] => 0
[mustAuthorise] =>
[usergroupID] =>
)
[validationRules:private] => Array
(
)
[_profileStartTime:protected] =>
[_profileTag:protected] =>
)
[1] => User Object
(
[valid] =>
[validationMessage] =>
[id] => 31
[table:private] => user
[fields:private] => Array
(
[title] => master
[fname] => Seb
[lname] => Howden
[email] => seb#antithug.co.uk
[password] => xxxxxxxxx
[lastlogin] => 2009-07-09 02:02:24
[instanceID] => 2
[deliveryAddress] => saltash
[invoiceAddress] => saltash
[tel] => 8908908
[isAdmin] => 0
[disabled] => 0
[mustAuthorise] =>
[usergroupID] =>
)
[validationRules:private] => Array
(
)
[_profileStartTime:protected] =>
[_profileTag:protected] =>
)
)
)
Collection passed through is:
this is the collection I am going to return:
Collection Object
(
[_valueType:protected] => User
[_isBasicType:protected] =>
[_validateFunc:protected] =>
[_collection:protected] => Array
(
)
)
Collection Object ( [_valueType:protected] => User [_isBasicType:protected] => [_validateFunc:protected] => [_collection:protected] => Array ( ) )
The object returned has been modified??
If the GetUsersByGroup method is called with a userGroupID i.e the first case, then output is all as expected.
If i remove the conditional from the method and simply return $col = UserGroup::GetCollection("User" ,_DB_GET_ALL_INSTANCE_NOGROUP_MEMBERS,$instanceID); then all output is as expected.
It seems that the else condition executes correctly, and then is corrupted on return, but this only happens if the else condition is present, remove the else condition, and simply return the result of the method call in the else condition, and all is as expected.
Any idea please?
Thanks
ADDED THE UserGroup::GetCollection Method (this is a deep rabbit hole though, could go on)
protected static function GetCollection($class, $sqlID, $params = null)
{
$dal = DAL::GetInstance(); //not to be confused with the Instance object, this is an instance of DAL
$collection = new Collection($class);
$items = $dal->QueryForAssoc($sqlID,$params);
foreach($items as $item)
{
$itemObject = new $class();
$itemObject->LoadFromList($item);
$collection->add($itemObject);
}
return $collection;
}
To further clarify the follwing works fine ::
public static function GetUsersByGroup($instanceID, $groupID)
{
$col = null;
//if($groupID != null)
//{
//$col = UserGroup::GetCollection("User" ,_DB_GET_ALL_INSTANCE_USREGROUP_MEMBERS,array ($instanceID, $groupID));
//}
//else
//{
$col = UserGroup::GetCollection("User" ,_DB_GET_ALL_INSTANCE_NOGROUP_MEMBERS,$instanceID);
// }
return $col;
}
I only see the issue if the line is in the else block.
The likely problem here lies in your UserGroup::GetCollection function. PHP 5 passes all objects by reference, so if you are doing any sort of modification in this routine based on the way you are retrieving these objects, then this modification will persist after UserGroup::GetCollection has finished.
I would examine carefully the differences between these two function calls and make sure there are no object changes happening in UserGroup::GetCollection.
$col = UserGroup::GetCollection("User" ,_DB_GET_ALL_INSTANCE_USERGROUP_MEMBERS,array ($instanceID, $groupID));
vs.
$col = UserGroup::GetCollection("User" ,_DB_GET_ALL_INSTANCE_NOGROUP_MEMBERS,$instanceID);
Turns out the method is being called twice, the second call is using the other condition, and returning a blank collection (the problem result).
By setting an echo in each condition I could see as they are called, and first the null case is called and then the non null.
The actual error is that I had a stateful list calling the method twice in the same postback. Hard to catch.
Thanks for looking