Drupal 7 hook_node_access to conditionally block node access - drupal

For all users I need to conditionally block access to nodes of type 'message'. The only way users should be able to view these message nodes is by successfully submitting a form.
I've started like this:
function mymodule_node_access($node, $op, $account) {
if ($op == 'view' && $node->type == 'message') {
return NODE_ACCESS_DENY;
}
}
However, I want to allow view access to individual nodes of this type upon successful submission of form:
function form_submit($form, &$form_state) {
// some logic here
$form_state['redirect'] = 'node/255';
}
so node 255 is of type 'message', and I want to 'lift' the NODE_ACCESS_DENY for this particular node and this user (+ in most cases this will be an anonymous user)
Any suggestions on different ways to accomplish this?

The only way you can do that is to set a value in the form submission handler that is then checked by hook_node_access(); you could use a Drupal variable, or a value saved in a database table.
You need to store the user ID of the user that accessed the form, and the node ID of every node for which such form has been submitted.
Supposing you use a Drupal variable, you could use code similar to the following one:
function mymodule_form_submit($form, &$form_state) {
global $user;
$message_nid = 255;
$values = variable_get('access_nid', array());
if (isset($values[$user->uid])) {
if (!isset($values[$user->uid][$message_nid])) {
$values[$user->uid][$message_nid] = $message_nid;
}
}
else {
$values[$user->uid] = array($message_nid => $message_nid);
}
variable_set('access_nid', $values);
$form_state['redirect'] = 'node/' . $message_nid;
}
function mymodule_node_access($node, $op, $account) {
$result = NODE_ACCESS_IGNORE;
if ($op == 'view' && $node->type == 'message') {
$values = variable_get('access_nid', array());
if (!empty($values[$account->uid]) {
if (isset($values[$account->uid][$node->nid])) {
unset($values[$account->uid][$node->nid]);
$result = NODE_ACCESS_ALLOW;
}
else {
$result = NODE_ACCESS_DENY;
}
}
else {
$result = NODE_ACCESS_DENY;
}
}
variable_set('access_nid', $values);
return $result;
}
To notice that this code allows a user to access a node only once; if the user would try to access the same node the second time, the user would get an "access denied" error. If that is not desired, then the second function should be re-written as follows:
function mymodule_node_access($node, $op, $account) {
if ($op == 'view' && $node->type == 'message') {
$values = variable_get('access_nid', array());
if (!empty($values[$account->uid]) {
if (isset($values[$account->uid][$node->nid])) {
return NODE_ACCESS_ALLOW;
}
return NODE_ACCESS_DENY;
}
}
else {
$result = NODE_ACCESS_DENY;
}
}
return NODE_ACCESS_IGNORE;
}
I used a Drupal variable to write simple code; using a Drupal variable, in this case, should be done if the users that can create nodes of that content type are few; if there are many users who can create those nodes, then using a database table is better.
Also when using Drupal variables, Drupal is using a database table; the difference is that the content of that database table is always loaded in memory. If you need to store many data, you should not use Drupal variables.

Modified solution to use $_SESSION as I'm working mostly with anonymous users:
function mymodule_form_submit($form, &$form_state) {
$message_nid = 255;
if (!isset($_SESSION['node_access'])) {
$_SESSION['node_access'] = array();
}
if (!isset($_SESSION['node_access']['nid'])) {
$_SESSION['node_access']['nid'] = $message_nid;
}
$form_state['redirect'] = 'node/' . $message_nid;
}
function mymodule_node_access($node, $op, $account) {
$node_access = NODE_ACCESS_IGNORE;
if ($op == 'view' && $node->type == 'message') {
if (isset($_SESSION['node_access'] && !empty($_SESSION['node_access'])) {
if ($node->nid == $_SESSION['node_access']['nid']) {
unset($_SESSION['node_access']['nid']);
$node_access = NODE_ACCESS_ALLOW ;
} else {
unset($_SESSION['node_access']['nid']);
$node_access = NODE_ACCESS_DENY;
}
} else {
$node_access = NODE_ACCESS_DENY;
}
}
return $node_access;
}

Related

How to Save Multiple User Metadata in Database?

I am trying to create a registration form (here) with the help of a free plugin.
There are many elements in the registration form.
In the admin panel, meta keys can be assigned for each element in the plugin interface. So there is such an opportunity.
I'm trying to collect many of the elements on the same meta key by taking advantage of this possibility. In this direction, I gave the common meta key value to the elements I created. For example: info_about_register
So far everything is fine. However, if the form is posted, I can only get the last entry in the usermeta table. So the plugin is not serializing the same meta key data. An array does not occur.
There are many form elements. I want to pull these to the admin panel later. Therefore, I think that defining a separate line for each element will tire the system a lot. I contacted the plugin developers about this issue. However, no response for about 1.5 weeks.
I tried to solve this problem myself and found the codes where the action was taken. I made some changes to these. However, I was not successful. I would be very happy if you guide me.
.../includes/class-frontend.php
/*
* Called after submission save
* Registers new user into WordPress.
* Also map field values to user meta (If configured)
*/
public function after_submission_insertion($errors, $submission, $data) {
$sub_model = erforms()->submission;
$form_model = erforms()->form;
$form = $form_model->get_form($submission['form_id']);
// Copy attachment values in data from submission (as $data does not have any uploaded file values)
if(!empty($submission['attachments'])){
foreach($submission['attachments'] as $attachment){
if(!isset($data[$attachment['f_name']])){
$data[$attachment['f_name']]= $attachment['f_val'];
}
}
}
if ($form['type'] == "reg") { // Handling of registration forms
$user = 0;
$id = 0;
// Get mapping for user meta fields if any
$user_field_map = erforms_filter_user_fields($form['id'], $submission['fields_data']);
// Avoid user registration process if user already logged in
if (!is_user_logged_in()) {
$email_or_username = $user_field_map['user_email'];
if (isset($user_field_map['password'])) {
// Silently creates user
$username = isset($user_field_map['username']) ? $data[$user_field_map['username']] : $data[$email_or_username];
do_action('erf_before_user_creation',$submission);
$id = wp_create_user($username, $data[$user_field_map['password']], $data[$email_or_username]);
} else {
// Register user and sends random password via email notification
do_action('erf_before_user_creation',$submission);
$id = register_new_user($data[$email_or_username], $data[$email_or_username]);
}
if (is_wp_error($id)) {
// In case something goes wrong delete the submission
wp_delete_post($submission['id'], true);
$error_code = $id->get_error_code();
if ($error_code == 'existing_user_login') {
$email_or_username = 'username_error';
}
$errors[] = array($email_or_username, $id->get_error_message($id->get_error_code()));
return $errors;
} else {
$selected_role = erforms_get_selected_role($submission['form_id'], $data);
if (!empty($selected_role)) { // Means user has selected any role
$user_model = erforms()->user;
$selected_role= apply_filters('erf_before_setting_user_role',$selected_role,$id,$form, $submission);
$user_model->set_user_role($id, $selected_role);
}
foreach ($user_field_map as $req_key => $meta_key) {
$is_primary_key = in_array($meta_key, erforms_primary_field_types());
if (isset($data[$req_key]) && !$is_primary_key) {
$m_keys= explode(',',$meta_key);
foreach($m_keys as $m_key){
if(!empty($m_key)){
$status = erforms_update_user_meta($id, $m_key, $data[$req_key]);
do_action('erf_user_meta_updated',$m_key,$id,$data[$req_key],$status);
}
}
}
}
do_action('erf_user_created', $id, $form['id'], $submission['id']);
}
} else {
// Get user details
$user = wp_get_current_user();
$id = $user->ID;
foreach ($user_field_map as $req_key => $meta_key) {
$is_primary_key = in_array($meta_key, erforms_primary_field_types());
if (isset($data[$req_key]) && !$is_primary_key) {
$m_keys= explode(',',$meta_key);
foreach($m_keys as $m_key){
if(!empty($m_key)){
$status= erforms_update_user_meta($id,$m_key,$data[$req_key]);
do_action('erf_user_meta_updated',$m_key,$id,$data[$req_key],$status);
}
}
}
}
//...
// User meta,URL params or default values should be prefilled only when we are not loading submission data
if(empty($submission)){
$user_meta = erforms()->user->frontend_localize_user_meta($form);
$filtered_url_params = array();
foreach ($_GET as $key => $val) {
$filtered_url_params[urldecode(strtolower(wp_unslash($key)))] = sanitize_text_field(wp_unslash($val));
}
$url_keys = array_keys($filtered_url_params);
foreach ($form['fields'] as $field) {
$label = !empty($field['label']) ? strtolower(str_replace(' ', '_', $field['label'])) : '';
$label = str_replace('&', 'and', $label); // Cause URL params do not allow &
if (!empty($field['name']) && !empty($label) && in_array($label, $url_keys)) {
if (!isset($user_meta[$field['name']]) && !empty($filtered_url_params[$label])) {
$user_meta[$field['name']] = stristr($filtered_url_params[$label], '|') ? explode('|', $filtered_url_params[$label]) : $filtered_url_params[$label];
}
}
if(!empty($field['name']) && empty($user_meta[$field['name']]) && !empty($field['value'])){
$user_meta[$field['name']] = $field['value'];
}
}
if (!empty($user_meta)) {
$data['user_meta'] = $user_meta;
}
}
$data= apply_filters('erf_form_localize_data',$data,$form);
return $data;
}
.../includes/functions.php
/**
* Wrapper to call update_user_meta function.
* This simply calls wordpress meta function and does not add any special prefix.
* Checks for any special meta key to update user table data.
* For example: display_name : updates user's display name. Instead of adding display_name usermeta
*/
function erforms_update_user_meta($user_id, $m_key, $m_val) {
switch ($m_key) {
case 'display_name' : $status = wp_update_user(array('ID' => $user_id, $m_key => $m_val));
return is_wp_error($status) ? false : true;
}
return update_user_meta($user_id, $m_key, $m_val);
}
Update:
Data can be stored as an array with a definition like below. Also, the key values ($all_meta_value[$req_key]) are equal to the id, name values automatically assigned to the HTML elements by the plugin.
Using this, different conditional states can be written.
The following code must be defined in the function.php file in the child theme:
add_action('erf_user_meta_updated','for_new_user_meta_uptated',10);
function for_new_user_meta_uptated($data){
//if the defined meta key (info_about_register) matches
if($m_key == 'info_about_register'){
$all_meta_value[$req_key] = $data;
}
}
add_action('erf_user_created', 'for_new_user_created',10);
function for_new_user_created($id){
//Save the values as a new user meta
add_user_meta($id, 'new_info_about_register', $get_meta_value);
//Remove saved single element user meta.
delete_user_meta($id, 'info_about_register');
}

Get initial value of entity in FormExtension

In my update form, I want to add a data attribute on the inputs that will contains the initial value of the entity. This way, I will be able to highlight the input when the user will modify it.
In the end, only the input modified by the users will be highlighted.
I want to use this only in update, not in creation.
To do so, I created a form extension like this:
class IFormTypeExtension extends AbstractTypeExtension
{
...
public static function getExtendedTypes()
{
//I want to be able to extend any form type
return [FormType::class];
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'is_iform' => false,
'is_iform_modification' => function (Options $options) {
return $options['is_iform'] ? null : false;
},
]);
$resolver->setAllowedTypes('is_iform', 'bool');
$resolver->setAllowedTypes('is_iform_modification', ['bool', 'null']);
}
public function buildView(FormView $view, FormInterface $form, array $options)
{
if (!$options['is_iform'] && !$this->isParentIForm($form)) {
return;
}
//We need to add the original value in the input as data-attributes
if (is_string($form->getViewData()) || is_int($form->getViewData())) {
$originValue = $form->getViewData();
} elseif (is_array($form->getViewData())) {
if (is_object($form->getNormData())) {
$originValue = implode('###', array_keys($form->getViewData()));
} elseif (is_array($form->getNormData()) && count($form->getNormData()) > 0 && is_object($form->getNormData()[0])) {
$originValue = implode('###', array_keys($form->getViewData()));
} else {
$originValue = implode('###', $form->getViewData());
}
} else {
//There's no value yet
$originValue = '';
}
$view->vars['attr'] = array_merge($view->vars['attr'], ['data-orig-value' => $originValue]);
}
private function isParentIForm(FormInterface $form)
{
if (null === $form->getParent()) {
return $form->getConfig()->getOption('is_iform');
}
return $this->isParentIForm($form->getParent());
}
}
As you can see in the buildView method, I get the originValue from the ViewData.
In a lot of cases, this works well.
But if I have any validation error in my form OR if I reload my form through AJAX, the ViewData contains the new information and not the values of the entity I want to update.
How can I get the values of the original entity?
I don't want to make a DB request in here.
I think I can use the FormEvents::POST_SET_DATA event, then save the entity values in session and use these in the buildView.
I could also give a new Option in my OptionResolver to ask for the initial entity.
Is it possible to have the original data of the entity directly form the buildView? (If I'm not wrong, this means the form before we call the handleRequest method).
Someone wanted to have an example with a controller. I don't think it's really interresting, because with the FormExtension, the code will be added automatically. But anyway, here is how I create a form in my controller :
$form = $this->createForm(CustomerType::class, $customer)->handleRequest($request);
And in the CustomerType, I will add the 'is_iform' key with configureOptions() :
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
"translation_domain" => "customer",
"data_class" => Customer::class,
'is_iform' => true //This line will activate the extension
]);
}
It's probably an opinionated answer. There also might be better approaches.
I'm not a big fan of your form extension, since it's really convoluted and unclear what's happening, at least to my eyes.
What I'm proposing: When the form submit happened, in your controller you should do the following
// ((*)) maybe store customer, see below
$form = $this->createForm(CustomerType::class, $customer);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
// easy case, you got this.
$em->flush();
return $this->redirect(); // or another response
} elseif($form->isSubmitted()) {
// form was submitted with errors, have to refresh entity!
// REFRESH - see discussion below for alternatives
$em->refresh($customer);
// then create form again with original values:
$form = $this->createForm(CustomerType::class, $customer);
}
// other stuff
return $this->render(..., ['form' => $form->createView(), ...]);
so, essentially, when the form validation fails, you refresh the entity and recreate the form, avoiding the problem with the changed state of your entity. I believe this approach ultimately is easier then hacking the form to magically not update values or re-set older values.
Now the question remains: how to refresh an entity? Simplest approach: reload from database:
$em->refresh($customer); // easiest approach, will likely run another query.
Alternatives:
Instead of giving $customer to the form, you create a customer DTO that contains the same values but on change doesn't automatically change the original object. If the form validation fails, you can just re-generate the DTO.
Instead of refresh($customer), which will most likely run another query (except maybe not, if you have a cache), you could cache the customer yourself via a DefaultCacheEntityHydrator, you would have to create your own EntityCacheKey object (not really hard), generate a cache entry (DefaultCacheEntityHydrator::buildCacheEntry() at the ((*)) above) and restore the entry for when you need to restore it. Disclaimer: I don't know if/how this works with collections (i.e. collection properties, the entity might have).
That being said ... if you really really want a form extension for whatever reason, you might want to form event with a PRE_SET_DATA handler that stores the data in the form type object, then on buildView uses those values. I wouldn't store something in the session for I don't see the necessity ... your aversion to db queries is baffling though, if that's your main reason for all the shenanigans
In the end, I managed to make it work BUT I'm not fully convinced by what I did.
It was not possible to get the original data from the form OR add a new property (the form is read only in the form extension).
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addEventListener(
FormEvents::POST_SET_DATA,
function (FormEvent $event) {
$form = $event->getForm();
if ('_token' === $form->getName()) {
return;
}
$data = $event->getData();
$this->session->set('iform_'.$form->getName(), is_object($data) ? clone $data : $data);
}
);
}
What I do here, is simply register the form values by its name in the session.
If it's an object, I need to clone it, because the form will modify it later in the process and I want to work with the original state of the form.
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'is_iform' => false,
'is_iform_modification' => function (Options $options) {
return $options['is_iform'] ? null : false;
},
]);
$resolver->setAllowedTypes('is_iform', 'bool');
$resolver->setAllowedTypes('is_iform_modification', ['bool', 'null']);
}
The configure options did not change.
And then, depending on the value type, I create my "data-orig-value" :
public function buildView(FormView $view, FormInterface $form, array $options)
{
if (!$options['is_iform'] && !$this->isParentIForm($form)) {
return;
}
$propertyValue = $this->session->get('iform_'.$form->getName());
$originValue = '';
try {
if (null !== $propertyValue) {
//We need to add the original value in the input as data-attributes
if (is_bool($propertyValue)) {
$originValue = $propertyValue ? 1 : 0;
} elseif (is_string($propertyValue) || is_int($propertyValue)) {
$originValue = $propertyValue;
} elseif (is_array($propertyValue) || $propertyValue instanceof Collection) {
if (is_object($propertyValue)) {
$originValue = implode('###', array_map(function ($object) {
return $object->getId();
}, $propertyValue->toArray()));
} elseif (is_array($propertyValue) && count($propertyValue) > 0 && is_object(array_values($propertyValue)[0])) {
$originValue = implode('###', array_map(function ($object) {
return $object->getId();
}, $propertyValue));
} else {
$originValue = implode('###', $propertyValue);
}
} elseif ($propertyValue instanceof DateTimeInterface) {
$originValue = \IntlDateFormatter::formatObject($propertyValue, $form->getConfig()->getOption('format', 'dd/mm/yyyy'));
} elseif (is_object($propertyValue)) {
$originValue = $propertyValue->getId();
} else {
$originValue = $propertyValue;
}
}
} catch (NoSuchPropertyException $e) {
if (null !== $propertyValue = $this->session->get('iform_'.$form->getName())) {
$originValue = $propertyValue;
$this->session->remove('iform_'.$form->getName());
} else {
$originValue = '';
}
} finally {
//We remove the value from the session, to not overload the memory
$this->session->remove('iform_'.$form->getName());
}
$view->vars['attr'] = array_merge($view->vars['attr'], ['data-orig-value' => $originValue]);
}
private function isParentIForm(FormInterface $form)
{
if (null === $form->getParent()) {
return $form->getConfig()->getOption('is_iform');
}
return $this->isParentIForm($form->getParent());
}
Maybe the code sample will help anyone !
If anyone have a better option, don't hesitate to post it !

