public function serveCachedPage() { $cache_enabled = $this->getCacheMode(); // If there is no session cookie and cache is enabled (or forced), try // to serve a cached page. if (!isset($_COOKIE[session_name()]) && $cache_enabled) { global $user; // Make sure there is a user object because its timestamp will be // checked, hook_boot might check for anonymous user etc. $user = drupal_anonymous_user(); // Get the page from the cache. $cache = drupal_page_get_cache(); // If there is a cached page, display it. if (is_object($cache)) { header('X-Drupal-Cache: HIT'); // Restore the metadata cached with the page. $_GET['q'] = $cache->data['path']; drupal_set_title($cache->data['title'], PASS_THROUGH); date_default_timezone_set(drupal_get_user_timezone()); // If the skipping of the bootstrap hooks is not enforced, call // hook_boot. if (variable_get('page_cache_invoke_hooks', TRUE)) { bootstrap_invoke_all('boot'); } drupal_serve_page_from_cache($cache); // If the skipping of the bootstrap hooks is not enforced, call // hook_exit. if (variable_get('page_cache_invoke_hooks', TRUE)) { bootstrap_invoke_all('exit'); } // We are done. exit; } else { header('X-Drupal-Cache: MISS'); } } }
/** * {@inheritdoc} */ public function blockForm($form, &$form_state) { $form['list_size'] = array('#type' => 'textfield', '#title' => t('Number of users to display in the list'), '#default_value' => $this->configuration['list_size'], '#size' => '3', '#maxlength' => '4'); $form['include_anon'] = array('#type' => 'checkbox', '#title' => t('Include %anonymous', array('%anonymous' => user_format_name(drupal_anonymous_user()))), '#default_value' => $this->configuration['include_anon']); $form['show_form'] = array('#type' => 'checkbox', '#title' => t('Allow entering any user name'), '#default_value' => $this->configuration['show_form']); return $form; }
public function alterItems(array &$items) { // Prevent session information from being saved while indexing. drupal_save_session(FALSE); // Force the current user to anonymous to prevent access bypass in search // indexes. $original_user = $GLOBALS['user']; $GLOBALS['user'] = drupal_anonymous_user(); $entity_type = $this->index->getEntityType(); $entity_handler = panelizer_entity_plugin_get_handler($entity_type); foreach ($items as &$item) { $entity_id = entity_id($entity_type, $item); $item->search_api_panelizer_content = NULL; $item->search_api_panelizer_title = NULL; try { if ($render_info = $entity_handler->render_entity($item, 'page_manager')) { $item->search_api_panelizer_content = $render_info['content']; $item->search_api_panelizer_title = !empty($render_info['title']) ? $render_info['title'] : NULL; } } catch (Exception $e) { watchdog_exception('panelizer', $e, 'Error indexing Panelizer content for %entity_type with ID %entity_id', array('%entity_type' => $entity_type, '%entity_id' => $entity_id)); } } // Restore the user. $GLOBALS['user'] = $original_user; drupal_save_session(TRUE); }
/** * {@inheritdoc} * @see user_logout() */ public function logout(Request $request, Response $response, TokenInterface $token) { $user = $token->getUser(); if (is_a($user, 'Bangpound\\Bundle\\DrupalBundle\\Security\\User\\User')) { /** @var \Bangpound\Bundle\DrupalBundle\Security\User\User $user */ $user = $token->getUser()->getDrupalUser(); watchdog('user', 'Session closed for %name.', array('%name' => $user->name)); module_invoke_all('user_logout', $user); $GLOBALS['user'] = drupal_anonymous_user(); } }
/** * Helper function that creates a user object with the given role. */ protected function createUser($role) { $edit = array(); $edit['name'] = $this->randomName(); $edit['mail'] = $edit['name'] . '@example.com'; // @todo role ids are completely broken, if modules are enable in the wrong // order. $edit['roles'] = array($role->rid => $role->name); $edit['pass'] = user_password(); $edit['status'] = 1; $user = user_save(drupal_anonymous_user(), $edit); $user->pass_raw = $edit['pass']; return $user; }
/** * Constructor for RateLimitManager. * * @param ResourceInterface $resource * Resource being checked. * @param array $plugin_options * Array of options keyed by plugin id. * @param object $account * The identified user account for the request. * @param RateLimitPluginManager $manager * The plugin manager. */ public function __construct(ResourceInterface $resource, array $plugin_options, $account = NULL, RateLimitPluginManager $manager = NULL) { $this->resource = $resource; $account = $account ? $account : $resource->getAccount(); $this->account = $account ? $account : drupal_anonymous_user(); $manager = $manager ?: RateLimitPluginManager::create(); $options = array(); foreach ($plugin_options as $plugin_id => $rate_options) { // Set the instance id to articles::request and specify the plugin id. $instance_id = $resource->getResourceName() . PluginBase::DERIVATIVE_SEPARATOR . $plugin_id; $options[$instance_id] = array('id' => $plugin_id, 'resource' => $resource); $options[$instance_id] += $rate_options; } $this->plugins = new RateLimitPluginCollection($manager, $options); }
/** * {@inheritdoc} * * If "File entity" module exists, determine access by its provided * permissions otherwise, check if variable is set to allow anonymous users to * upload. Defaults to authenticated user. */ public function access() { // The getAccount method may return an UnauthorizedException when an // authenticated user cannot be found. Since this is called from the access // callback, not from the page callback we need to catch the exception. try { $account = $this->getAccount(); } catch (UnauthorizedException $e) { // If a user is not found then load the anonymous user to check // permissions. $account = drupal_anonymous_user(); } if (module_exists('file_entity')) { return user_access('bypass file access', $account) || user_access('create files', $account); } return (variable_get('restful_file_upload_allow_anonymous_user', FALSE) || $account->uid) && parent::access(); }
public function alterItems(array &$items) { // Prevent session information from being saved while indexing. drupal_save_session(FALSE); // Force the current user to anonymous to prevent access bypass in search // indexes. $original_user = $GLOBALS['user']; $GLOBALS['user'] = drupal_anonymous_user(); $entity_type = $this->index->getEntityType(); $entity_handler = panelizer_entity_plugin_get_handler($entity_type); foreach ($items as &$item) { $entity_id = entity_id($entity_type, $item); $item->search_api_panelizer_content = NULL; $item->search_api_panelizer_title = NULL; // If Search API specifies a language to view the item in, force the // global language_content to be Search API item language. Fieldable // panel panes will render in the correct language. if (isset($item->search_api_language)) { global $language_content; $original_language_content = $language_content; $languages = language_list(); if (isset($languages[$item->search_api_language])) { $language_content = $languages[$item->search_api_language]; } else { $language_content = language_default(); } } try { if ($render_info = $entity_handler->render_entity($item, 'page_manager')) { $item->search_api_panelizer_content = $render_info['content']; $item->search_api_panelizer_title = !empty($render_info['title']) ? $render_info['title'] : NULL; } } catch (Exception $e) { watchdog_exception('panelizer', $e, 'Error indexing Panelizer content for %entity_type with ID %entity_id', array('%entity_type' => $entity_type, '%entity_id' => $entity_id)); } // Restore the language_content global if it was overridden. if (isset($original_language_content)) { $language_content = $original_language_content; } } // Restore the user. $GLOBALS['user'] = $original_user; drupal_save_session(TRUE); }
/** * Tests authorization. */ public function testAuthorize() { // Create a user with limited permissions. We can't use // $this->drupalCreateUser here because we need to to set a specific user // name. $edit = array('name' => 'Poor user', 'mail' => '*****@*****.**', 'pass' => user_password(), 'status' => 1); $account = user_save(drupal_anonymous_user(), $edit); // // Adding a mapping to the user_name will invoke authorization. $this->addMappings('comment', array(5 => array('source' => 'mail', 'target' => 'user_mail'))); $url = $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'feeds_comment_processor') . '/tests/test.csv'; $nid = $this->createFeedNode('comment', $url, 'Comment test'); $this->assertText('Failed importing 1 comment'); $this->assertText('User ' . $account->name . ' is not permitted to post comments.'); $this->assertEqual(0, db_query("SELECT COUNT(*) FROM {comment}")->fetchField()); user_role_change_permissions(2, array('post comments' => TRUE)); $this->drupalPost("node/{$nid}/import", array(), 'Import'); $this->assertText('Created 1 comment.'); $this->assertEqual(1, db_query("SELECT COUNT(*) FROM {comment}")->fetchField()); $comment = comment_load(1); $this->assertEqual(0, $comment->status); }
public function read($sessionId) { global $user; if (!isset($_COOKIE[$this->sessionName])) { $user = drupal_anonymous_user(); return ''; } $cid = $this->getCid($sessionId); if ($cached = $this->cacheBackend->get($cid)) { $data = $cached->data; if ($data && $data->uid > 0) { $this->uid = $data->uid; $serializedData = $data->session; } else { $serializedData = ''; } $this->sessionDataSetHash($sessionId, $serializedData); return $serializedData; } else { return NULL; } }
/** * Get the user account for the request. * * @param array $request * The request. * @param string $method * The HTTP method. * @param boolean $cache * Boolean indicating if the resolved user should be cached for next calls. * * @throws RestfulUnauthorizedException * @return \stdClass * The user object. */ public function getAccount(array $request = array(), $method = \RestfulInterface::GET, $cache = TRUE) { global $user; // Return the previously resolved user, if any. if (!empty($this->account)) { return $this->account; } // Resolve the user based on the providers in the manager. $account = NULL; foreach ($this as $provider) { if ($provider->applies($request, $method) && $account = $provider->authenticate($request, $method)) { // The account has been loaded, we can stop looking. break; } } if (!$account) { if ($this->count() && !$this->getIsOptional()) { // Allow caching pages for anonymous users. drupal_page_is_cacheable(variable_get('restful_page_cache', FALSE)); // User didn't authenticate against any provider, so we throw an error. throw new \RestfulUnauthorizedException('Bad credentials'); } // If the account could not be authenticated default to the global user. // Most of the cases the cookie provider will do this for us. $account = drupal_anonymous_user(); if (empty($request['__application']['rest_call'])) { // If we are using the API from within Drupal and we have not tried to // authenticate using the 'cookie' provider, then we expect to be logged // in using the cookie authentication as a last resort. $account = $user->uid ? user_load($user->uid) : $account; } } if ($cache) { $this->setAccount($account); } // Disable page caching for security reasons so that an authenticated user // response never gets into the page cache for anonymous users. // This is necessary because the page cache system only looks at session // cookies, but not at HTTP Basic Auth headers. drupal_page_is_cacheable(!$account->uid && variable_get('restful_page_cache', FALSE)); // Record the access time of this request. $this->setAccessTime($account); return $account; }
/** * @deprecated Use the entity_is_public module instead. */ public static function isPubliclyVisible($entity_type, $entity, array $options = array()) { $options += array('needs alias' => FALSE); $uri = entity_uri($entity_type, $entity); if (empty($uri['path'])) { return FALSE; } elseif ($options['needs alias'] && !drupal_lookup_path('alias', $uri['path'], NULL)) { return FALSE; } elseif (module_exists('rabbit_hole') && rabbit_hole_get_action($entity_type, $entity) !== RABBIT_HOLE_DISPLAY_CONTENT) { return FALSE; } else { return entity_access('view', $entity_type, $entity, drupal_anonymous_user()); } }
/** * Create a user with a particular role. * * @param array|string $role_names * String role or array of role names to assign to user. Note that the user * always has the default permissions derived from the "authenticated users" * role. * @param string $password * Preferred password to set for the user. * @param array $edit_overrides * Values for user or user profile fields to override. * * @return object|bool * A fully loaded user object with pass_raw property, or FALSE if account * creation fails. */ protected function drupalCreateUserWithRoles($role_names = [], $password = NULL, $edit_overrides = []) { // Create a user assigned to that role. $edit = []; $edit['mail'] = Random::email(); $edit['name'] = $edit['mail']; $edit['pass'] = is_null($password) ? user_password() : $password; $edit['status'] = 1; $edit['roles'] = []; if (!empty($role_names)) { $role_names = is_array($role_names) ? $role_names : [$role_names]; foreach ($role_names as $rolename) { $role = user_role_load_by_name($rolename); $edit['roles'][$role->rid] = $role->name; } } // Merge fields with provided $edit_overrides. $edit_overrides = array_merge($edit, $edit_overrides); // Build an empty user object, including all default fields. $account = drupal_anonymous_user(); $account->roles = array_merge($account->roles, $edit_overrides['roles']); foreach (field_info_instances('user', 'user') as $field_name => $info) { if (!isset($account->{$field_name})) { $account->{$field_name} = []; } } $account = user_save($account, $edit_overrides); if (empty($account->uid)) { return FALSE; } $account->pass_raw = $edit_overrides['pass']; $this->assertTrue(!empty($account->uid), t('User created with name %name (%uid) and pass %pass and roles %roles', ['%roles' => implode(', ', $role_names), '%name' => $edit['name'], '%uid' => $account->uid, '%pass' => $edit['pass']]), t('User login')); return $account; }
/** * Constructor for RestfulRateLimitManager. * * @param string $resource * Resource name being checked. * @param array $plugin * The plugin info array for the rate limit. * @param \stdClass $account * The identified user account for the request. */ public function __construct($resource, array $plugin, $account = NULL) { parent::__construct($plugin); $this->resource = $resource; $this->setPluginInfo($plugin); $this->account = $account ? $account : drupal_anonymous_user(); }
<?php global $user; tzbase_include_proto_classes(); $account = user_load(array('name' => 'Johan Heander')); if ($account) { TZIntellitimeBot::destroy_session_data($account->intellitime_session_data); user_save($account, array('intellitime_session_data' => NULL)); } // Login and logout to refresh cookie $form_state = array('values' => array('name' => 'Johan Heander', 'pass' => '0733623516', 'op' => t('Log in'))); drupal_execute('user_login', $form_state); // Destroy the current session: session_destroy(); // Only variables can be passed by reference workaround. $null = NULL; user_module_invoke('logout', $null, $user); // Load the anonymous user $user = drupal_anonymous_user(); tzintellitime_sync_synchronize_users(); TZIntellitimeBot::destroy_session_data($account->intellitime_session_data);
public function getUserClaims($uid, $scope) { $account = user_load($uid); if (!$account) { throw new \InvalidArgumentException("The supplied user couldn't be loaded."); } $requested_scopes = explode(' ', trim($scope)); // The OpenID Connect 'sub' (Subject Identifier) property is usually the // user's UID, but this is configurable for backwards compatibility reasons. // See: https://www.drupal.org/node/2274357#comment-9779467 $sub_property = variable_get('oauth2_server_user_sub_property', 'uid'); // Prepare the default claims. $claims = array('sub' => $account->{$sub_property}); if (in_array('email', $requested_scopes)) { $claims['email'] = $account->mail; $claims['email_verified'] = variable_get('user_email_verification', TRUE); } if (in_array('profile', $requested_scopes)) { if (!empty($account->name)) { $claims['name'] = format_username($account); $claims['preferred_username'] = $account->name; } if (!empty($account->timezone)) { $claims['zoneinfo'] = $account->timezone; } if (user_access('access user profiles', drupal_anonymous_user())) { $claims['profile'] = url('user/' . $account->uid, array('absolute' => TRUE)); } if ($picture = $this->getUserPicture($account)) { $claims['picture'] = $picture; } } // Allow modules to supply additional claims. $claims += module_invoke_all('oauth2_server_user_claims', $account, $requested_scopes); // Finally, allow modules to alter claims. drupal_alter('oauth2_server_user_claims', $claims, $account, $requested_scopes); return $claims; }
/** * Get the user account for the request. * * @param array $request * The request. * @param string $method * The HTTP method. * @param boolean $cache * Boolean indicating if the resolved user should be cached for next calls. * * @throws RestfulUnauthorizedException * @return \stdClass * The user object. */ public function getAccount(array $request = array(), $method = \RestfulInterface::GET, $cache = TRUE) { global $user; // Return the previously resolved user, if any. if (!empty($this->account)) { return $this->account; } // Resolve the user based on the providers in the manager. $account = NULL; foreach ($this as $provider) { if ($provider->applies($request, $method) && $account = $provider->authenticate($request, $method)) { // The account has been loaded, we can stop looking. break; } } if (!$account) { if ($this->count() && !$this->getIsOptional()) { // User didn't authenticate against any provider, so we throw an error. throw new \RestfulUnauthorizedException('Bad credentials'); } // If the account could not be authenticated default to the global user. // Most of the cases the cookie provider will do this for us. $account = drupal_anonymous_user(); if (empty($request['__application']['rest_call'])) { // If we are using the API from within Drupal and we have not tried to // authenticate using the 'cookie' provider, then we expect to be logged // in using the cookie authentication as a last resort. $account = $user->uid ? user_load($user->uid) : $account; } } if ($cache) { $this->setAccount($account); } return $account; }
/** * Get Drupal anonymous user * * @return AccountInterface */ protected final function getAnonymousUser() { return drupal_anonymous_user(); }
/** * @param $config * * @return mixed */ public function install($config) { global $installDirPath; // create database if does not exists $this->createDatabaseIfNotExists($config['mysql']['server'], $config['mysql']['username'], $config['mysql']['password'], $config['mysql']['database']); global $installDirPath; // Build database require_once $installDirPath . 'civicrm.php'; civicrm_main($config); if (!$this->errors) { global $installType, $installURLPath; $registerSiteURL = "https://civicrm.org/register-site"; $commonOutputMessage = "<li>" . ts("Have you registered this site at CiviCRM.org? If not, please help strengthen the CiviCRM ecosystem by taking a few minutes to <a %1>fill out the site registration form</a>. The information collected will help us prioritize improvements, target our communications and build the community. If you have a technical role for this site, be sure to check Keep in Touch to receive technical updates (a low volume mailing list).", array(1 => "href='{$registerSiteURL}' target='_blank'")) . "</li>" . "<li>" . ts("We have integrated KCFinder with CKEditor and TinyMCE. This allows a user to upload images. All uploaded images are public.") . "</li>"; $output = NULL; if ($installType == 'drupal' && version_compare(VERSION, '7.0-rc1') >= 0) { // clean output @ob_clean(); $output .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'; $output .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'; $output .= '<head>'; $output .= '<title>' . ts('CiviCRM Installed') . '</title>'; $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'; $output .= '<link rel="stylesheet" type="text/css" href="template.css" />'; $output .= '</head>'; $output .= '<body>'; $output .= '<div style="padding: 1em;"><p class="good">' . ts('CiviCRM has been successfully installed') . '</p>'; $output .= '<ul>'; $drupalURL = civicrm_cms_base(); $drupalPermissionsURL = "{$drupalURL}index.php?q=admin/people/permissions"; $drupalURL .= "index.php?q=civicrm/admin/configtask&reset=1"; $output .= "<li>" . ts("Drupal user permissions have been automatically set - giving anonymous and authenticated users access to public CiviCRM forms and features. We recommend that you <a %1>review these permissions</a> to ensure that they are appropriate for your requirements (<a %2>learn more...</a>)", array(1 => "target='_blank' href='{$drupalPermissionsURL}'", 2 => "target='_blank' href='http://wiki.civicrm.org/confluence/display/CRMDOC/Default+Permissions+and+Roles'")) . "</li>"; $output .= "<li>" . ts("Use the <a %1>Configuration Checklist</a> to review and configure settings for your new site", array(1 => "target='_blank' href='{$drupalURL}'")) . "</li>"; $output .= $commonOutputMessage; // automatically enable CiviCRM module once it is installed successfully. // so we need to Bootstrap Drupal, so that we can call drupal hooks. global $cmsPath, $crmPath; // relative / abosolute paths are not working for drupal, hence using chdir() chdir($cmsPath); // Force the re-initialisation of the config singleton on the next call // since so far, we had used the Config object without loading the DB. $c = CRM_Core_Config::singleton(FALSE); $c->free(); include_once "./includes/bootstrap.inc"; include_once "./includes/unicode.inc"; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); // prevent session information from being saved. drupal_save_session(FALSE); // Force the current user to anonymous. $original_user = $GLOBALS['user']; $GLOBALS['user'] = drupal_anonymous_user(); // explicitly setting error reporting, since we cannot handle drupal related notices error_reporting(1); // rebuild modules, so that civicrm is added system_rebuild_module_data(); // now enable civicrm module. module_enable(array('civicrm', 'civicrmtheme')); // clear block, page, theme, and hook caches drupal_flush_all_caches(); //add basic drupal permissions civicrm_install_set_drupal_perms(); // restore the user. $GLOBALS['user'] = $original_user; drupal_save_session(TRUE); //change the default language to one chosen if (isset($config['seedLanguage']) && $config['seedLanguage'] != 'en_US') { civicrm_api3('Setting', 'create', array('domain_id' => 'current_domain', 'lcMessages' => $config['seedLanguage'])); } $output .= '</ul>'; $output .= '</div>'; $output .= '</body>'; $output .= '</html>'; echo $output; } elseif ($installType == 'drupal' && version_compare(VERSION, '6.0') >= 0) { // clean output @ob_clean(); $output .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'; $output .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'; $output .= '<head>'; $output .= '<title>' . ts('CiviCRM Installed') . '</title>'; $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'; $output .= '<link rel="stylesheet" type="text/css" href="template.css" />'; $output .= '</head>'; $output .= '<body>'; $output .= '<div style="padding: 1em;"><p class="good">' . ts("CiviCRM has been successfully installed") . '</p>'; $output .= '<ul>'; $drupalURL = civicrm_cms_base(); $drupalPermissionsURL = "{$drupalURL}index.php?q=admin/user/permissions"; $drupalURL .= "index.php?q=civicrm/admin/configtask&reset=1"; $output .= "<li>" . ts("Drupal user permissions have been automatically set - giving anonymous and authenticated users access to public CiviCRM forms and features. We recommend that you <a %1>review these permissions</a> to ensure that they are appropriate for your requirements (<a %2>learn more...</a>)", array(1 => "target='_blank' href='{$drupalPermissionsURL}'", 2 => "target='_blank' href='http://wiki.civicrm.org/confluence/display/CRMDOC/Default+Permissions+and+Roles'")) . "</li>"; $output .= "<li>" . ts("Use the <a %1>Configuration Checklist</a> to review and configure settings for your new site", array(1 => "target='_blank' href='{$drupalURL}'")) . "</li>"; $output .= $commonOutputMessage; // explicitly setting error reporting, since we cannot handle drupal related notices error_reporting(1); // automatically enable CiviCRM module once it is installed successfully. // so we need to Bootstrap Drupal, so that we can call drupal hooks. global $cmsPath, $crmPath; // relative / abosolute paths are not working for drupal, hence using chdir() chdir($cmsPath); // Force the re-initialisation of the config singleton on the next call // since so far, we had used the Config object without loading the DB. $c = CRM_Core_Config::singleton(FALSE); $c->free(); include_once "./includes/bootstrap.inc"; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); // rebuild modules, so that civicrm is added module_rebuild_cache(); // now enable civicrm module. module_enable(array('civicrm')); // clear block, page, theme, and hook caches drupal_flush_all_caches(); //add basic drupal permissions db_query('UPDATE {permission} SET perm = CONCAT( perm, \', access CiviMail subscribe/unsubscribe pages, access all custom data, access uploaded files, make online contributions, profile create, profile edit, profile view, register for events, view event info\') WHERE rid IN (1, 2)'); echo $output; } elseif ($installType == 'wordpress') { echo '<h1>' . ts('CiviCRM Installed') . '</h1>'; echo '<div style="padding: 1em;"><p style="background-color: #0C0; border: 1px #070 solid; color: white;">' . ts("CiviCRM has been successfully installed") . '</p>'; echo '<ul>'; $cmsURL = civicrm_cms_base(); $cmsURL .= "wp-admin/admin.php?page=CiviCRM&q=civicrm/admin/configtask&reset=1"; $wpPermissionsURL = "wp-admin/admin.php?page=CiviCRM&q=civicrm/admin/access/wp-permissions&reset=1"; $output .= "<li>" . ts("WordPress user permissions have been automatically set - giving Anonymous and Subscribers access to public CiviCRM forms and features. We recommend that you <a %1>review these permissions</a> to ensure that they are appropriate for your requirements (<a %2>learn more...</a>)", array(1 => "target='_blank' href='{$wpPermissionsURL}'", 2 => "target='_blank' href='http://wiki.civicrm.org/confluence/display/CRMDOC/Default+Permissions+and+Roles'")) . "</li>"; $output .= "<li>" . ts("Use the <a %1>Configuration Checklist</a> to review and configure settings for your new site", array(1 => "target='_blank' href='{$cmsURL}'")) . "</li>"; $output .= $commonOutputMessage; echo '</ul>'; echo '</div>'; $c = CRM_Core_Config::singleton(FALSE); $c->free(); $wpInstallRedirect = admin_url("?page=CiviCRM&q=civicrm&reset=1"); echo "<script>\n window.location = '{$wpInstallRedirect}';\n </script>"; } } return $this->errors; }
/** * Create a user with a given set of permissions. The permissions correspond to the * names given on the privileges page. * * @param $permissions * Array of permission names to assign to user. * @return * A fully loaded user object with pass_raw property, or FALSE if account * creation fails. */ protected function drupalCreateUser($permissions = array('access comments', 'access content', 'post comments', 'skip comment approval')) { // Create a role with the given permission set. if (!($rid = $this->drupalCreateRole($permissions))) { return FALSE; } // Create a user assigned to that role. $edit = array(); $edit['name'] = $this->randomName(); $edit['mail'] = $edit['name'] . '@example.com'; $edit['roles'] = array($rid => $rid); $edit['pass'] = user_password(); $edit['status'] = 1; $account = user_save(drupal_anonymous_user(), $edit); $this->assertTrue(!empty($account->uid), t('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), t('User login')); if (empty($account->uid)) { return FALSE; } // Add the raw password so that we can log in as this user. $account->pass_raw = $edit['pass']; return $account; }
/** * Extend drupalCreateUser() base method to accept a name as well as * multiple roles (rather than permissions). * * @param $name * Name to assign to the user * @param $rids * Array of Role IDs to assign to user. * @return * A fully loaded user object with pass_raw property, or FALSE if account * creation fails. */ protected function drupalCreateNamedUser($name, $rids = array()) { // Create a user. $rids2 = array(); foreach ($rids as $rid) { $rids2[$rid] = $rid; } $edit = array(); $edit['name'] = $name; $edit['mail'] = $edit['name'] . '@example.com'; $edit['roles'] = $rids2; $edit['pass'] = user_password(); $edit['status'] = 1; $account = user_save(drupal_anonymous_user(), $edit); $this->assertTrue(!empty($account->uid), t('User %name created, uid=%uid.', array('%name' => $edit['name'], '%uid' => $account->uid)), t('User login')); if (empty($account->uid)) { return FALSE; } // Add the raw password so that we can log in as this user. $account->pass_raw = $edit['pass']; return $account; }
/** * Listener bootstraps Drupal to DRUPAL_BOOTSTRAP_PAGE_HEADER * * @param GetResponseEvent $event */ public function onKernelRequestAfterSession(GetResponseEvent $event) { if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) { if (empty($GLOBALS['user'])) { $GLOBALS['user'] = drupal_anonymous_user(); date_default_timezone_set(drupal_get_user_timezone()); } // This is basically noop. drupal_bootstrap(DRUPAL_BOOTSTRAP_PAGE_HEADER); } }
/** * Session handler assigned by session_set_save_handler(). * * Cleans up a specific session. * * @param $sid * Session ID. * @return bool|void */ public function destroy($sid) { global $user; // Nothing to do if we are not allowed to change the session. if (!drupal_save_session()) { return; } // Delete session data. db_delete('sessions')->condition('sid', $sid)->execute(); // Reset $_SESSION and $user to prevent a new session from being started // in drupal_session_commit(). $_SESSION = array(); $user = drupal_anonymous_user(); }
/** * Create a new user based on informations from the Shibboleth handler if it's necessary or log in. * * If already authenticated - do nothing * If Shibboleth doesn't provide User information - error message * Else if user exists, and mail override (shib_auth_req_shib_only) enabled, override existing user info * If not exists, and Shibboleth provides mail address, create an account for this user * If there's no mail attribute, ask for the mail address on a generated form if mail override (shib_auth_req_shib_only) is disabled * In this case, the account will be created with this e-mail address. * * This function also gives roles to the user, if certain server fields were provided by the Shibboleth server */ function shib_auth_init() { global $user; $shib_headers_exist = $_SERVER['HTTP_SHIB_IDENTITY_PROVIDER'] || $_SERVER['Shib-Identity-Provider']; if (shib_auth_isDebug()) { $debug_message = print_r($_SERVER, TRUE); drupal_set_message('<pre>' . $debug_message . '</pre>'); } // if the user IS logged in as non-admin, but we're missing Shibboleth identity if (!$shib_headers_exist && $_SESSION['authentication'] == 'shib_auth' && variable_get('shib_auth_auto_destroy_session', FALSE) && $user->uid && $user->uid != 1) { drupal_set_message(t('Your session is expired. Please log in again!'), "error"); unset($_SESSION['authentication']); session_destroy(); $user = drupal_anonymous_user(); } $uname = $_SERVER[variable_get('shib_auth_username_variable', 'REMOTE_USER')]; $umail = $_SERVER[variable_get('shib_auth_username_email', 'HTTP_SHIB_MAIL')]; $umail_single = preg_replace('/;.*/', '', $umail); // Ensure that the user is the same as the one who has initiated the session if (isset($_SESSION['uname'])) { if ($_SESSION['uname'] != $uname) { unset($_SESSION['authentication']); unset($_SESSION['uname']); session_destroy(); $user = drupal_anonymous_user(); } } else { $_SESSION['uname'] = $uname; } // If // - The user isn't logged in // - There is Shibboleth authentication in the background // - The settings are fine and there has been a valid username set up // - The settings are fine and there has been a valid user email address set up if (!$user->uid && $shib_headers_exist) { //If custom mail form will be generated, generate it only once if (isset($_SESSION['redirected_to_custom_mail_form']) && $_SESSION['redirected_to_custom_mail_form']) { unset($_SESSION['redirected_to_custom_mail_form']); } else { //Shib didn't provide username, or the admin gave wrong server variable on the shib config form if (!$uname) { $message = t('Username is missing. Please contact your Shibboleth administrator!'); drupal_set_message($message, "error"); watchdog('shib_auth', $message, WATCHDOG_CRITICAL); } else { $username_query = db_query("SELECT * FROM {users} WHERE name='%s'", $uname); $new_user = !db_fetch_object($username_query); //The user exists in the drupal user database, login her if (!$new_user) { user_external_login_register($uname, "shib_auth"); $_SESSION['authentication'] = 'shib_auth'; //if we have an e-mail address from the shib server if ($umail_single) { //and the Shibboleth mail address override was enabled in the admin config if (variable_get('shib_auth_mail_shib_only', 0) == 0) { //check if there isn't any user with this e-mail (whose name is different) $email_for_other_user_query = db_query("SELECT * FROM {users} WHERE mail='%s' AND name <> '%s'", $umail_single, $uname); $email_for_other_user = db_fetch_object($username_and_email_query); if ($email_for_other_user) { drupal_set_message(t("Error saving user account. E-mail address is already used."), 'error'); } else { $user = user_save($user, array('mail' => $umail_single)); } } } } else { //If we have an e-mail address from the shib server, and there isn't any user with this address, create an account with these infos if ($umail_single) { $email_already_used_query = db_query("SELECT * FROM {users} WHERE mail='%s'", $umail_single); $email_already_used = db_fetch_object($email_already_used_query); // If the mail address is used, give an error if ($email_already_used) { drupal_set_message(t("Error saving user account. E-mail address is already used."), 'error'); } else { user_external_login_register($uname, "shib_auth"); $_SESSION['authentication'] = 'shib_auth'; $user = user_save($user, array('mail' => $umail_single)); } } else { if (variable_get('shib_auth_mail_shib_only', 0) == 0) { $message = t('E-mail address is missing. Please contact your Shibboleth administrator!'); drupal_set_message($message, "error"); watchdog('shib_auth', $message, WATCHDOG_CRITICAL); } else { // if the custom mail was enabled on the admin form if ($_POST['form_id'] == 'shib_auth_custom_email' && $_POST['custom_mail']) { $custom_mail = $_POST['custom_mail']; } //if the user provided the custom mail string, and it is not empty if (isset($custom_mail) && $custom_mail) { // and it isn't used by another registered drupal user $email_already_used_query = db_query("SELECT * FROM {users} WHERE mail='%s'", $custom_mail); $email_already_used = db_fetch_object($email_already_used_query); if ($email_already_used) { drupal_set_message(t("Error saving user account. E-mail address is already used."), 'error'); } else { user_external_login_register($uname, "shib_auth"); $_SESSION['authentication'] = 'shib_auth'; $user = user_save($user, array('mail' => $custom_mail)); } //then the user is redirected to the page, which she wanted to open before the auth process had been initiated if (isset($_SESSION['redirected_to_custom_mail_form_url'])) { $redirect_url = $_SESSION['redirected_to_custom_mail_form_url']; unset($_SESSION['redirected_to_custom_mail_form_url']); drupal_goto($redirect_url); } } else { $_SESSION['redirected_to_custom_mail_form'] = TRUE; $_SESSION['redirected_to_custom_mail_form_url'] = $_GET['q']; drupal_goto('shib_auth/get_custom_mail'); } } } } } } } //The admin can define authorization rules based on the server variables - which are provided by Shibboleth - //to give roles to users, if the IdP provide certain authorization or authentication string //the rules can be defined as a server field - Regexp - role(s) trio // Store rules for further examination $former_rules = serialize($user->roles); // Examine all previously saved rule $rules = db_query("SELECT * FROM {shib_auth}"); while ($rule = db_fetch_array($rules)) { $fieldname = $rule['field']; $expression = '/' . urldecode($rule['regexpression']) . '/'; //check out, if the given server field exists if (isset($_SERVER[$fieldname])) { foreach (explode(';', $_SERVER[$fieldname]) as $value) { //check if the RegEx can be fit to one of the value of the server field if (preg_match($expression, trim($value))) { $roles = unserialize(urldecode($rule['role'])); //if there is a match, give this user the specified role(s) if (!empty($roles)) { foreach ($roles as $key => $value) { $user->roles[$key] = $value; } } } } } } $user->roles = array_filter($user->roles); // If the user roles array has been changed then reset the permission cache if (serialize($user->roles) != $former_rules) { // Hack to reset the permissions user_access('access content', $account, TRUE); } }
public function postAuthenticate() { if ($this->disabled) return; $attributes = $this->getIdentity(); \LogHelper::log_debug('ADFS Attributes'); \LogHelper::log_debug($attributes); if ( $attributes ) { global $user; $roles = array(); $r = user_roles(true); $db_user = db_select('users') ->fields('users', array('uid')) ->condition('name', db_like($attributes[ADFS_EMAIL_SCHEMA][0]), 'LIKE') ->range(0, 1) ->execute() ->fetchField(); if (isset($attributes[ADFS_GROUP_SCHEMA])) { $groups = $attributes[ADFS_GROUP_SCHEMA]; $defaultDatasource = null; foreach ($groups as $group) { if (isset($this->roleMappings[$group])) { foreach ($this->roleMappings[$group] as $role) { $roles[array_search($role, $r)] = TRUE; } } if (!isset($defaultDatasource) && isset($this->dsMappings[$group])) { $defaultDatasource = $this->dsMappings[$group][0]; } } foreach ($this->requiredGroups as $requiredGroup) { if (!in_array($requiredGroup, $groups)) { drupal_goto('forbidden'); } } } if (isset($defaultDatasource)) { $datasources = gd_datasource_get_all(); foreach ($datasources as $ds) { if ($ds->publicName == $defaultDatasource) { $defaultDatasource = $ds->name; break; } } } // Load user if it exists if ((bool) $db_user) { $u = user_load($db_user); // If user is blocked if ($u->status == 0) { drupal_goto('forbidden'); } foreach ($u->roles as $role) { if (in_array($role, $r)) { $roles[array_search($role, $r)] = TRUE; } } // Keep user roles the same. Sync the first and last name from ADFS $info = array( 'roles' => $roles, 'mail' => $attributes[ADFS_EMAIL_SCHEMA][0], 'field_gd_user_first_name' => array( LANGUAGE_NONE => array( 0 => array( 'value' => $attributes[ADFS_COMMON_NAME_SCHEMA][0] ) ) ), 'field_gd_user_last_name' => array( LANGUAGE_NONE => array( 0 => array( 'value' => $attributes[ADFS_SURNAME_SCHEMA][0] ) ) ) ); $user = user_save($u, $info); } else if ($this->autoCreate) { // Always give new users the authenticated user role $roles[array_search('authenticated user', $r)] = TRUE; $info = array( 'name' => $attributes[ADFS_EMAIL_SCHEMA][0], 'pass' => user_password(), 'mail' => $attributes[ADFS_EMAIL_SCHEMA][0], 'status' => 1, 'roles' => $roles, 'field_gd_user_first_name' => array( LANGUAGE_NONE => array( 0 => array( 'value' => $attributes[ADFS_COMMON_NAME_SCHEMA][0] ) ) ), 'field_gd_user_last_name' => array( LANGUAGE_NONE => array( 0 => array( 'value' => $attributes[ADFS_SURNAME_SCHEMA][0] ) ) ) ); $user = user_save(drupal_anonymous_user(), $info); } else { $message = t('Unauthorized account: @email', array('@email' => $attributes[ADFS_EMAIL_SCHEMA][0])); \LogHelper::log_error($message); drupal_goto('forbidden'); } user_login_finalize($info); if (isset($defaultDatasource)) { gd_datasource_set_active($defaultDatasource); } } }
function install($config) { global $installDirPath; // create database if does not exists $this->createDatabaseIfNotExists($config['mysql']['server'], $config['mysql']['username'], $config['mysql']['password'], $config['mysql']['database']); global $installDirPath; // Build database require_once $installDirPath . 'civicrm.php'; civicrm_main($config); if (!$this->errors) { global $installType, $installURLPath; $output = NULL; if ($installType == 'drupal' && version_compare(VERSION, '7.0-rc1') >= 0) { // clean output @ob_clean(); $output .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'; $output .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'; $output .= '<head>'; $output .= '<title>CiviCRM Installed</title>'; $output .= '<link rel="stylesheet" type="text/css" href="template.css" />'; $output .= '</head>'; $output .= '<body>'; $output .= '<div style="padding: 1em;"><p class="good">CiviCRM has been successfully installed</p>'; $output .= '<ul>'; $docLinkConfig = CRM_Utils_System::docURL2('Configuring a New Site', FALSE, 'here', NULL, NULL, "wiki"); if (!function_exists('ts')) { $docLinkConfig = "<a href=\"{$docLinkConfig}\">here</a>"; } $drupalURL = civicrm_cms_base(); $drupalPermissionsURL = "{$drupalURL}index.php?q=admin/people/permissions"; $drupalURL .= "index.php?q=civicrm/admin/configtask&reset=1"; $registerSiteURL = "http://civicrm.org/civicrm/profile/create?reset=1&gid=15"; $output .= "<li>Drupal user permissions have been automatically set - giving anonymous and authenticated users access to public CiviCRM forms and features. We recommend that you <a target='_blank' href={$drupalPermissionsURL}>review these permissions</a> to ensure that they are appropriate for your requirements (<a target='_blank' href='http://wiki.civicrm.org/confluence/display/CRMDOC/Default+Permissions+and+Roles'>learn more...</a>)</li>\n <li>Use the <a target='_blank' href=\"{$drupalURL}\">Configuration Checklist</a> to review and configure settings for your new site</li>\n <li> Have you registered this site at CiviCRM.org? If not, please help strengthen the CiviCRM ecosystem by taking a few minutes to <a href='{$registerSiteURL}' target='_blank'>fill out the site registration form</a>. The information collected will help us prioritize improvements, target our communications and build the community. If you have a technical role for this site, be sure to check Keep in Touch to receive technical updates (a low volume mailing list).</li>\n <li>We have integrated KCFinder with CKEditor and TinyMCE, which enables user to upload images. Note that all the images uploaded using KCFinder will be public.</li>"; // automatically enable CiviCRM module once it is installed successfully. // so we need to Bootstrap Drupal, so that we can call drupal hooks. global $cmsPath, $crmPath; // relative / abosolute paths are not working for drupal, hence using chdir() chdir($cmsPath); include_once "./includes/bootstrap.inc"; include_once "./includes/unicode.inc"; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); // prevent session information from being saved. drupal_save_session(FALSE); // Force the current user to anonymous. $original_user = $GLOBALS['user']; $GLOBALS['user'] = drupal_anonymous_user(); // explicitly setting error reporting, since we cannot handle drupal related notices error_reporting(1); // rebuild modules, so that civicrm is added system_rebuild_module_data(); // now enable civicrm module. module_enable(array('civicrm', 'civicrmtheme')); // clear block and page cache, to make sure civicrm link is present in navigation block cache_clear_all(); //add basic drupal permissions civicrm_install_set_drupal_perms(); // restore the user. $GLOBALS['user'] = $original_user; drupal_save_session(TRUE); $output .= '</ul>'; $output .= '</div>'; $output .= '</body>'; $output .= '</html>'; echo $output; } elseif ($installType == 'drupal' && version_compare(VERSION, '6.0') >= 0) { // clean output @ob_clean(); $output .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'; $output .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'; $output .= '<head>'; $output .= '<title>CiviCRM Installed</title>'; $output .= '<link rel="stylesheet" type="text/css" href="template.css" />'; $output .= '</head>'; $output .= '<body>'; $output .= '<div style="padding: 1em;"><p class="good">CiviCRM has been successfully installed</p>'; $output .= '<ul>'; $docLinkConfig = CRM_Utils_System::docURL2('Configuring a New Site', FALSE, 'here', NULL, NULL, "wiki"); if (!function_exists('ts')) { $docLinkConfig = "<a href=\"{$docLinkConfig}\">here</a>"; } $drupalURL = civicrm_cms_base(); $drupalPermissionsURL = "{$drupalURL}index.php?q=admin/user/permissions"; $drupalURL .= "index.php?q=civicrm/admin/configtask&reset=1"; $registerSiteURL = "http://civicrm.org/civicrm/profile/create?reset=1&gid=15"; $output .= "<li>Drupal user permissions have been automatically set - giving anonymous and authenticated users access to public CiviCRM forms and features. We recommend that you <a target='_blank' href={$drupalPermissionsURL}>review these permissions</a> to ensure that they are appropriate for your requirements (<a target='_blank' href='http://wiki.civicrm.org/confluence/display/CRMDOC/Default+Permissions+and+Roles'>learn more...</a>)</li>\n <li>Use the <a target='_blank' href=\"{$drupalURL}\">Configuration Checklist</a> to review and configure settings for your new site</li>\n <li> Have you registered this site at CiviCRM.org? If not, please help strengthen the CiviCRM ecosystem by taking a few minutes to <a href='{$registerSiteURL}' target='_blank'>fill out the site registration form</a>. The information collected will help us prioritize improvements, target our communications and build the community. If you have a technical role for this site, be sure to check Keep in Touch to receive technical updates (a low volume mailing list).</li>\n <li>We have integrated KCFinder with CKEditor and TinyMCE, which enables user to upload images. Note that all the images uploaded using KCFinder will be public.</li>"; // explicitly setting error reporting, since we cannot handle drupal related notices error_reporting(1); // automatically enable CiviCRM module once it is installed successfully. // so we need to Bootstrap Drupal, so that we can call drupal hooks. global $cmsPath, $crmPath; // relative / abosolute paths are not working for drupal, hence using chdir() chdir($cmsPath); include_once "./includes/bootstrap.inc"; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); // rebuild modules, so that civicrm is added module_rebuild_cache(); // now enable civicrm module. module_enable(array('civicrm')); // clear block and page cache, to make sure civicrm link is present in navigation block cache_clear_all(); //add basic drupal permissions db_query('UPDATE {permission} SET perm = CONCAT( perm, \', access CiviMail subscribe/unsubscribe pages, access all custom data, access uploaded files, make online contributions, profile create, profile edit, profile view, register for events, view event info\') WHERE rid IN (1, 2)'); echo $output; } elseif ($installType == 'wordpress') { echo '<h1>CiviCRM Installed</h1>'; echo '<div style="padding: 1em;"><p style="background-color: #0C0; border: 1px #070 solid; color: white;">CiviCRM has been successfully installed</p>'; echo '<ul>'; $docLinkConfig = CRM_Utils_System::docURL2('Configuring a New Site', FALSE, 'here', NULL, NULL, "wiki"); if (!function_exists('ts')) { $docLinkConfig = "<a href=\"{$docLinkConfig}\">here</a>"; } $cmsURL = civicrm_cms_base(); $cmsURL .= "wp-admin/admin.php?page=CiviCRM&q=civicrm/admin/configtask&reset=1"; $registerSiteURL = "http://civicrm.org/civicrm/profile/create?reset=1&gid=15"; echo "<li>Use the <a target='_blank' href=\"{$cmsURL}\">Configuration Checklist</a> to review and configure settings for your new site</li>\n <li> Have you registered this site at CiviCRM.org? If not, please help strengthen the CiviCRM ecosystem by taking a few minutes to <a href='{$registerSiteURL}' target='_blank'>fill out the site registration form</a>. The information collected will help us prioritize improvements, target our communications and build the community. If you have a technical role for this site, be sure to check Keep in Touch to receive technical updates (a low volume mailing list).</li>\n <li>We have integrated KCFinder with CKEditor and TinyMCE, which enables user to upload images. Note that all the images uploaded using KCFinder will be public.</li>"; echo '</ul>'; echo '</div>'; } } return $this->errors; }
/** * Default constructor. */ public function __construct() { global $user, $is_https; $this->httpsEnabled = $this->handleHttps() && $is_https; $this->sessionName = session_name(); if ($this->httpsEnabled) { $this->sessionNameUnsecure = substr(session_name(), 1); } if (!empty($_COOKIE[$this->sessionName]) || $this->httpsEnabled && !empty($_COOKIE[$this->sessionNameUnsecure])) { // If a session cookie exists, initialize the session. Otherwise the // session is only started on demand in drupal_session_commit(), making // anonymous users not use a session cookie unless something is stored in // $_SESSION. This allows HTTP proxies to cache anonymous page views. $this->start(); $this->sessionIdentifier = session_id(); $this->refreshAfterSessionChange(); if ($user->uid || !$this->sessionIsEmpty()) { drupal_page_is_cacheable(FALSE); } } else { // Set a session identifier for this request. This is necessary because // we lazily start sessions at the end of this request, and some // processes (like drupal_get_token()) needs to know the future // session ID in advance. $user = drupal_anonymous_user(); $this->generateSessionIdentifier(); $this->refreshAfterSessionChange(); } }
/** * Authenticate the user against the drupal db * * @param string $name the user name * @param string $password the password for the above user name * @param boolean $loadCMSBootstrap load cms bootstrap? * @param NULL|string $realPath filename of script * * @return mixed false if no auth * array( * contactID, ufID, unique string ) if success * @access public */ static function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) { require_once 'DB.php'; $config = CRM_Core_Config::singleton(); $dbDrupal = DB::connect($config->userFrameworkDSN); if (DB::isError($dbDrupal)) { CRM_Core_Error::fatal("Cannot connect to drupal db via {$config->userFrameworkDSN}, " . $dbDrupal->getMessage()); } $account = $userUid = $userMail = NULL; if ($loadCMSBootstrap) { $bootStrapParams = array(); if ($name && $password) { $bootStrapParams = array('name' => $name, 'pass' => $password); } CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath); global $user; if ($user) { $userUid = $user->uid; $userMail = $user->mail; } } else { // CRM-8638 // SOAP cannot load drupal bootstrap and hence we do it the old way // Contact CiviSMTP folks if we run into issues with this :) $cmsPath = $config->userSystem->cmsRootPath($realPath); require_once "{$cmsPath}/includes/bootstrap.inc"; require_once "{$cmsPath}/includes/password.inc"; $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower'; $name = $dbDrupal->escapeSimple($strtolower($name)); $sql = "\nSELECT u.*\nFROM {$config->userFrameworkUsersTableName} u\nWHERE LOWER(u.name) = '{$name}'\nAND u.status = 1\n"; $query = $dbDrupal->query($sql); $row = $query->fetchRow(DB_FETCHMODE_ASSOC); if ($row) { $fakeDrupalAccount = drupal_anonymous_user(); $fakeDrupalAccount->name = $name; $fakeDrupalAccount->pass = $row['pass']; $passwordCheck = user_check_password($password, $fakeDrupalAccount); if ($passwordCheck) { $userUid = $row['uid']; $userMail = $row['mail']; } } } if ($userUid && $userMail) { CRM_Core_BAO_UFMatch::synchronizeUFMatch($account, $userUid, $userMail, 'Drupal'); $contactID = CRM_Core_BAO_UFMatch::getContactId($userUid); if (!$contactID) { return FALSE; } return array($contactID, $userUid, mt_rand()); } return FALSE; }
function os_poker_buddies_invite_form($form_state) { $form = array(); for ($i = 0; $i < 5; $i++) { $nb = $i + 1; $form["name_" . $nb] = array('#type' => 'textfield', '#title' => $i == 0 ? t("Name") : "", '#prefix' => '<div class="clear"></div><div class="num" ' . ($i == 0 ? "style='margin-top: 14px'" : "") . ' >' . $nb . '</div>'); $form["mail_" . $nb] = array('#type' => 'textfield', '#title' => $i == 0 ? t("E-Mail") : "", '#attributes' => array("class" => "invite_target_mail", "number" => $nb)); } $form["message"] = array('#type' => 'textarea', '#title' => "Message", '#resizable' => FALSE, '#default_value' => isset($form_state['values']['message']) ? $form_state['values']['message'] : t('I just forked out 5.000 chips for you, so we can play together on !site_name ;-). Just click on the link in this e-mail and register!', array('!site_name' => variable_get('site_name', 'Drupal')))); $form["email"] = array('#type' => 'hidden', '#default_value' => ''); $form['submit'] = array('#type' => 'submit', '#value' => t('Send invite'), '#attributes' => array("style" => "display:none;")); $form['f_submit'] = array('#type' => 'markup', '#value' => '<div class="clear"></div><div class="TeaseMore"><div onclick="javascript:os_poker_submit(this, \'os-poker-buddies-invite-form\');" ' . " class='poker_submit big'" . " ><div class='pre'> </div><div class='label'>" . t("Send") . "</div></div></div>"); $cuser = CUserManager::instance()->CurrentUser(); //invite stuff : $remaining_invites = invite_get_remaining_invites($cuser->DrupalUser()); if ($remaining_invites == 0) { // Deny access when NOT resending an invite. drupal_set_message(t("Sorry, you've reached the maximum number of invitations."), 'error'); drupal_goto(referer_uri()); } $form['resent'] = array('#type' => 'value', '#value' => 0); $form['reg_code'] = array('#type' => 'value', '#value' => NULL); if ($remaining_invites != INVITE_UNLIMITED) { $form['remaining_invites'] = array('#type' => 'value', '#value' => $remaining_invites); } // Sender e-mail address. if ($user->uid && variable_get('invite_use_users_email', 0)) { $from = $user->mail; } else { $from = variable_get('site_mail', ini_get('sendmail_from')); } // Personalize displayed e-mail address. // @see http://drupal.org/project/pmail if (module_exists('pmail')) { $from = personalize_email($from); } $form['from'] = array('#type' => 'hidden', '#value' => check_plain($from)); $allow_multiple = user_access('send mass invitations'); if (!$allow_multiple) { drupal_set_message(t("'send mass invitations' permission must be set !"), 'error'); } //user_relationship stuff : $new_user = drupal_anonymous_user(); module_load_include('inc', 'user_relationships_ui', 'user_relationships_ui.forms'); $form += user_relationships_ui_request_form($cuser->uid, $new_user->uid, $form); $form['rtid']['#weight'] = 0; $form['#redirect'] = array("poker/buddies/invitedlist"); return $form; }