Custom session variables in Drupal 7 - php

I'm trying to make a custom form in Drupal. This form call a web service and will receive some Json. in this Json response, I have three information (or an error) :
1. User name
2. User language
3. User custom Token (special for another webapp)
Those three info must be placed in session (or anything else) and will be shown in some webpages.
In example, on every page, It will be written "Hello Mr John", and on some web pages I want to show a icon + link with the custom Token to access to another web application, ...
We already have a lots of users, and we don't want to have all the users in the drupal DB.
How can I Do? I'm using Drupal 7
Thanks in advance

I wrote this function to deal with session in Drupal
function _mySite_session($key, $value = NULL)
{
static $storage;
if ($value)
{
$storage[$key] = $value ;
$_SESSION['mykey'][$key] = $value ; // I use 'mykey' as a session key because in case some other module uses 'type' in $_SESSION. So try to make it unique.
}
elseif (empty($storage[$key]) && isset($_SESSION['mykey'][$key]))
{
$storage[$key] = $_SESSION['mykey'][$key];
}
return $storage[$key];
}
To set a session variable:
_mySite_session("USERNAME", "Mr. John");
And to retrieve the value of the session variable:
$username = _mySite_session("USERNAME");

Related

Pref-fill fields on Gravity Forms

I would like to pre-fill a registration form for 2021 school year using last year's info and send out invitations to all parents.
The form all "Allow prefill" turned on for all needed fields. The prefill field name the the 'pf'&the admin name.
I tried sending myself an email with a URL containing the prefill fields=last year's data.
The obvious problem is security since the link contains personal information. So that won't work.
Next I wrote a php function (I initially put the data into an array during development) that will read a csv file on my server that contains the personal information.
I installed it into Gravity forms as a plug-in. Unfortunately, I am not familiar enough with php functions so I was unable to filter out extraneous calls to the function. It needs to run only for a specific form ID. In addition, I could not understand the part in the Gravity forms documentation regarding the sub function, so it ran every time I clicked on the web site and bombed the site.
My plan was to send an email with an account number and password, and once logged in, the function will run and prefill the fields for that one customer.
I would appreciate help either with this function, or a better way to prefill the fields.
Thanks for your help.
Here's the code:
<?php
// for testing
$account = 'B-613048';
$data_array = Array(
Array("pfAccountNumber","B-613001","B-613002","B-613003","B-613004","B-613005","B-613006","B-613007","B-613008","B-613009","B-613010","B-613011","B-613012","B-613013","B-613014","B-613015","B-613016","B-613017","B-613018","B-613019","B-613020","B-613021","B-613022","B-613023","B-613024","B-613025","B-613026","B-613027","B-613028","B-613029","B-613030","B-613031","B-613032","B-613033","B-613034","B-613035","B-613036","B-613037","B-613038","B-613039","B-613040","B-613041","B-613042","B-613043","B-613044","B-613045","B-613046","B-613047","B-613048","B-613049","B-613050","B-613051","B-613052","B-613053","B-613054","B-613055","B-613056","B-613057","B-613058","B-613059","B-613060","B-613061","B-613062","B-613063","B-613064","B-613065","B-613066","B-613067","B-613068","B-613069","B-613070","B-613071","B-613072","B-613073","B-613074","B-613075","B-613076","B-613077","B-613078","B-613079","B-613080"),
Array("pfLastYear","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes","Yes"),
Array("pfPG1Prefix","Mrs.","Ms.","Mrs.","","Mr.","Ms.","Ms.","Mr.","Ms.","Mrs.","Ms.","Mrs.","Mrs.","Ms.","Mrs.","Mrs.","Mrs.","Mrs.","Ms.","Mrs.","Mrs.","Ms.","Mrs.","Mr.","Mrs.","Mrs.","Mrs.","Ms.","Mrs.","Mrs.","Mrs.","","Mrs.","Mrs.","Mrs.","Mrs.","Mrs.","Mrs.","Mrs.","","Mrs.","Mrs.","","Ms.","Mrs.","Mrs.","Ms.","Mr.","Mrs.","Mr.","Mrs.","Ms.","Mr.","Mr.","Mr.","Ms.","Ms.","Dr.","Mrs.","Mrs.","Mr.","Mrs.","Mrs.","Mrs.","","","","","","","","","","","","","","","","")
);
$num_rows=count($data_array,0);
$num_cols=(count($data_array,1)-$num_rows)/$num_rows;
echo "num_rows= ".$num_rows."</br>";
echo "num_cols= ".$num_cols."</br>";
for ($f = 0; $f < $num_cols;$f++){$fields[$f] = $data_array[0][$f];}
for($c = 0; $c < $num_cols; $c++) {
if($account == $data_array[0][$c]){
for ($r = 0; $r < $num_rows;$r++){
$account_data[$r] = $data_array[$r][$c];
$filter = 'gform_field_value_'.$fields[$r];
add_filter( $filter, 'populate_function' );
function populate_function() {
return $account_data[$r];
};
}
break;
};
}
?>
<?php
function populate_function($g) {
echo "g= ".$g;
return $account_data[$g];
};
?>
I would suggest using the gravity_form function which allows you to pass an array of dynamic population parameter keys with their corresponding values to be populated.
Furthermore, if you did not want to require a login prior to accessing the form you could assign a unique ID to each user which would be defined as a URL parameter to identify and retrieve the required field data.
For example:
www.school.com/signup/?user=unique_complex_user_identier
Hits a template with a gravity form
URL parameter read and decoded to identify corresponding user, else fail.
User data passed into form