How to pre-select a selct box in Ninja Forms from a query string

I am trying to pre select a value within a select field in my contact from on the contact page from another page by passing a query string ?request=call-back. I am using Ninja Forms and the values that I have in my select field are: email-us, call-back
I have tried the following:
add_filter( 'ninja_forms_render_default_value', 'my_ninja_forms_pre_populate', 10, 3 );
function my_ninja_forms_pre_populate( $default_value, $field_type, $field_settings ){
if( 'request' == $field_settings[ 'key' ] ){
$default_value = $_GET['request'];
}
return $default_value;
}
I would like the select field to have call-back already selected.
I didnt need to use the filter that I was attempting. I changed the key value under administration within the ninja form builder and I made sure that none of the values were pre selected.
This drove me mad... but finally I've got a solution:
// register custom get parameter (to use it with get_query_var() for safety reasons)
function add_get_val() {
global $wp;
$wp->add_query_var('request');
}
add_action('init', 'add_get_val');
add_filter('ninja_forms_localize_field_listselect', function ($field) {
if (get_query_var('request')) {
$request = get_query_var('request');
$optionExists = FALSE;
// check if field exists
foreach ($field['settings']['options'] as $option) {
if ($option['value'] === $request) {
$optionExists = TRUE;
break;
}
}
if ($optionExists) {
foreach ($field['settings']['options'] as $key => $option) {
// deselect all fields
$field['settings']['options'][$key]['selected'] = 0;
// select parameter
if ($option['value'] === $request) {
$field['settings']['options'][$key]['selected'] = 1;
}
}
}
}
return $field;
});

