shortcut.module 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. <?php
  2. /**
  3. * @file
  4. * Allows users to manage customizable lists of shortcut links.
  5. */
  6. use Drupal\Component\Render\FormattableMarkup;
  7. use Drupal\Core\Access\AccessResult;
  8. use Drupal\Core\Cache\Cache;
  9. use Drupal\Core\Routing\RouteMatchInterface;
  10. use Drupal\Core\Url;
  11. use Drupal\shortcut\Entity\ShortcutSet;
  12. use Drupal\shortcut\ShortcutSetInterface;
  13. /**
  14. * Implements hook_help().
  15. */
  16. function shortcut_help($route_name, RouteMatchInterface $route_match) {
  17. switch ($route_name) {
  18. case 'help.page.shortcut':
  19. $output = '<h3>' . t('About') . '</h3>';
  20. $output .= '<p>' . t('The Shortcut module allows users to create sets of <em>shortcut</em> links to commonly-visited pages of the site. Shortcuts are contained within <em>sets</em>. Each user with <em>Select any shortcut set</em> permission can select a shortcut set created by anyone at the site. For more information, see the <a href=":shortcut">online documentation for the Shortcut module</a>.', [':shortcut' => 'https://www.drupal.org/documentation/modules/shortcut']) . '</p>';
  21. $output .= '<h3>' . t('Uses') . '</h3>';
  22. $output .= '<dl><dt>' . t('Administering shortcuts') . '</dt>';
  23. $output .= '<dd>' . t('Users with the <em>Administer shortcuts</em> permission can manage shortcut sets and edit the shortcuts within sets from the <a href=":shortcuts">Shortcuts administration page</a>.', [':shortcuts' => \Drupal::url('entity.shortcut_set.collection')]) . '</dd>';
  24. $output .= '<dt>' . t('Choosing shortcut sets') . '</dt>';
  25. $output .= '<dd>' . t('Users with permission to switch shortcut sets can choose a shortcut set to use from the Shortcuts tab of their user account page.') . '</dd>';
  26. $output .= '<dt>' . t('Adding and removing shortcuts') . '</dt>';
  27. $output .= '<dd>' . t('The Shortcut module creates an add/remove link for each page on your site; the link lets you add or remove the current page from the currently-enabled set of shortcuts (if your theme displays it and you have permission to edit your shortcut set). The core Seven administration theme displays this link next to the page title, as a grey or yellow star. If you click on the grey star, you will add that page to your preferred set of shortcuts. If the page is already part of your shortcut set, the link will be a yellow star, and will allow you to remove the current page from your shortcut set.') . '</dd>';
  28. $output .= '<dt>' . t('Displaying shortcuts') . '</dt>';
  29. $output .= '<dd>' . t('You can display your shortcuts by enabling the <em>Shortcuts</em> block on the <a href=":blocks">Blocks administration page</a>. Certain administrative modules also display your shortcuts; for example, the core <a href=":toolbar-help">Toolbar module</a> provides a corresponding menu item.', [':blocks' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#', ':toolbar-help' => (\Drupal::moduleHandler()->moduleExists('toolbar')) ? \Drupal::url('help.page', ['name' => 'toolbar']) : '#']) . '</dd>';
  30. $output .= '</dl>';
  31. return $output;
  32. case 'entity.shortcut_set.collection':
  33. case 'shortcut.set_add':
  34. case 'entity.shortcut_set.edit_form':
  35. $user = \Drupal::currentUser();
  36. if ($user->hasPermission('access shortcuts') && $user->hasPermission('switch shortcut sets')) {
  37. $output = '<p>' . t('Define which shortcut set you are using on the <a href=":shortcut-link">Shortcuts tab</a> of your account page.', [':shortcut-link' => \Drupal::url('shortcut.set_switch', ['user' => $user->id()])]) . '</p>';
  38. return $output;
  39. }
  40. }
  41. }
  42. /**
  43. * Access callback for editing a shortcut set.
  44. *
  45. * @param Drupal\shortcut\ShortcutSetInterface $shortcut_set
  46. * (optional) The shortcut set to be edited. If not set, the current user's
  47. * shortcut set will be used.
  48. *
  49. * @return \Drupal\Core\Access\AccessResultInterface
  50. * The access result.
  51. */
  52. function shortcut_set_edit_access(ShortcutSetInterface $shortcut_set = NULL) {
  53. $account = \Drupal::currentUser();
  54. // Shortcut administrators can edit any set.
  55. if ($account->hasPermission('administer shortcuts')) {
  56. return AccessResult::allowed()->cachePerPermissions();
  57. }
  58. // Sufficiently-privileged users can edit their currently displayed shortcut
  59. // set, but not other sets. They must also be able to access shortcuts.
  60. $may_edit_current_shortcut_set = $account->hasPermission('customize shortcut links') && (!isset($shortcut_set) || $shortcut_set == shortcut_current_displayed_set()) && $account->hasPermission('access shortcuts');
  61. $result = AccessResult::allowedIf($may_edit_current_shortcut_set)->cachePerPermissions();
  62. if (!$result->isAllowed()) {
  63. $result->setReason("The shortcut set must be the currently displayed set for the user and the user must have 'access shortcuts' AND 'customize shortcut links' permissions.");
  64. }
  65. return $result;
  66. }
  67. /**
  68. * Access callback for switching the shortcut set assigned to a user account.
  69. *
  70. * @param object $account
  71. * (optional) The user account whose shortcuts will be switched. If not set,
  72. * permissions will be checked for switching the logged-in user's own
  73. * shortcut set.
  74. *
  75. * @return \Drupal\Core\Access\AccessResultInterface
  76. * The access result.
  77. */
  78. function shortcut_set_switch_access($account = NULL) {
  79. $user = \Drupal::currentUser();
  80. if ($user->hasPermission('administer shortcuts')) {
  81. // Administrators can switch anyone's shortcut set.
  82. return AccessResult::allowed()->cachePerPermissions();
  83. }
  84. if (!$user->hasPermission('access shortcuts')) {
  85. // The user has no permission to use shortcuts.
  86. return AccessResult::neutral()->cachePerPermissions();
  87. }
  88. if (!$user->hasPermission('switch shortcut sets')) {
  89. // The user has no permission to switch anyone's shortcut set.
  90. return AccessResult::neutral()->cachePerPermissions();
  91. }
  92. // Users with the 'switch shortcut sets' permission can switch their own
  93. // shortcuts sets.
  94. if (!isset($account)) {
  95. return AccessResult::allowed()->cachePerPermissions();
  96. }
  97. elseif ($user->id() == $account->id()) {
  98. return AccessResult::allowed()->cachePerPermissions()->cachePerUser();
  99. }
  100. // No opinion.
  101. return AccessResult::neutral()->cachePerPermissions();
  102. }
  103. /**
  104. * Assigns a user to a particular shortcut set.
  105. *
  106. * @param $shortcut_set Drupal\shortcut\Entity\Shortcut
  107. * An object representing the shortcut set.
  108. * @param $account
  109. * A user account that will be assigned to use the set.
  110. *
  111. * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
  112. * Use \Drupal::entityManager()->getStorage('shortcut_set')->assignUser().
  113. */
  114. function shortcut_set_assign_user($shortcut_set, $account) {
  115. \Drupal::entityManager()
  116. ->getStorage('shortcut_set')
  117. ->assignUser($shortcut_set, $account);
  118. }
  119. /**
  120. * Unassigns a user from any shortcut set they may have been assigned to.
  121. *
  122. * The user will go back to using whatever default set applies.
  123. *
  124. * @param $account
  125. * A user account that will be removed from the shortcut set assignment.
  126. *
  127. * @return
  128. * TRUE if the user was previously assigned to a shortcut set and has been
  129. * successfully removed from it. FALSE if the user was already not assigned
  130. * to any set.
  131. *
  132. * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
  133. * Use \Drupal::entityManager()->getStorage('shortcut_set')->unassignUser().
  134. */
  135. function shortcut_set_unassign_user($account) {
  136. return (bool) \Drupal::entityManager()
  137. ->getStorage('shortcut_set')
  138. ->unassignUser($account);
  139. }
  140. /**
  141. * Returns the current displayed shortcut set for the provided user account.
  142. *
  143. * @param $account
  144. * (optional) The user account whose shortcuts will be returned. Defaults to
  145. * the currently logged-in user.
  146. *
  147. * @return
  148. * An object representing the shortcut set that should be displayed to the
  149. * current user. If the user does not have an explicit shortcut set defined,
  150. * the default set is returned.
  151. */
  152. function shortcut_current_displayed_set($account = NULL) {
  153. $shortcut_sets = &drupal_static(__FUNCTION__, []);
  154. $user = \Drupal::currentUser();
  155. if (!isset($account)) {
  156. $account = $user;
  157. }
  158. // Try to return a shortcut set from the static cache.
  159. if (isset($shortcut_sets[$account->id()])) {
  160. return $shortcut_sets[$account->id()];
  161. }
  162. // If none was found, try to find a shortcut set that is explicitly assigned
  163. // to this user.
  164. $shortcut_set_name = \Drupal::entityManager()
  165. ->getStorage('shortcut_set')
  166. ->getAssignedToUser($account);
  167. if ($shortcut_set_name) {
  168. $shortcut_set = ShortcutSet::load($shortcut_set_name);
  169. }
  170. // Otherwise, use the default set.
  171. else {
  172. $shortcut_set = shortcut_default_set($account);
  173. }
  174. $shortcut_sets[$account->id()] = $shortcut_set;
  175. return $shortcut_set;
  176. }
  177. /**
  178. * Returns the default shortcut set for a given user account.
  179. *
  180. * @param object $account
  181. * (optional) The user account whose default shortcut set will be returned.
  182. * If not provided, the function will return the currently logged-in user's
  183. * default shortcut set.
  184. *
  185. * @return
  186. * An object representing the default shortcut set.
  187. */
  188. function shortcut_default_set($account = NULL) {
  189. $user = \Drupal::currentUser();
  190. if (!isset($account)) {
  191. $account = $user;
  192. }
  193. // Allow modules to return a default shortcut set name. Since we can only
  194. // have one, we allow the last module which returns a valid result to take
  195. // precedence. If no module returns a valid set, fall back on the site-wide
  196. // default, which is the lowest-numbered shortcut set.
  197. $suggestions = array_reverse(\Drupal::moduleHandler()->invokeAll('shortcut_default_set', [$account]));
  198. $suggestions[] = 'default';
  199. foreach ($suggestions as $name) {
  200. if ($shortcut_set = ShortcutSet::load($name)) {
  201. break;
  202. }
  203. }
  204. return $shortcut_set;
  205. }
  206. /**
  207. * Check to see if a shortcut set with the given title already exists.
  208. *
  209. * @param $title
  210. * Human-readable name of the shortcut set to check.
  211. *
  212. * @return
  213. * TRUE if a shortcut set with that title exists; FALSE otherwise.
  214. *
  215. * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
  216. */
  217. function shortcut_set_title_exists($title) {
  218. $sets = ShortcutSet::loadMultiple();
  219. foreach ($sets as $set) {
  220. if ($set->label() == $title) {
  221. return TRUE;
  222. }
  223. }
  224. return FALSE;
  225. }
  226. /**
  227. * Returns an array of shortcut links, suitable for rendering.
  228. *
  229. * @param \Drupal\shortcut\ShortcutSetInterface $shortcut_set
  230. * (optional) An object representing the set whose links will be displayed.
  231. * If not provided, the user's current set will be displayed.
  232. *
  233. * @return \Drupal\shortcut\ShortcutInterface[]
  234. * An array of shortcut links, in the format returned by the menu system.
  235. */
  236. function shortcut_renderable_links($shortcut_set = NULL) {
  237. $shortcut_links = [];
  238. if (!isset($shortcut_set)) {
  239. $shortcut_set = shortcut_current_displayed_set();
  240. }
  241. $cache_tags = [];
  242. foreach ($shortcut_set->getShortcuts() as $shortcut) {
  243. $shortcut = \Drupal::entityManager()->getTranslationFromContext($shortcut);
  244. $url = $shortcut->getUrl();
  245. if ($url->access()) {
  246. $links[$shortcut->id()] = [
  247. 'type' => 'link',
  248. 'title' => $shortcut->label(),
  249. 'url' => $shortcut->getUrl(),
  250. ];
  251. $cache_tags = Cache::mergeTags($cache_tags, $shortcut->getCacheTags());
  252. }
  253. }
  254. if (!empty($links)) {
  255. $shortcut_links = [
  256. '#theme' => 'links__toolbar_shortcuts',
  257. '#links' => $links,
  258. '#attributes' => [
  259. 'class' => ['toolbar-menu'],
  260. ],
  261. '#cache' => [
  262. 'tags' => $cache_tags,
  263. ],
  264. ];
  265. }
  266. return $shortcut_links;
  267. }
  268. /**
  269. * Implements hook_preprocess_HOOK() for block templates.
  270. */
  271. function shortcut_preprocess_block(&$variables) {
  272. if ($variables['configuration']['provider'] == 'shortcut') {
  273. $variables['attributes']['role'] = 'navigation';
  274. }
  275. }
  276. /**
  277. * Implements hook_preprocess_HOOK() for page title templates.
  278. */
  279. function shortcut_preprocess_page_title(&$variables) {
  280. // Only display the shortcut link if the user has the ability to edit
  281. // shortcuts and if the page's actual content is being shown (for example,
  282. // we do not want to display it on "access denied" or "page not found"
  283. // pages).
  284. if (shortcut_set_edit_access()->isAllowed() && !\Drupal::request()->attributes->has('exception')) {
  285. $link = Url::fromRouteMatch(\Drupal::routeMatch())->getInternalPath();
  286. $route_match = \Drupal::routeMatch();
  287. // Replicate template_preprocess_html()'s processing to get the title in
  288. // string form, so we can set the default name for the shortcut.
  289. // Strip HTML tags from the title.
  290. $name = trim(strip_tags(render($variables['title'])));
  291. $query = [
  292. 'link' => $link,
  293. 'name' => $name,
  294. ];
  295. $shortcut_set = shortcut_current_displayed_set();
  296. // Check if $link is already a shortcut and set $link_mode accordingly.
  297. $shortcuts = \Drupal::entityManager()->getStorage('shortcut')->loadByProperties(['shortcut_set' => $shortcut_set->id()]);
  298. /** @var \Drupal\shortcut\ShortcutInterface $shortcut */
  299. foreach ($shortcuts as $shortcut) {
  300. if (($shortcut_url = $shortcut->getUrl()) && $shortcut_url->isRouted() && $shortcut_url->getRouteName() == $route_match->getRouteName() && $shortcut_url->getRouteParameters() == $route_match->getRawParameters()->all()) {
  301. $shortcut_id = $shortcut->id();
  302. break;
  303. }
  304. }
  305. $link_mode = isset($shortcut_id) ? "remove" : "add";
  306. if ($link_mode == "add") {
  307. $link_text = shortcut_set_switch_access()->isAllowed() ? t('Add to %shortcut_set shortcuts', ['%shortcut_set' => $shortcut_set->label()]) : t('Add to shortcuts');
  308. $route_name = 'shortcut.link_add_inline';
  309. $route_parameters = ['shortcut_set' => $shortcut_set->id()];
  310. }
  311. else {
  312. $query['id'] = $shortcut_id;
  313. $link_text = shortcut_set_switch_access()->isAllowed() ? t('Remove from %shortcut_set shortcuts', ['%shortcut_set' => $shortcut_set->label()]) : t('Remove from shortcuts');
  314. $route_name = 'entity.shortcut.link_delete_inline';
  315. $route_parameters = ['shortcut' => $shortcut_id];
  316. }
  317. if (theme_get_setting('third_party_settings.shortcut.module_link')) {
  318. $query += \Drupal::destination()->getAsArray();
  319. $variables['title_suffix']['add_or_remove_shortcut'] = [
  320. '#attached' => [
  321. 'library' => [
  322. 'shortcut/drupal.shortcut',
  323. ],
  324. ],
  325. '#type' => 'link',
  326. '#title' => new FormattableMarkup('<span class="shortcut-action__icon"></span><span class="shortcut-action__message">@text</span>', ['@text' => $link_text]),
  327. '#url' => Url::fromRoute($route_name, $route_parameters),
  328. '#options' => ['query' => $query],
  329. '#attributes' => [
  330. 'class' => [
  331. 'shortcut-action',
  332. 'shortcut-action--' . $link_mode,
  333. ],
  334. ],
  335. ];
  336. }
  337. }
  338. }
  339. /**
  340. * Implements hook_toolbar().
  341. */
  342. function shortcut_toolbar() {
  343. $user = \Drupal::currentUser();
  344. $items = [];
  345. $items['shortcuts'] = [
  346. '#cache' => [
  347. 'contexts' => [
  348. // Cacheable per user, because each user can have their own shortcut
  349. // set, even if they cannot create or select a shortcut set, because
  350. // an administrator may have assigned a non-default shortcut set.
  351. 'user',
  352. ],
  353. ],
  354. ];
  355. if ($user->hasPermission('access shortcuts')) {
  356. $links = shortcut_renderable_links();
  357. $shortcut_set = shortcut_current_displayed_set();
  358. \Drupal::service('renderer')->addCacheableDependency($items['shortcuts'], $shortcut_set);
  359. $configure_link = NULL;
  360. if (shortcut_set_edit_access($shortcut_set)->isAllowed()) {
  361. $configure_link = [
  362. '#type' => 'link',
  363. '#title' => t('Edit shortcuts'),
  364. '#url' => Url::fromRoute('entity.shortcut_set.customize_form', ['shortcut_set' => $shortcut_set->id()]),
  365. '#options' => ['attributes' => ['class' => ['edit-shortcuts']]],
  366. ];
  367. }
  368. if (!empty($links) || !empty($configure_link)) {
  369. $items['shortcuts'] += [
  370. '#type' => 'toolbar_item',
  371. 'tab' => [
  372. '#type' => 'link',
  373. '#title' => t('Shortcuts'),
  374. '#url' => $shortcut_set->urlInfo('collection'),
  375. '#attributes' => [
  376. 'title' => t('Shortcuts'),
  377. 'class' => ['toolbar-icon', 'toolbar-icon-shortcut'],
  378. ],
  379. ],
  380. 'tray' => [
  381. '#heading' => t('User-defined shortcuts'),
  382. 'shortcuts' => $links,
  383. 'configure' => $configure_link,
  384. ],
  385. '#weight' => -10,
  386. '#attached' => [
  387. 'library' => [
  388. 'shortcut/drupal.shortcut',
  389. ],
  390. ],
  391. ];
  392. }
  393. }
  394. return $items;
  395. }
  396. /**
  397. * Implements hook_themes_installed().
  398. */
  399. function shortcut_themes_installed($theme_list) {
  400. if (in_array('seven', $theme_list)) {
  401. // Theme settings are not configuration entities and cannot depend on modules
  402. // so to set a module-specific setting, we need to set it with logic.
  403. if (\Drupal::moduleHandler()->moduleExists('shortcut')) {
  404. \Drupal::configFactory()->getEditable('seven.settings')->set('third_party_settings.shortcut.module_link', TRUE)->save(TRUE);
  405. }
  406. }
  407. }