How to access ASP classic session variable from PHP?

I have a login protected back office website written in ASP classic running on Windows. Login status is stored in a session variable. I also have a PHP page that should be accessible only to logged in users. How do I check in PHP that the client is logged in to this website?
P.S. There may be multiple users accessing the page at the same time.
By assuming both PHP and ASP applications share the same domain name, here's a step by step guide.
1 - Create an asp file named sessionConnector.asp.
2 - In sessionConnector.asp, serialize the Session.Contents object into a format that PHP can deserialize, JSON for example. You can use JSON.asp from aspjson.
<%#Language=VBScript CodePage=65001%>
<!--#include file="JSON.asp"-->
<%
Set JSONObject = jsObject()
For Each Key In Session.Contents
If Not IsObject(Session.Contents(Key)) Then 'skip the objects cannot be serialized
JSONObject(Key) = Session.Contents(Key)
End If
Next
JSONObject.Flush
%>
3 - Create a PHP function named GetASPSessionState().
4 - In GetASPSessionState(), make an HTTP request for sessionConnector.asp by specifying the Cookie header filled with $_SERVER["HTTP_COOKIE"] which must contains identifier of the ASP Session, so ASP can identify the user and the response will vary by user.
5 - After fetching the response (string of JSON), deserialize by using json_decode and look for the ASP session variable.
function GetASPSessionState(){
if(stripos($_SERVER["HTTP_COOKIE"], "ASPSESSIONID") === false){
# since ASP sessions stored in memory
# don't make request to get ASP session state if the cookie does not contain ASPSESSIONID
# otherwise IIS will create new redundant sessions for each of your checks so it wouldn't be a memory-friendly way
# returning an empty array
return array();
} else {
$options = array('http' =>
array('method'=>"GET", 'header' => "Cookie: " . $_SERVER["HTTP_COOKIE"])
);
$cx = stream_context_create($options);
$response = file_get_contents("http://mywebsite.com/sessionConnector.asp", false, $cx);
return json_decode($response, JSON_FORCE_OBJECT);
}
}
$aspSessionState = GetASPSessionState();
if($aspSessionState["IsLoggedIn"] == true){
//user previously logged in with the ASP
}
My solution was to auto-submit a webform which works both ways regardless of whether PHP to ASP or ASP to PHP.
On the leading page simply add an OnLoad to the body tag like so:
<body onload="document.xxx.submit()">
Where "xxx" is the is the ID of your form that contains the hidden fields that you want to pass. For example:
<form id="xxx" action="example.asp" method="post">
This will work locally and across domains.