Hook to change page title

I want to programmatically alter a page title in Drupal 8 so that it will be hard-coded in the theme file.
I'm attempting to use a hook function to preprocess_page_title, but it seems to not understand what page to change the title on.
Here's what I have so far:
function test_preprocess_page_title(&$variables) {
if (arg(0) == 'node/12') {
$variables['title'] = 'New Title';
}
}
I figured the only way to make this change on one specific page is to set the node argument. Has any one figured out a way to override page title on Drupal?
In your template.theme file add the preprocessor and then override page-title.html.twig in your template folder by printing the variable, like below:
function theme_preprocess_page_title(&$variables) {
$node = \Drupal::request()->attributes->get('node');
$nid = $node->id();
if($nid == '14') {
$variables['subtitle'] = 'Subheading';
}
}
then {{ subtitle }}
Here's the method to preprocess your page :
function yourthemename_preprocess_page(&$variables) {
$node = \Drupal::routeMatch()->getParameter('node');
if ($node) {
$variables['title'] = $node->getTitle();
}
}
and in your template page.html.twig
{{title}}
There are a couple of solutions to change the page title
On template
/**
* Implements hook_preprocess_HOOK().
*/
function MYMODULE_preprocess_page_title(&$variables) {
if ($YOUR_LOGIC == TRUE) {
$variables['title'] = 'New Title';
}
}
On the node view page
/**
* Implements hook_ENTITY_TYPE_view_alter().
*/
function mymodule_user_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
if ($YOUR_LOGIC == TRUE) {
$build['#title'] = $entity->get('field_display_name')->getString();
}
}
for a sample if you want to change user title
function mymodule_user_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
if ($entity->getEntityTypeId() == 'user') {
$build['#title'] = $entity->get('field_first_name')->getString();
}
}
On Controller or hook_form_alter
if ($YOUR_LOGIC == TRUE) {
$request = \Drupal::request();
if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
$route->setDefault('_title', 'New Title');
}
}
The Page Title is a block in Drupal 8. If you can find the plugin_id of the page title block (which is likely to be page_title_block), then you can override the title directly, with no need to change an existing twig template, using a block preprocessor. Your code may be similar to the following:
function vhs_preprocess_block(&$variables) {
// This example restricts based on the actual URL; you can replace this with any other logic you wish.
$request = \Drupal::request();
$uri = $request->getRequestUri();
if (
isset($variables['elements']['#base_plugin_id']) &&
$variables['elements']['#base_plugin_id'] == 'page_title_block' &&
isset($variables['content']['#title']['#markup']) &&
strpos($uri, '/url-to-match') === 0 // replace with logic that finds the correct page to override
) {
$variables['content']['#title']['#markup'] = 'My Custom Title';
}
}
The example above uses the Drupal request object to grab and compare the actual URL. The initial question asked to match based on the node path; you could get that with something like:
$current_path = \Drupal::service('path.current')->getPath();
Then, in place of the strpos condition above, you could use:
$current_path == 'node/12'
i have changed the page_title block for user/uid to a different custom account field name like this :
function hook_preprocess_block(&$variables) {
$path = \Drupal::request()->getpathInfo();
$arg = explode('/', $path);
if (isset($arg[2]) && $arg[2] == 'user' && isset($arg[3])) {
if (isset($variables['elements']['content']['#type']) && $variables['elements']['content']['#type'] == 'page_title') {
$account = \Drupal\user\Entity\User::load($arg[3]);
if(isset($account) && isset($account->field_mycustomfield->value)){
$variables['content']['#title']['#markup']=$account->field_mycustomfield->value;
}
}
}
}

