Projet

Général

Profil

Paste
Télécharger (31 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / admin_menu / admin_menu.module @ 74f6bef0

1
<?php
2

    
3
/**
4
 * @file
5
 * Render an administrative menu as a dropdown menu at the top of the window.
6
 */
7

    
8
/**
9
 * Implements hook_help().
10
 */
11
function admin_menu_help($path, $arg) {
12
  switch ($path) {
13
    case 'admin/config/administration/admin_menu':
14
      return '<p>' . t('The administration menu module provides a dropdown menu arranged for one- or two-click access to most administrative tasks and other common destinations (to users with the proper permissions). Use the settings below to customize the appearance of the menu.') . '</p>';
15

    
16
    case 'admin/help#admin_menu':
17
      $output = '';
18
      $output .= '<p>' . t('The administration menu module provides a dropdown menu arranged for one- or two-click access to most administrative tasks and other common destinations (to users with the proper permissions). Administration menu also displays the number of anonymous and authenticated users, and allows modules to add their own custom menu items. Integration with the menu varies from module to module; the contributed module <a href="@drupal">Devel</a>, for instance, makes strong use of the administration menu module to provide quick access to development tools.', array('@drupal' => 'http://drupal.org/project/devel')) . '</p>';
19
      $output .= '<p>' . t('The administration menu <a href="@settings">settings page</a> allows you to modify some elements of the menu\'s behavior and appearance. Since the appearance of the menu is dependent on your site theme, substantial customizations require modifications to your site\'s theme and CSS files. See the advanced module README.txt file for more information on theme and CSS customizations.', array('@settings' => url('admin/config/administration/admin_menu'))) . '</p>';
20
      $output .= '<p>' . t('The menu items displayed in the administration menu depend upon the actual permissions of the viewer. First, the administration menu is only displayed to users in roles with the <em>Access administration menu</em> (admin_menu module) permission. Second, a user must be a member of a role with the <em>Access administration pages</em> (system module) permission to view administrative links. And, third, only currently permitted links are displayed; for example, if a user is not a member of a role with the permissions <em>Administer permissions</em> (user module) and <em>Administer users</em> (user module), the <em>User management</em> menu item is not displayed.') . '</p>';
21
      return $output;
22
  }
23
}
24

    
25
/**
26
 * Implements hook_permission().
27
 */
28
function admin_menu_permission() {
29
  return array(
30
    'access administration menu' => array(
31
      'title' => t('Access administration menu'),
32
      'description' => t('Display the administration menu at the top of each page.'),
33
    ),
34
    'flush caches' => array(
35
      'title' => t('Flush caches'),
36
      'description' => t('Access links to flush caches in the administration menu.'),
37
    ),
38
    'display drupal links' => array(
39
      'title' => t('Display Drupal links'),
40
      'description' => t('Provide Drupal.org links in the administration menu.'),
41
    ),
42
  );
43
}
44

    
45
/**
46
 * Implements hook_theme().
47
 */
48
function admin_menu_theme() {
49
  return array(
50
    'admin_menu_links' => array(
51
      'render element' => 'elements',
52
    ),
53
    'admin_menu_icon' => array(
54
      'variables' => array('src' => NULL, 'alt' => NULL),
55
      'file' => 'admin_menu.inc',
56
    ),
57
  );
58
}
59

    
60
/**
61
 * Implements hook_menu().
62
 */
63
function admin_menu_menu() {
64
  // AJAX callback.
65
  // @see http://drupal.org/project/js
66
  $items['js/admin_menu/cache'] = array(
67
    'page callback' => 'admin_menu_js_cache',
68
    'delivery callback' => 'admin_menu_deliver',
69
    'access arguments' => array('access administration menu'),
70
    'type' => MENU_CALLBACK,
71
  );
72
  // Module settings.
73
  $items['admin/config/administration'] = array(
74
    'title' => 'Administration',
75
    'description' => 'Administration tools.',
76
    'page callback' => 'system_admin_menu_block_page',
77
    'access arguments' => array('access administration pages'),
78
    'file' => 'system.admin.inc',
79
    'file path' => drupal_get_path('module', 'system'),
80
  );
81
  $items['admin/config/administration/admin_menu'] = array(
82
    'title' => 'Administration menu',
83
    'description' => 'Adjust administration menu settings.',
84
    'page callback' => 'drupal_get_form',
85
    'page arguments' => array('admin_menu_theme_settings'),
86
    'access arguments' => array('administer site configuration'),
87
    'file' => 'admin_menu.inc',
88
  );
89
  // Menu link callbacks.
90
  $items['admin_menu/toggle-modules'] = array(
91
    'page callback' => 'admin_menu_toggle_modules',
92
    'access arguments' => array('administer modules'),
93
    'type' => MENU_CALLBACK,
94
    'file' => 'admin_menu.inc',
95
  );
96
  $items['admin_menu/flush-cache'] = array(
97
    'page callback' => 'admin_menu_flush_cache',
98
    'access arguments' => array('flush caches'),
99
    'type' => MENU_CALLBACK,
100
    'file' => 'admin_menu.inc',
101
  );
102
  return $items;
103
}
104

    
105
/**
106
 * Implements hook_menu_alter().
107
 */
108
function admin_menu_menu_alter(&$items) {
109
  // Flush client-side caches whenever the menu is rebuilt.
110
  admin_menu_flush_caches();
111
}
112

    
113
/**
114
 * Implements hook_menu_link_insert().
115
 */
116
function admin_menu_menu_link_insert($link) {
117
  // Flush all of our caches to pick up the link.
118
  admin_menu_flush_caches();
119
}
120

    
121
/**
122
 * Implements hook_menu_link_update().
123
 */
124
function admin_menu_menu_link_update($link) {
125
  // Flush all of our caches to pick up the link.
126
  admin_menu_flush_caches();
127
}
128

    
129
/**
130
 * Implements hook_menu_link_delete().
131
 */
132
function admin_menu_menu_link_delete($link) {
133
  // Flush all of our caches to pick up the link.
134
  admin_menu_flush_caches();
135
}
136

    
137
/**
138
 * Implements hook_system_info_alter().
139
 *
140
 * Indicate that the 'page_bottom' region (in which the administration menu
141
 * is displayed) is an overlay supplemental region that should be refreshed
142
 * whenever its content is updated.
143
 *
144
 * @see toolbar_system_info_alter()
145
 */
146
function admin_menu_system_info_alter(&$info, $file, $type) {
147
  if ($type == 'theme') {
148
    $info['overlay_supplemental_regions'][] = 'page_bottom';
149
  }
150
}
151

    
152
/**
153
 * Implements hook_page_build().
154
 */
155
function admin_menu_page_build(&$page) {
156
  if (!user_access('access administration menu') || admin_menu_suppress(FALSE)) {
157
    return;
158
  }
159
  // Performance: Skip this entirely for AJAX requests.
160
  if (strpos($_GET['q'], 'js/') === 0) {
161
    return;
162
  }
163
  global $user, $language;
164
  $path = drupal_get_path('module', 'admin_menu');
165

    
166
  $page['page_bottom']['admin_menu'] = array(
167
    '#attached' => array(),
168
  );
169
  $attached = &$page['page_bottom']['admin_menu']['#attached'];
170
  $options = array('every_page' => TRUE);
171

    
172
  $attached['css'][$path . '/admin_menu.css'] = $options;
173
  if ($user->uid == 1) {
174
    $attached['css'][$path . '/admin_menu.uid1.css'] = $options;
175
  }
176
  // Previous versions used the 'defer' attribute to increase browser rendering
177
  // performance. At least starting with Firefox 3.6, deferred .js files are
178
  // loaded, but Drupal.behaviors are not contained in the DOM when drupal.js
179
  // executes Drupal.attachBehaviors().
180
  $attached['js'][$path . '/admin_menu.js'] = $options;
181

    
182
  // Destination query strings are applied via JS.
183
  $settings['destination'] = drupal_http_build_query(drupal_get_destination());
184

    
185
  // Determine whether we need to show all components and disable all caches.
186
  $complete = FALSE;
187
  if (current_path() == 'admin/config/administration/admin_menu' && $_SERVER['REQUEST_METHOD'] == 'GET') {
188
    $complete = TRUE;
189
  }
190

    
191
  // If the client supports JavaScript and we have a cached menu for the current
192
  // user, only output the hash for the client-side HTTP cache callback URL.
193
  $cid = 'admin_menu:' . $user->uid . ':' . session_id() . ':' . $language->language;
194
  if (!$complete && !empty($_COOKIE['has_js']) && ($hash = admin_menu_cache_get($cid))) {
195
    $settings['hash'] = $hash;
196
    // The base path to use for cache requests depends on whether clean URLs
197
    // are enabled, whether Drupal runs in a sub-directory, and on the language
198
    // system configuration. url() already provides us the proper path and also
199
    // invokes potentially existing custom_url_rewrite() functions, which may
200
    // add further required components to the URL to provide context. Due to
201
    // those components, and since url('') returns only base_path() when clean
202
    // URLs are disabled, we need to use a replacement token as path.  Yuck.
203
    $settings['basePath'] = url('admin_menu');
204
  }
205
  // Otherwise, add the full menu to the page.
206
  else {
207
    $page['page_bottom']['admin_menu']['#markup'] = admin_menu_output($complete);
208
  }
209

    
210
  $replacements = module_invoke_all('admin_menu_replacements', $complete);
211
  if (!empty($replacements)) {
212
    $settings['replacements'] = $replacements;
213
  }
214

    
215
  if ($setting = variable_get('admin_menu_margin_top', 1)) {
216
    $settings['margin_top'] = $setting;
217
    // @todo Drupal.behaviors.adminMenuMarginTop is obsolete, but
218
    //   hook_page_build() does not allow to set a CSS class on the body yet.
219
    // @see http://drupal.org/node/1473548, http://drupal.org/node/1194528
220
    //$page['#attributes']['class'][] = 'admin-menu';
221
  }
222
  if ($setting = variable_get('admin_menu_position_fixed', 1)) {
223
    $settings['position_fixed'] = $setting;
224

    
225
    // In fixed positioning, supply a callback function for tableheader.js to
226
    // allow it to determine the top viewport offset.
227
    // @see admin_menu.js, toolbar.js
228
    $attached['js'][] = array(
229
      'data' => array('tableHeaderOffset' => 'Drupal.admin.height'),
230
      'type' => 'setting',
231
    );
232
  }
233
  if ($setting = variable_get('admin_menu_tweak_tabs', 0)) {
234
    $settings['tweak_tabs'] = $setting;
235
  }
236
  if ($_GET['q'] == 'admin/modules' || strpos($_GET['q'], 'admin/modules/list') === 0) {
237
    $settings['tweak_modules'] = variable_get('admin_menu_tweak_modules', 0);
238
  }
239
  if ($_GET['q'] == 'admin/people/permissions' || $_GET['q'] == 'admin/people/permissions/list') {
240
    $settings['tweak_permissions'] = variable_get('admin_menu_tweak_permissions', 0);
241
  }
242

    
243
  $attached['js'][] = array(
244
    'data' => array('admin_menu' => $settings),
245
    'type' => 'setting',
246
  );
247
}
248

    
249
/**
250
 * Suppress display of administration menu.
251
 *
252
 * This function should be called from within another module's page callback
253
 * (preferably using module_invoke()) when the menu should not be displayed.
254
 * This is useful for modules that implement popup pages or other special
255
 * pages where the menu would be distracting or break the layout.
256
 *
257
 * @param $set
258
 *   Defaults to TRUE. If called before hook_footer(), the menu will not be
259
 *   displayed. If FALSE is passed, the suppression state is returned.
260
 */
261
function admin_menu_suppress($set = TRUE) {
262
  static $suppress = FALSE;
263
  // drupal_add_js() must only be invoked once.
264
  if (!empty($set) && $suppress === FALSE) {
265
    $suppress = TRUE;
266
    drupal_add_js(array('admin_menu' => array('suppress' => 1)), 'setting');
267
  }
268
  return $suppress;
269
}
270

    
271
/**
272
 * Implements hook_js().
273
 */
274
function admin_menu_js() {
275
  return array(
276
    'cache' => array(
277
      'callback' => 'admin_menu_js_cache',
278
      'includes' => array('common', 'theme', 'unicode'),
279
      'dependencies' => array('devel', 'filter', 'user'),
280
    ),
281
  );
282
}
283

    
284
/**
285
 * Retrieve a client-side cache hash from cache.
286
 *
287
 * The hash cache is consulted more than once per request; we therefore cache
288
 * the results statically to avoid multiple database requests.
289
 *
290
 * This should only be used for client-side cache hashes. Use cache_menu for
291
 * administration menu content.
292
 *
293
 * @param $cid
294
 *   The cache ID of the data to retrieve.
295
 */
296
function admin_menu_cache_get($cid) {
297
  $cache = &drupal_static(__FUNCTION__, array());
298

    
299
  if (!variable_get('admin_menu_cache_client', TRUE)) {
300
    return FALSE;
301
  }
302
  if (!array_key_exists($cid, $cache)) {
303
    $cache[$cid] = cache_get($cid, 'cache_admin_menu');
304
    if ($cache[$cid] && isset($cache[$cid]->data)) {
305
      $cache[$cid] = $cache[$cid]->data;
306
    }
307
  }
308

    
309
  return $cache[$cid];
310
}
311

    
312
/**
313
 * Store a client-side cache hash in persistent cache.
314
 *
315
 * This should only be used for client-side cache hashes. Use cache_menu for
316
 * administration menu content.
317
 *
318
 * @param $cid
319
 *   The cache ID of the data to retrieve.
320
 */
321
function admin_menu_cache_set($cid, $data) {
322
  if (variable_get('admin_menu_cache_client', TRUE)) {
323
    cache_set($cid, $data, 'cache_admin_menu');
324
  }
325
}
326

    
327
/**
328
 * Menu callback; Output administration menu for HTTP caching via AJAX request.
329
 *
330
 * @see admin_menu_deliver()
331
 */
332
function admin_menu_js_cache() {
333
  global $conf;
334

    
335
  // Suppress Devel module.
336
  $GLOBALS['devel_shutdown'] = FALSE;
337

    
338
  // Enforce page caching.
339
  $conf['cache'] = 1;
340
  drupal_page_is_cacheable(TRUE);
341

    
342
  // If we have a cache, serve it.
343
  // @see _drupal_bootstrap_page_cache()
344
  $cache = drupal_page_get_cache();
345
  if (is_object($cache)) {
346
    header('X-Drupal-Cache: HIT');
347
    // Restore the metadata cached with the page.
348
    $_GET['q'] = $cache->data['path'];
349
    date_default_timezone_set(drupal_get_user_timezone());
350

    
351
    drupal_serve_page_from_cache($cache);
352

    
353
    // We are done.
354
    exit;
355
  }
356

    
357
  // Otherwise, create a new page response (that will be cached).
358
  header('X-Drupal-Cache: MISS');
359

    
360
  // The Expires HTTP header is the heart of the client-side HTTP caching. The
361
  // additional server-side page cache only takes effect when the client
362
  // accesses the callback URL again (e.g., after clearing the browser cache or
363
  // when force-reloading a Drupal page).
364
  $max_age = 3600 * 24 * 365;
365
  drupal_add_http_header('Expires', gmdate(DATE_RFC1123, REQUEST_TIME + $max_age));
366
  drupal_add_http_header('Cache-Control', 'private, max-age=' . $max_age);
367

    
368
  // Retrieve and return the rendered menu.
369
  return admin_menu_output();
370
}
371

    
372
/**
373
 * Delivery callback for client-side HTTP caching.
374
 *
375
 * @see admin_menu_js_cache()
376
 */
377
function admin_menu_deliver($page_callback_result) {
378
  drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
379

    
380
  // Send appropriate language header for browsers.
381
  global $language;
382
  drupal_add_http_header('Content-Language', $language->language);
383

    
384
  // The page callback is always admin_menu_js_cache(), which always returns a
385
  // string, and is only accessed when the user actually has access to it.
386
  // Therefore, we do not care for the other possible page callback results.
387
  print $page_callback_result;
388

    
389
  // Perform end-of-request tasks. The page cache is created here.
390
  drupal_page_footer();
391
}
392

    
393
/**
394
 * Implements hook_admin_menu_replacements().
395
 */
396
function admin_menu_admin_menu_replacements($complete) {
397
  $items = array();
398
  // If the complete menu is output, then it is uncached and will contain the
399
  // current counts already.
400
  if (!$complete) {
401
    // Check whether the users count component is enabled.
402
    $components = variable_get('admin_menu_components', array());
403
    if (!empty($components['admin_menu.users']) && ($user_count = admin_menu_get_user_count())) {
404
      // Replace the counters in the cached menu output with current counts.
405
      $items['.admin-menu-users a'] = $user_count;
406
    }
407
  }
408
  return $items;
409
}
410

    
411
/**
412
 * Return count of online anonymous/authenticated users.
413
 *
414
 * @see user_block(), user.module
415
 */
416
function admin_menu_get_user_count() {
417
  $interval   = REQUEST_TIME - variable_get('user_block_seconds_online', 900);
418
  $count_anon = admin_menu_session_count($interval, TRUE);
419
  $count_auth = admin_menu_session_count($interval, FALSE);
420

    
421
  return t('@count-anon / @count-auth', array('@count-anon' => $count_anon, '@count-auth' => $count_auth));
422
}
423

    
424
/**
425
 * Counts how many users are active on the site.
426
 *
427
 * Counts how many users have sessions which have been active since the
428
 * specified time. Can count either anonymous sessions or authenticated
429
 * sessions.
430
 *
431
 * @param $timestamp
432
 *   A Unix timestamp. Users who have been active since this time will be
433
 *   counted. The default is 0, which counts all existing sessions.
434
 * @param $anonymous
435
 *   TRUE counts only anonymous users. FALSE counts only authenticated users.
436
 *
437
 * @return
438
 *   The number of users with sessions.
439
 *
440
 * @todo There are mostly no anonymous sessions anymore. Split this into a
441
 *   separate module providing proper user statistics.
442
 */
443
function admin_menu_session_count($timestamp = 0, $anonymous = TRUE) {
444
  $query = db_select('sessions');
445
  $query->addExpression('COUNT(sid)', 'count');
446
  $query->condition('timestamp', $timestamp, '>=');
447
  $query->condition('uid', 0, $anonymous ? '=' : '>');
448
  return $query->execute()->fetchField();
449
}
450

    
451
/**
452
 * Build the administration menu output.
453
 *
454
 * @param bool $complete
455
 *   (optional) Whether to build to the complete menu including all components
456
 *   and ignore the cache. Defaults to FALSE. Internally used for the settings
457
 *   page.
458
 */
459
function admin_menu_output($complete = FALSE) {
460
  global $user, $language;
461

    
462
  $cache_server_enabled = !$complete && variable_get('admin_menu_cache_server', TRUE);
463
  $cid = 'admin_menu:' . $user->uid . ':' . session_id() . ':' . $language->language;
464

    
465
  // Try to load and output administration menu from server-side cache.
466
  // @todo Duplicates the page cache? Page cache ID contains the hash that is
467
  //   generated at the bottom of this function, which is based on $content,
468
  //   but logically identical to the $cid. Investigate whether not only the
469
  //   cache_menu but also the cache_admin_menu could be dropped; the
470
  //   client-side HTTP cache hash check could be based on a cid lookup in
471
  //   cache_page instead? (i.e., one cache to rule them all) However,
472
  //   cache_page is cleared very often.
473
  if ($cache_server_enabled) {
474
    $cache = cache_get($cid, 'cache_menu');
475
    if ($cache && isset($cache->data)) {
476
      $content = $cache->data;
477
    }
478
  }
479

    
480
  // Rebuild the output.
481
  if (!isset($content)) {
482
    // Retrieve enabled components to display and make them available for others.
483
    $components = variable_get('admin_menu_components', array());
484
    $components += array(
485
      'admin_menu.menu' => TRUE,
486
      'admin_menu.icon' => TRUE,
487
      'admin_menu.account' => TRUE,
488
    );
489
    $content['#components'] = $components;
490
    $content['#complete'] = $complete;
491

    
492
    // Add site name as CSS class for development/staging theming purposes. We
493
    // leverage the cookie domain instead of HTTP_HOST to account for many (but
494
    // not all) multi-domain setups (e.g. language-based sub-domains).
495
    $classes = 'admin-menu-site' . drupal_strtolower(preg_replace('/[^a-zA-Z0-9-]/', '-', $GLOBALS['cookie_domain']));
496
    // Displace overlay.
497
    // @see Drupal.overlay.create
498
    // @see toolbar_preprocess_toolbar()
499
    if (module_exists('overlay')) {
500
      $classes .= ' overlay-displace-top';
501
    }
502
    // @todo Always output container to harden JS-less support.
503
    $content['#prefix'] = '<div id="admin-menu" class="' . $classes . '"><div id="admin-menu-wrapper">';
504
    $content['#suffix'] = '</div></div>';
505

    
506
    // Load menu builder functions.
507
    module_load_include('inc', 'admin_menu');
508

    
509
    // @todo Move the below callbacks into hook_admin_menu_build()
510
    //   implementations (and $module.admin_menu.inc).
511

    
512
    // Add administration menu.
513
    if (!empty($components['admin_menu.menu']) || $complete) {
514
      $content['menu'] = admin_menu_links_menu(admin_menu_tree('management'));
515
      $content['menu']['#theme'] = 'admin_menu_links';
516
      $content['menu']['#wrapper_attributes']['id'] = 'admin-menu-menu';
517
      // Ensure the menu tree is rendered between the icon and user links.
518
      $content['menu']['#weight'] = 0;
519
    }
520

    
521
    // Add menu additions.
522
    if (!empty($components['admin_menu.icon']) || $complete) {
523
      $content['icon'] = admin_menu_links_icon();
524
    }
525
    if (!empty($components['admin_menu.account']) || $complete) {
526
      $content['account'] = admin_menu_links_account();
527
    }
528
    if (!empty($components['admin_menu.users']) || $complete) {
529
      $content['users'] = admin_menu_links_users();
530
    }
531
    if (!empty($components['admin_menu.search']) || $complete) {
532
      $content['search'] = admin_menu_links_search();
533
    }
534

    
535
    // Allow modules to enhance the menu.
536
    // Uses '_output' suffix for consistency with the alter hook (see below).
537
    foreach (module_implements('admin_menu_output_build') as $module) {
538
      $function = $module . '_admin_menu_output_build';
539
      $function($content);
540
    }
541

    
542
    // Allow modules to alter the output.
543
    // The '_output' suffix is required to prevent hook implementation function
544
    // name clashes with the contributed Admin module.
545
    drupal_alter('admin_menu_output', $content);
546

    
547
    $content = drupal_render($content);
548

    
549
    // Cache the menu for this user.
550
    if ($cache_server_enabled) {
551
      cache_set($cid, $content, 'cache_menu');
552
    }
553
  }
554

    
555
  // Store the new hash for this user.
556
  if (!empty($_COOKIE['has_js']) && !$complete) {
557
    admin_menu_cache_set($cid, md5($content));
558
  }
559

    
560
  return $content;
561
}
562

    
563
/**
564
 * Implements hook_admin_menu_output_build().
565
 */
566
function admin_menu_admin_menu_output_build(&$content) {
567
  if (!isset($content['menu'])) {
568
    return;
569
  }
570

    
571
  // Unassign weights for categories below Configuration.
572
  // An alphabetical order is more natural for a dropdown menu.
573
  if (isset($content['menu']['admin/config'])) {
574
    foreach (element_children($content['menu']['admin/config']) as $key) {
575
      $content['menu']['admin/config'][$key]['#weight_original'] = $content['menu']['admin/config'][$key]['#weight'];
576
      unset($content['menu']['admin/config'][$key]['#weight']);
577
    }
578
  }
579

    
580
  // Retrieve the "Add content" link tree.
581
  $link = db_query("SELECT * FROM {menu_links} WHERE router_path = 'node/add' AND module = 'system'")->fetchAssoc();
582
  $conditions = array();
583
  for ($i = 1; $i < MENU_MAX_DEPTH; $i++) {
584
    if (!empty($link["p$i"])) {
585
      $conditions["p$i"] = $link["p$i"];
586
    }
587
  }
588
  $tree = menu_build_tree($link['menu_name'], array(
589
    'conditions' => $conditions,
590
    'min_depth' => $link['depth'],
591
  ));
592
  $links = admin_menu_links_menu($tree);
593
  if (!empty($links)) {
594
    // If the user has access to the top-level "Content" category, insert the
595
    // "Add content" link tree there.
596
    if (isset($content['menu']['admin/content'])) {
597
      $content['menu']['admin/content'] += $links;
598
    }
599
    // Otherwise make insert "Add content" as top-level category.
600
    else {
601
      $key = key($links);
602
      $links[$key]['#weight'] = -100;
603
      $content['menu'] += $links;
604
    }
605
  }
606
}
607

    
608
/**
609
 * Implements hook_admin_menu_output_alter().
610
 */
611
function admin_menu_admin_menu_output_alter(&$content) {
612
  foreach ($content['menu'] as $key => $link) {
613
    // Move local tasks on 'admin' into icon menu.
614
    if ($key == 'admin/tasks' || $key == 'admin/index') {
615
      $content['icon']['icon'][$key] = $link;
616
      unset($content['menu'][$key]);
617
    }
618
  }
619
}
620

    
621
/**
622
 * Render a themed list of links.
623
 *
624
 * @param $variables
625
 *   - elements: A renderable array of links using the following keys:
626
 *     - #attributes: Optional array of attributes for the list item, processed
627
 *       via drupal_attributes().
628
 *     - #title: Title of the link, passed to l().
629
 *     - #href: Optional path of the link, passed to l(). When omitted, the
630
 *       element's '#title' is rendered without link.
631
 *     - #description: Optional alternative text for the link, passed to l().
632
 *     - #options: Optional alternative text for the link, passed to l().
633
 *     The array key of each child element itself is passed as path for l().
634
 */
635
function theme_admin_menu_links($variables) {
636
  $destination = &drupal_static('admin_menu_destination');
637
  $elements = $variables['elements'];
638

    
639
  if (!isset($destination)) {
640
    $destination = drupal_get_destination();
641
    $destination = $destination['destination'];
642
  }
643

    
644
  // The majority of items in the menu are sorted already, but since modules
645
  // may add or change arbitrary items anywhere, there is no way around sorting
646
  // everything again. element_sort() is not sufficient here, as it
647
  // intentionally retains the order of elements having the same #weight,
648
  // whereas menu links are supposed to be ordered by #weight and #title.
649
  uasort($elements, 'admin_menu_element_sort');
650
  $elements['#sorted'] = TRUE;
651

    
652
  $output = '';
653
  foreach (element_children($elements) as $path) {
654
    // Early-return nothing if user does not have access.
655
    if (isset($elements[$path]['#access']) && !$elements[$path]['#access']) {
656
      continue;
657
    }
658
    $elements[$path] += array(
659
      '#attributes' => array(),
660
      '#options' => array(),
661
    );
662
    // Render children to determine whether this link is expandable.
663
    if (isset($elements[$path]['#type']) || isset($elements[$path]['#theme']) || isset($elements[$path]['#pre_render'])) {
664
      $elements[$path]['#children'] = drupal_render($elements[$path]);
665
    }
666
    else {
667
      $elements[$path]['#children'] = theme('admin_menu_links', array('elements' => $elements[$path]));
668
      if (!empty($elements[$path]['#children'])) {
669
        $elements[$path]['#attributes']['class'][] = 'expandable';
670
      }
671
      if (isset($elements[$path]['#attributes']['class'])) {
672
        $elements[$path]['#attributes']['class'] = $elements[$path]['#attributes']['class'];
673
      }
674
    }
675

    
676
    $link = '';
677
    // Handle menu links.
678
    if (isset($elements[$path]['#href'])) {
679
      // Strip destination query string from href attribute and apply a CSS class
680
      // for our JavaScript behavior instead.
681
      if (isset($elements[$path]['#options']['query']['destination']) && $elements[$path]['#options']['query']['destination'] == $destination) {
682
        unset($elements[$path]['#options']['query']['destination']);
683
        $elements[$path]['#options']['attributes']['class'][] = 'admin-menu-destination';
684
      }
685

    
686
      $link = l($elements[$path]['#title'], $elements[$path]['#href'], $elements[$path]['#options']);
687
    }
688
    // Handle plain text items, but do not interfere with menu additions.
689
    elseif (!isset($elements[$path]['#type']) && isset($elements[$path]['#title'])) {
690
      if (!empty($elements[$path]['#options']['html'])) {
691
        $title = $elements[$path]['#title'];
692
      }
693
      else {
694
        $title = check_plain($elements[$path]['#title']);
695
      }
696
      $attributes = '';
697
      if (isset($elements[$path]['#options']['attributes'])) {
698
        $attributes = drupal_attributes($elements[$path]['#options']['attributes']);
699
      }
700
      $link = '<span' . $attributes . '>' . $title . '</span>';
701
    }
702

    
703
    $output .= '<li' . drupal_attributes($elements[$path]['#attributes']) . '>';
704
    $output .= $link . $elements[$path]['#children'];
705
    $output .= '</li>';
706
  }
707
  // @todo #attributes probably required for UL, but already used for LI.
708
  // @todo Use $element['#children'] here instead.
709
  if ($output) {
710
    $elements['#wrapper_attributes']['class'][] = 'dropdown';
711
    $attributes = drupal_attributes($elements['#wrapper_attributes']);
712
    $output = "\n" . '<ul' . $attributes . '>' . $output . '</ul>';
713
  }
714
  return $output;
715
}
716

    
717
/**
718
 * Function used by uasort to sort structured arrays by #weight AND #title.
719
 */
720
function admin_menu_element_sort($a, $b) {
721
  // @see element_sort()
722
  $a_weight = isset($a['#weight']) ? $a['#weight'] : 0;
723
  $b_weight = isset($b['#weight']) ? $b['#weight'] : 0;
724
  if ($a_weight == $b_weight) {
725
    // @see element_sort_by_title()
726
    $a_title = isset($a['#title']) ? $a['#title'] : '';
727
    $b_title = isset($b['#title']) ? $b['#title'] : '';
728
    return strnatcasecmp($a_title, $b_title);
729
  }
730
  return ($a_weight < $b_weight) ? -1 : 1;
731
}
732

    
733
/**
734
 * Implements hook_translated_menu_link_alter().
735
 *
736
 * Here is where we make changes to links that need dynamic information such
737
 * as the current page path or the number of users.
738
 */
739
function admin_menu_translated_menu_link_alter(&$item, $map) {
740
  global $user, $base_url;
741
  static $access_all;
742

    
743
  if ($item['menu_name'] != 'admin_menu') {
744
    return;
745
  }
746

    
747
  // Check whether additional development output is enabled.
748
  if (!isset($access_all)) {
749
    $access_all = variable_get('admin_menu_show_all', 0) && module_exists('devel');
750
  }
751
  // Prepare links that would not be displayed normally.
752
  if ($access_all && !$item['access']) {
753
    $item['access'] = TRUE;
754
    // Prepare for http://drupal.org/node/266596
755
    if (!isset($item['localized_options'])) {
756
      _menu_item_localize($item, $map, TRUE);
757
    }
758
  }
759

    
760
  // Don't waste cycles altering items that are not visible
761
  if (!$item['access']) {
762
    return;
763
  }
764

    
765
  // Add developer information to all links, if enabled.
766
  if ($extra = variable_get('admin_menu_display', 0)) {
767
    $item['title'] .= ' ' . $extra[0] . ': ' . $item[$extra];
768
  }
769
}
770

    
771
/**
772
 * Implements hook_flush_caches().
773
 *
774
 * Flushes client-side caches.
775
 *
776
 * @param int $uid
777
 *   (optional) A user ID to limit the cache flush to.
778
 */
779
function admin_menu_flush_caches($uid = NULL) {
780
  // A call to menu_rebuild() will trigger potentially thousands of calls into
781
  // menu_link_save(), for which admin_menu has to implement the corresponding
782
  // CRUD hooks, in order to take up any menu link changes, since any menu link
783
  // change could affect the admin menu (which essentially is an aggregate) and
784
  // since there is no other way to get notified about stale caches. The cache
785
  // only needs to be flushed once though, so we prevent a ton of needless
786
  // subsequent calls with this static.
787
  // @see http://drupal.org/node/918538
788
  $was_flushed = &drupal_static(__FUNCTION__, array());
789
  // $uid can be NULL. PHP automatically converts that into '' (empty string),
790
  // which is different to uid 0 (zero).
791
  if (isset($was_flushed[$uid])) {
792
    return;
793
  }
794
  $was_flushed[$uid] = TRUE;
795

    
796
  $cid = 'admin_menu:';
797
  if (isset($uid)) {
798
    $cid .= $uid . ':';
799
  }
800
  // Flush cached output of admin_menu.
801
  cache_clear_all($cid, 'cache_menu', TRUE);
802
  // Flush client-side cache hashes.
803
  drupal_static_reset('admin_menu_cache_get');
804
  // db_table_exists() required for SimpleTest.
805
  if (db_table_exists('cache_admin_menu')) {
806
    cache_clear_all(isset($uid) ? $cid : '*', 'cache_admin_menu', TRUE);
807
  }
808
}
809

    
810
/**
811
 * Implements hook_form_alter().
812
 */
813
function admin_menu_form_alter(&$form, &$form_state, $form_id) {
814
  $global_flush_ids = array(
815
    'admin_menu_theme_settings' => 1,
816
    // Update links for clean/non-clean URLs.
817
    'system_clean_url_settings' => 1,
818
    // Incorporate changed user permissions.
819
    'user_admin_permissions' => 1,
820
    // Removing a role potentially means less permissions.
821
    'user_admin_role_delete_confirm' => 1,
822
    // User name and roles may be changed on the user account form.
823
    'user_profile_form' => 1,
824
  );
825
  if (isset($global_flush_ids[$form_id])) {
826
    $form['#submit'][] = 'admin_menu_form_alter_flush_cache_submit';
827

    
828
    // Optionally limit the cache flush to a certain user ID.
829
    $form_state['admin_menu_uid'] = NULL;
830
    if ($form_id == 'user_profile_form') {
831
      $form_state['admin_menu_uid'] = $form_state['user']->uid;
832
    }
833
  }
834

    
835
  // UX: Add a confirmation to the permissions form to ask the user whether to
836
  // auto-enable the 'access administration menu' permission along with
837
  // 'access administration pages'.
838
  if ($form_id == 'user_admin_permissions') {
839
    $form['#attached']['js'][] = drupal_get_path('module', 'admin_menu') . '/admin_menu.admin.js';
840
  }
841
}
842

    
843
/**
844
 * Form submission handler to flush Administration menu caches.
845
 */
846
function admin_menu_form_alter_flush_cache_submit($form, &$form_state) {
847
  admin_menu_flush_caches($form_state['admin_menu_uid']);
848
}
849

    
850
/**
851
 * Implements hook_form_FORM_ID_alter().
852
 *
853
 * Extends Devel module with Administration menu developer settings.
854
 */
855
function admin_menu_form_devel_admin_settings_alter(&$form, &$form_state) {
856
  form_load_include($form_state, 'inc', 'admin_menu');
857
  _admin_menu_form_devel_admin_settings_alter($form, $form_state);
858
}