shortcut.module 17 KB

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