Drupal 7 with Multiple Login sources?

I'm just a new to Drupal but i wanna make my site to be authenticated from external login sources. I mean, not to use the current Drupal database to login. Then use one or more external databases.
To make it a little more clear:
User Login Authentication will not use the existing Drupal database.
Then it will use the external database(s)
External Database will be one or more (If User is not found on one external database, then found on another source again.)
I've been trying to hack the Drupal Login but i can't make it yet as the structure is complicated enough. Any solution or suggestion please?
Which files will be needed to modify?
You shouldn't completely discard Drupal's user system for this, but rather piggy tail on it with your own authentication. The way this works is by 1) collecting user credentials, 2) authenticating against your custom sources and 3) registering/logging in an external user.
Collecting credentials
One way of collecting user credentials is by hijacking the user login form. You do this by implementing hook_form_alter() and add your own validation callback.
function mymodule_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'user_login') {
$form['#validate'][] = array('mymodule_user_login_validate');
$form['#validate'][] = array('mymodule_user_login_submit');
}
}
The login form will look exactly the same and but it will send the username and password to your callback instead.
The user_login_name_validate() and user_login_final_validate() callbacks are user.module's default validators. They supply user blocking functionality and brute force protection but feel free to leave them out.
Authentication
When the login form is sent you pick up the credentials and authenticate against your custom sources.
function mymodule_user_login_validate($form, &$form_state) {
mymodule_authenticate(
$form_state['values']['name'],
$form_state['values']['name']
);
}
If the credentials doesn't check out you can just call form_set_error() to inform the user of what went wrong. Doing this will also make sure no further validation or submit callbacks are executed.
External users
So if no error is evoked then Drupal will move on to running your submit callback. Then we can run user_external_login_register() to create our external user as a Drupal user.
function mymodule_user_login_submit($form, &$form_state) {
user_external_login_register($form_state['values']['name'], 'mymodule');
}
As the name implies, this function will also log the user in. And that should be it!
There's a module for that
Chances are there is already a module for what you want to do. Always go search for existing contrib modules before starting your own!
define('DRUPAL_ROOT', 'full/path/to/drupal');
$drupal_url = 'http://site.com';
drupal_external_load($drupal_path, $drupal_url);
if ( !($user->uid > 0) ) {
drupal_external_login('user', 'pass');
} else {
print 'user is already logged';
}
function drupal_external_load($drupal_url) {
global $base_url;
// set drupal base_url (if not set set in settings.php)
// because it's used in session name
$base_url = $drupal_url;
// save current path
$current_path = getcwd();
// move to drupal path, because it uses relative path for its includes
chdir(DRUPAL_ROOT);
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// to use the drupal global user var (instead of session hack)
// drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
// return the current path
chdir($current_path);
}
// load a drupal user into the user obj
function drupal_external_userload($user_info = array()) {
// Dynamically compose a SQL query:
$query = array();
$params = array();
if (is_numeric($user_info)) {
$user_info = array('uid' => $user_info);
}
elseif (!is_array($user_info)) {
return FALSE;
}
foreach ($user_info as $key => $value) {
if ($key == 'uid' || $key == 'status') {
$query[] = "$key = %d";
$params[] = $value;
}
else if ($key == 'pass') {
$query[] = "pass = '%s'";
$params[] = md5($value);
}
else {
$query[]= "LOWER($key) = LOWER('%s')";
$params[] = $value;
}
}
$result = db_query('SELECT * FROM {users} u WHERE '. implode(' AND ', $query), $params);
if ($user = db_fetch_object($result)) {
$user = drupal_unpack($user);
$user->roles = array();
if ($user->uid) {
$user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
}
else {
$user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
}
$result = db_query('SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON
ur.rid = r.rid WHERE ur.uid = %d', $user->uid);
while ($role = db_fetch_object($result)) {
$user->roles[$role->rid] = $role->name;
}
//user_module_invoke('load', $user_info, $user);
}
else {
$user = FALSE;
}
return $user;
}
// don't send any headers before calling this
function drupal_external_login($username, $password) {
global $user;
if ( $user->uid > 0 ) {
if ( $user->name != $username ) {
drupal_external_logout();
} else {
return true;
}
}
require DRUPAL_ROOT. '/includes/password.inc' ;
$account = user_load_by_name($username);
if ( user_check_password($password, $account) ) {
$user = $account;
drupal_session_regenerate();
return true;
}
return false;
}
function drupal_external_logout() {
global $user;
session_destroy();
$user = drupal_anonymous_user();
}

Resources