login_destination.module 16 KB

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