How to store a permanent boolean flag?

I have created a web app that has 2 control panels. One for the admin and one for the users. I want the users to be able to perform one specific action from their panel only if the admin sets this action "on" (from his panel) and not being able when he sets it "off".
My app also uses a MySql database.
How can I implement it? Is an extra table with only one field a viable solution? Can I do it by reading a file (maybe JSON)?
EDIT: I want the admin to be able to toggle the "on/off" status with a click of a button, so constants are not a solution.
A database query could be used every time the action is used but if it is more general and you are going to be using this a lot, I would look into PHP constants. You could set it in a configuration file like:
Config.php
define('USER_CAN_MODIFY', true);
Other.php
if ((defined('USER_CAN_MODIFY') and USER_CAN_MODIFY === true) { }
Constants have a global scope and cannot be changed once set.
Since you want to store a single value you don't need to use DB. You may simply store this flag in a file as serialized value.
Below is simplified example.
define('PERM_FLAG_FILE', 'perm_flag.dat');
$PERM_FLAG = false;
function loadFlag() {
global $PERM_FLAG;
return file_exists(PERM_FLAG_FILE)? unserialize(file_get_contents($PERM_FLAG)) : false;
}
function saveFlag() {
global $PERM_FLAG;
file_put_contents(PERM_FLAG_FILE, serialize($PERM_FLAG));
}
function setFlag($v) {
global $PERM_FLAG;
$PERM_FLAG = (bool)$v;
}

User logs into frontend - plugin to automatically be logged into backend

I need to create a system plugin (no auth plugin!) where a user which logges into the frontend automaticaly gets logged in the backend too.
(The user has the rights to log into the backend via /administrator.)
I try to do it via the very basic code you see below, the result is positive, but if i go to the backend the user still needs to log in.
In the session table the backend session row is set, but the "guest" field is set to 1 instead of 0 and the userid is set to 0 instead of the correct id.
How can this be done?
function onAfterInitialise() {
if(JFactory::getUser()->get('id')) { // logged in?
$credentials = array();
$credentials['username'] = "walter"; // hardcoded first
$credentials['password'] = "123"; // hardcoded first
$options = array();
$options['action'] = 'core.login.admin';
$result = $app->login($credentials, $options); // this seams to work
if (!($result instanceof Exception)) {
$app->redirect("www.bummer.de");
}
}
Apart from this being a very bad idea, as mentioned in this question Joomla! is implemented as two applications a front-end (/index.php) and back-end application (/administrator/index.php).
In the code provided you don't show where $app is initialised so I'm guessing that it's probably something like $app->JFactory::getApplication('site');.
To login to the admin app you need to get it rather than the front-end client app e.g.
$adminApp->JFactory::getApplication('administrator');
$result = $adminApp->login($credentials, $options);
n.b. this is untested code just typed in to stack overflow... it should be right.

PHP -> SOAP -> Magento Webservice: get Cookies set by Magento

I am new to Magento Web-Service and have to expand it.
The Webservice shell be able to login an customer, give me the session cookie back so that I can redirect to a file that sets the cookie again, redirects me and I can see my cart and proceed to checkout on the Magento Store.
The Problem:
Magento creates a cookie (that contains the session id or whatever, ive tried to set this cookie manual and them im logged in) instead of setting a session when the customer logs in.
I've tried now for several hours to get this cookie that is set by magento in my magento web-service. It seems the cookie isn't set when i call
$session = Mage::getSingleton('customer/session');
return $session->getCookie()->get('frontend');
Heres my complete Code:
Magento Webservice Api:
<?php
class Customapi_Model_Core_Api
{
public function __construct()
{
}
public function checkout($user, $cart)
{
$ret['cookie'] = $this->login($user);
//$coreCookie = Mage::getSingleton('core/cookie');
//$ret['cookie'] = $_COOKIE['frontend'];
return $ret;
}
function login($user)
{
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('customer/session');
try
{
$session->loginById($user['id']);
}
catch (Exception $e)
{
}
return $session->getCookie()->get('frontend');
}
}
?>
Heres my Api Call in Php:
<?php
$teambook_path = 'http://localhost/magento/';
$soap = new SoapClient('http://localhost/magento/api/?wsdl');
$soap->startSession();
$sessionId = $soap->login('ApiUser', 'ApiKey');
$userSession = $soap->call(
$sessionId,
'customapi.checkout',
array(
array(
'id' => 1,
'username' => 'Ruf_Michael#gmx.de',
'password' => '***'
),
array(
)
)
);
echo '<pre>';
var_dump($userSession)."\n";
if(isset($userSession['sid']))
echo ''.$userSession['sid'].''."\n";
echo '</pre>';
$soap->endSession($sessionId);
?>
Thanks for every help!
MRu
Sorry i am writing an answer but the comment box denied me to write more than ... letters.
I've tried both codes you posted and all I get is an empty Array or Bool false.
I wrote a static function:
private static $cookie = array();
public static function cookie($key, $value)
{
if($key == 'frontend') {
self::$cookie['key'] = $key;
self::$cookie['value'] = $value;
}
}
that is called in Mage_Core_Model_Session_Abstract_Varien::start and I got the frontend cookie value:
Customapi_Model_Core_Api::cookie($sessionName, $this->getSessionId());
in line 125.
But that didnt solve my basic Problem:
The Session created in the Api call can't be restored, although it is set to the correct value.
Thanks for your help!
You can get an array of all your cookies with the following command:
Mage::getModel('core/cookie')->get();
The frontend cookie can be retrieved like this:
Mage::getModel('core/cookie')->get('frontend');
From your commented code I can see that you already knew that.
As far as I know, when you log in a user, Magento doesn't just create a new session id, it uses the session id of the active connection (which is generated by PHP itself). You are logging in the user and associating him to the session that your API client just created with Magento. Thus, the code that you have commented seems to be correct for what you are trying to achieve.
Now you should just need to get the returned session id and use it in your new request as the 'frontend' cookie.
Edit (a second time)
Magento has different sessions inside a single PHP session which it uses for different scopes. For instance, there is the core scope, the customer scope, etc. However, the customer scope is also specific to a given website. So, you can have a customer_website_one and a customer_website_two scope.
If you want to log in your user, you have to tell Magento in which website that is. Take the following code as an example
// This code goes inside your Magento API class method
// These two lines get your website code for the website with id 1
// You can obviously simply hardcode the $code variable if you prefer
// It must obviously be the website code to which your users will be redirected in the end
$webSites = Mage::app()->getWebsites();
$code = $webSites[1]->getCode();
$session = Mage::getSingleton("customer/session"); // This initiates the PHP session
// The following line is the trick here. You simulate that you
// entered Magento through a website (instead of the API) so if you log in your user
// his info will be stored in the customer_your_website scope
$session->init('customer_' . $code);
$session->loginById(4); // Just logging in some example user
return session_id(); // this holds your session id
If I understand you correctly, you now want to let the user open a PHP script in your server that sets the Magento Cookie to what you just returned in your API method. I wrote the following example which you would access like this: example.com/set_cookie.php?session=THE_RETURNED_SESSION_ID
<?php
// Make sure you match the cookie path magento is setting
setcookie('frontend', $_GET['session'], 0, '/your/magento/cookie/path');
header('Location: http://example.com');
?>
That should do it. Your user is now logged in (at least I got it to work in my test environment). One thing you should keep in mind is that Magento has a Session Validation Mechanism which will fail if enabled. That's because your session stores info about which browser you are using, the IP from which you are connecting, etc. These data will not match between calls through the API methods and the browser later. Here is an example output of the command print_r($session->getData()) after setting the session in the API method
[_session_validator_data] => Array
(
[remote_addr] => 172.20.1.1
[http_via] =>
[http_x_forwarded_for] =>
[http_user_agent] => PHP-SOAP/5.3.5
)
Make sure you turn of the validation in the Magento Admin in Settings > Configuration > General > Web > Session Validation Settings

Categories