login_destination.module 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. <?php
  2. /**
  3. * @file
  4. * Control where users are directed to, once they login
  5. */
  6. // Page constants
  7. define('LOGIN_DESTINATION_REDIRECT_NOTLISTED', 0);
  8. define('LOGIN_DESTINATION_REDIRECT_LISTED', 1);
  9. define('LOGIN_DESTINATION_REDIRECT_PHP', 2);
  10. // Destination constants
  11. define('LOGIN_DESTINATION_STATIC', 0);
  12. define('LOGIN_DESTINATION_SNIPPET', 1);
  13. /**
  14. * Implement hook_help().
  15. */
  16. function login_destination_help($path, $arg) {
  17. switch ($path) {
  18. case 'admin/help#login_destination':
  19. $output = '';
  20. $output .= '<h3>' . t('About') . '</h3>';
  21. $output .= '<p>' . t('The Login Destination module allows you to customize the destination that the user is redirected to after logging in, registering to the site, using a one-time login link or logging out. The destination can be an internal page or an external URL. You may specify certain conditions like pages or user roles and make the destination depend upon them. You may also use a PHP snippets to provide custom conditions and destinations. Note that PHP Filter module has to be enabled and you have to be granted the "Use PHP for settings" permissions to be able to enter PHP code.') . '</p>';
  22. return $output;
  23. case 'admin/config/people/login-destination':
  24. return '<p>' . t('Login destination rules are evaluated each time a user logs in, registers to the site, uses a one-time login link or logs out. Each rule consists of the destination, path conditions and user roles conditions. First matching rule gets executed.') . '</p>';
  25. }
  26. }
  27. /**
  28. * Implements hook_menu().
  29. */
  30. function login_destination_menu() {
  31. $items['admin/config/people/login-destination'] = array(
  32. 'title' => 'Login destinations',
  33. 'description' => 'Customize the destination that the user is redirected to after login.',
  34. 'page callback' => 'login_destination_overview',
  35. 'access arguments' => array('administer users'),
  36. 'file' => 'login_destination.admin.inc',
  37. 'weight' => 10,
  38. );
  39. $items['admin/config/people/login-destination/add'] = array(
  40. 'title' => 'Add login destination rule',
  41. 'page callback' => 'drupal_get_form',
  42. 'page arguments' => array('login_destination_edit_form'),
  43. 'access arguments' => array('administer users'),
  44. 'type' => MENU_LOCAL_ACTION,
  45. 'weight' => 1,
  46. 'file' => 'login_destination.admin.inc',
  47. );
  48. $items['admin/config/people/login-destination/edit/%login_destination'] = array(
  49. 'title' => 'Edit login destination rule',
  50. 'page callback' => 'drupal_get_form',
  51. 'page arguments' => array('login_destination_edit_form', 5),
  52. 'access arguments' => array('administer users'),
  53. 'file' => 'login_destination.admin.inc',
  54. );
  55. $items['admin/config/people/login-destination/delete/%login_destination'] = array(
  56. 'title' => 'Delete login destination rule',
  57. 'page callback' => 'drupal_get_form',
  58. 'page arguments' => array('login_destination_delete_form', 5),
  59. 'access arguments' => array('administer users'),
  60. 'file' => 'login_destination.admin.inc',
  61. );
  62. $items['admin/config/people/login-destination/list'] = array(
  63. 'title' => 'List',
  64. 'type' => MENU_DEFAULT_LOCAL_TASK,
  65. 'weight' => -10,
  66. );
  67. $items['admin/config/people/login-destination/settings'] = array(
  68. 'title' => 'Settings',
  69. 'description' => 'Change Login Destination settings.',
  70. 'page callback' => 'drupal_get_form',
  71. 'page arguments' => array('login_destination_settings'),
  72. 'access arguments' => array('administer users'),
  73. 'type' => MENU_LOCAL_TASK,
  74. 'file' => 'login_destination.admin.inc',
  75. 'weight' => 10,
  76. );
  77. return $items;
  78. }
  79. /**
  80. * Load a login destination.
  81. */
  82. function login_destination_load($id) {
  83. $result = db_select('login_destination', 'l')
  84. ->fields('l')
  85. ->condition('id', $id)
  86. ->execute()
  87. ->fetchAssoc();
  88. $result['triggers'] = unserialize($result['triggers']);
  89. if (empty($result['triggers'])) {
  90. $result['triggers'] = array();
  91. }
  92. $result['roles'] = unserialize($result['roles']);
  93. if (empty($result['roles'])) {
  94. $result['roles'] = array();
  95. }
  96. return $result;
  97. }
  98. /**
  99. * Implements hook_theme
  100. */
  101. function login_destination_theme() {
  102. return array(
  103. 'login_destination_destination' => array(
  104. 'variables' => array('destination' => NULL),
  105. 'file' => 'login_destination.admin.inc',
  106. ),
  107. 'login_destination_pages' => array(
  108. 'variables' => array('pages' => NULL, 'pages_type' => 0),
  109. 'file' => 'login_destination.admin.inc',
  110. ),
  111. 'login_destination_triggers' => array(
  112. 'variables' => array('items' => NULL),
  113. 'file' => 'login_destination.admin.inc',
  114. ),
  115. 'login_destination_roles' => array(
  116. 'variables' => array('items' => NULL),
  117. 'file' => 'login_destination.admin.inc',
  118. ),
  119. );
  120. }
  121. /**
  122. * Implements hook_form_alter
  123. */
  124. function login_destination_form_alter(&$form, &$form_state, $form_id) {
  125. // We redirect by using the drupal_goto_alter hook. If we simply
  126. // call drupal_goto() it may break compability with other modules. If we set
  127. // the $_GET['destination'] variable we will loose the possibility to redirect
  128. // to an external URL.
  129. // Please note the the system_goto_action() calls drupal_goto()
  130. // More on this issue http://drupal.org/node/732542.
  131. // If we add the $form_state['redirect'] here it will be overriden by the
  132. // user_login_submit(). So we add a submit handler instead and will set the
  133. // redirect later. Our submit handler will be executed after the execution
  134. // of user_login_submit(). This is because form_submit() functions are
  135. // appended to form before hook_form_alter() is executed.
  136. // We will execute also after LoginToboggan's function as it replaces the
  137. // original submit function from user module.
  138. switch ($form_id) {
  139. case 'user_register_form': // user register page
  140. case 'user_login': // user login page
  141. $form['#validate'][] = 'login_destination_validate';
  142. break;
  143. }
  144. switch ($form_id) {
  145. case 'user_profile_form': // one-time login, password reset
  146. if (isset($_GET['pass-reset-token'])) {
  147. // Redirect only from user_pass_reset
  148. // You have to explicitally turn on the option to always redirect from
  149. // the profile page. This is for constistency.
  150. $form['#submit'][] = 'login_destination_submit';
  151. break;
  152. }
  153. }
  154. }
  155. /**
  156. * Helper submit function.
  157. */
  158. function login_destination_validate($form, &$form_state) {
  159. // LoginToboggan's unified page is rendered dynamically. Fix it.
  160. switch ($form['#form_id']) {
  161. case 'user_register_form':
  162. if (drupal_match_path($_GET['q'], 'user')) {
  163. $_GET['q'] = 'user/register';
  164. }
  165. break;
  166. case 'user_login':
  167. if (drupal_match_path($_GET['q'], 'user/register')) {
  168. $_GET['q'] = 'user';
  169. }
  170. break;
  171. }
  172. // Fix the current page in case of 403 page.
  173. if ($form['#form_id'] == 'user_login') {
  174. if(drupal_get_http_header('Status') == '403 Forbidden') {
  175. $_GET['current'] = $_GET['destination'];
  176. }
  177. }
  178. }
  179. /**
  180. * Helper submit function.
  181. */
  182. function login_destination_submit($form, &$form_state) {
  183. login_destination_perform_redirect('login');
  184. }
  185. /**
  186. * Implements hook_menu_link_alter
  187. */
  188. function login_destination_menu_link_alter(&$item) {
  189. // Flag a link to be altered by hook_translated_menu_link_alter().
  190. // This is called only on menu rebuild, so we have to add this information
  191. // manually to the database on install. Clearing caches also helps.
  192. $paths = array('user/logout', 'user/login', 'user');
  193. if (in_array($item['link_path'], $paths)) {
  194. $item['options']['alter'] = TRUE;
  195. }
  196. }
  197. /**
  198. * Implements hook_translated_menu_link_alter
  199. */
  200. function login_destination_translated_menu_link_alter(&$item, $map) {
  201. global $user;
  202. $paths = array('user/login', 'user');
  203. // Append the current path to URL.
  204. if ($item['link_path'] == 'user/logout' || (in_array($item['link_path'], $paths) && user_is_anonymous())) {
  205. $item['localized_options']['query'] = array('current' => $_GET['q']);
  206. }
  207. }
  208. /**
  209. * Implements hook_page_alter
  210. */
  211. function login_destination_page_alter(&$page) {
  212. // Substitute toolbar's pre_render function to change links.
  213. if (isset($page['page_top']['toolbar']['#pre_render'])) {
  214. $page['page_top']['toolbar']['#pre_render'][0] = 'login_destination_toolbar_pre_render';
  215. }
  216. }
  217. /**
  218. * Helper function to change toolbar's links.
  219. */
  220. function login_destination_toolbar_pre_render($toolbar) {
  221. $toolbar = toolbar_pre_render($toolbar);
  222. // Add current param to be able to evaluate previous page.
  223. $toolbar['toolbar_user']['#links']['logout']['query'] = array('current' => $_GET['q']);
  224. return $toolbar;
  225. }
  226. /**
  227. * Implements hook_user_login
  228. */
  229. function login_destination_user_login(&$edit, $account) {
  230. if (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset' || variable_get('login_destination_immediate_redirect', FALSE)) {
  231. login_destination_perform_redirect('login');
  232. }
  233. }
  234. /**
  235. * Implements hook_user_insert
  236. */
  237. function login_destination_user_insert(&$edit, $account, $category) {
  238. global $user;
  239. if (!$user->uid) {
  240. // If the user is already logged in, it means probably that they create a
  241. // user account and not the user registers themselves.
  242. login_destination_perform_redirect('login');
  243. }
  244. }
  245. /**
  246. * Implements hook_user_logout
  247. */
  248. function login_destination_user_logout($account) {
  249. login_destination_perform_redirect('logout', _login_destination_get_current('logout'));
  250. }
  251. /**
  252. * Implements hook_drupal_goto_alter
  253. */
  254. function login_destination_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  255. // Note that this functionality cannot be backported do 6.x as Drupal 6 does
  256. // not call drupal_alter for drupal_goto.
  257. // This actually may be used also by templates.
  258. if (isset($GLOBALS['destination'])) {
  259. $destination = $GLOBALS['destination'];
  260. // alter drupal_goto
  261. if (is_array($destination)) {
  262. $path = $destination[0];
  263. $options = array();
  264. if (count($destination) > 1) {
  265. $options = $destination[1];
  266. }
  267. }
  268. else {
  269. $path = $destination;
  270. }
  271. }
  272. }
  273. /**
  274. * Pass destination to drupal_goto.
  275. */
  276. function login_destination_prepare_goto($destination) {
  277. // Check if $_GET['destination'] should overwrite us
  278. if (!isset($_GET['destination']) || !variable_get('login_destination_preserve_destination', FALSE)) {
  279. $GLOBALS['destination'] = $destination;
  280. }
  281. }
  282. /**
  283. * Evaluate rules and perform redirect.
  284. * This function is intended to be used by external modules.
  285. * @param <type> $trigger
  286. * @param <type> $current if null $_GET['q'] is used
  287. */
  288. function login_destination_perform_redirect($trigger = '', $current = NULL) {
  289. $destination = login_destination_get_destination($trigger, $current);
  290. // Check if we redirect
  291. if ($destination !== FALSE) {
  292. login_destination_prepare_goto($destination);
  293. }
  294. }
  295. /**
  296. * Process all destination rules and return destination path.
  297. * This function is intended to be used by external modules.
  298. */
  299. function login_destination_get_destination($trigger = '', $current = NULL) {
  300. // Get all the login destination rules from the database.
  301. $result = db_select('login_destination', 'l')
  302. //->addTag('translatable')
  303. ->fields('l', array('triggers', 'roles', 'pages_type', 'pages', 'destination_type', 'destination'))
  304. ->orderBy('weight')
  305. ->execute()
  306. ->fetchAll();
  307. if ($current == NULL) {
  308. $current = $_GET['q'];
  309. }
  310. // examine path matches
  311. foreach ($result as $data) {
  312. // try to match the subsequent rule
  313. if (_login_destination_match_rule($data, $trigger, $current)) {
  314. // Note: Matching rule with empty destination will cancel redirect.
  315. return _login_destination_evaluate_rule($data, $trigger);
  316. }
  317. }
  318. // no rule matched
  319. return FALSE;
  320. }
  321. /**
  322. * Evaluate the code with forms context.
  323. *
  324. * This function hides the calling function's scope from eval().
  325. */
  326. function _login_destination_eval($code) {
  327. // We could use the php_eval(), but would not be able get array return value.
  328. // We always check for the existance of PHP Filter module for security.
  329. return eval('?>' . $code);
  330. }
  331. /**
  332. * A helper function to provide role options
  333. */
  334. function _login_destination_role_options() {
  335. // user role selection, without anonymous and authentificated user roles.
  336. $role_options = array_map('check_plain', user_roles(TRUE));
  337. unset($role_options[DRUPAL_AUTHENTICATED_RID]);
  338. return $role_options;
  339. }
  340. /**
  341. * Get the current path (before trigger was invoked).
  342. */
  343. function _login_destination_get_current($trigger = '') {
  344. if (isset($_GET['current'])) {
  345. return check_plain($_GET['current']);
  346. }
  347. if ($trigger == 'login') {
  348. return $_GET['q'];
  349. }
  350. // front by default
  351. return '';
  352. }
  353. /**
  354. * A helper function to determine whether redirection should happen.
  355. *
  356. * @return bool TRUE - apply redirect, FALSE - not to apply redirect.
  357. */
  358. function _login_destination_match_rule($rule, $trigger = '', $current = NULL) {
  359. global $user;
  360. $type = $rule->pages_type;
  361. $pages = $rule->pages;
  362. $triggers = unserialize($rule->triggers);
  363. if (empty($triggers))
  364. $triggers = array();
  365. $roles = unserialize($rule->roles);
  366. if (empty($roles))
  367. $roles = array();
  368. // remove non-existent roles
  369. $roles = array_intersect_key(_login_destination_role_options(), $roles);
  370. // examine trigger match
  371. if (!(empty($triggers) || array_key_exists($trigger, $triggers))) {
  372. return FALSE;
  373. }
  374. // examine role matches
  375. $roles_intersect = array_intersect_key($roles, $user->roles);
  376. if (!empty($roles) && empty($roles_intersect)) {
  377. return FALSE;
  378. }
  379. if ($type < LOGIN_DESTINATION_REDIRECT_PHP) {
  380. $pages = drupal_strtolower($pages);
  381. $alias = drupal_strtolower(drupal_get_path_alias($current));
  382. $page_match = drupal_match_path($alias, $pages);
  383. if ($alias != $current) {
  384. $page_match = $page_match || drupal_match_path($current, $pages);
  385. }
  386. $page_match = !($type xor $page_match);
  387. }
  388. elseif (module_exists('php')) {
  389. // Do not execute php if the PHP Filter is off.
  390. $page_match = _login_destination_eval($pages);
  391. }
  392. else {
  393. $page_match = FALSE;
  394. }
  395. return $page_match;
  396. }
  397. /**
  398. * A helper function to evaluate destination path.
  399. */
  400. function _login_destination_evaluate_rule($rule, $trigger = '') {
  401. if ($rule->destination_type == LOGIN_DESTINATION_STATIC) {
  402. // take only 1st line
  403. if (preg_match("!^(.*?)$!", $rule->destination, $matches) === 1 ) {
  404. $path = $matches[1];
  405. if (empty($path)) {
  406. return FALSE;
  407. }
  408. // Current path
  409. elseif ($path == '<current>') {
  410. return _login_destination_get_current($trigger);
  411. }
  412. // External URL
  413. elseif (strpos($path, '://') !== FALSE) {
  414. return $path;
  415. }
  416. // Internal URL
  417. else {
  418. $destination = drupal_parse_url($path);
  419. $options = array();
  420. $options['query'] = $destination['query'];
  421. $options['fragment'] = $destination['fragment'];
  422. // drupal_goto cares about <front>
  423. return array($destination['path'], $options);
  424. }
  425. }
  426. else {
  427. // error - multiple lines
  428. return '';
  429. }
  430. }
  431. elseif (module_exists('php')) {
  432. // We cannot use the php_eval because we expect array here, but for the
  433. // matter of consistent UI we don't do it with the PHP Filter module off.
  434. $result = _login_destination_eval($rule->destination);
  435. if (empty($result)) {
  436. return FALSE;
  437. }
  438. return $result;
  439. }
  440. else {
  441. // PHP code and PHP filter disabled.
  442. return FALSE;
  443. }
  444. }