theme.inc 86.2 KB
Newer Older
Dries's avatar
   
Dries committed
1
<?php
2
// $Id$
Dries's avatar
   
Dries committed
3

4
/**
Dries's avatar
   
Dries committed
5
 * @file
6
 * The theme system, which controls the output of Drupal.
Dries's avatar
   
Dries committed
7
8
9
10
 *
 * The theme system allows for nearly all output of the Drupal system to be
 * customized by user themes.
 *
11
 * @ingroup themeable
Dries's avatar
   
Dries committed
12
 */
Dries's avatar
   
Dries committed
13

14
/**
15
16
17
18
19
 * @name Content markers
 * @{
 * Markers used by theme_mark() and node_mark() to designate content.
 * @see theme_mark(), node_mark()
 */
20
21
22
23
24
25
26
27
28
29
30
31
32
33

/**
 * Mark content as read.
 */
define('MARK_READ', 0);

/**
 * Mark content as being new.
 */
define('MARK_NEW', 1);

/**
 * Mark content as being updated.
 */
34
define('MARK_UPDATED', 2);
35

36
37
38
39
/**
 * @} End of "Content markers".
 */

40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
 * Determines if a theme is available to use.
 *
 * @param $theme
 *   An object representing the theme to check.
 * @return
 *   Boolean TRUE if the theme is enabled or is the site administration theme;
 *   FALSE otherwise.
 */
function drupal_theme_access($theme) {
  $admin_theme = variable_get('admin_theme');
  return !empty($theme->status) || ($admin_theme && $theme->name == $admin_theme);
}

Dries's avatar
   
Dries committed
54
/**
Dries's avatar
   
Dries committed
55
 * Initialize the theme system by loading the theme.
Dries's avatar
   
Dries committed
56
 */
57
function drupal_theme_initialize() {
58
  global $theme, $user, $theme_key;
59
60
61
62
63

  // If $theme is already set, assume the others are set, too, and do nothing
  if (isset($theme)) {
    return;
  }
Dries's avatar
   
Dries committed
64

65
  drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
Dries's avatar
   
Dries committed
66
67
  $themes = list_themes();

68
  // Only select the user selected theme if it is available in the
69
70
  // list of themes that can be accessed.
  $theme = !empty($user->theme) && isset($themes[$user->theme]) && drupal_theme_access($themes[$user->theme]) ? $user->theme : variable_get('theme_default', 'garland');
Dries's avatar
   
Dries committed
71
72

  // Allow modules to override the present theme... only select custom theme
73
74
75
  // if it is available in the list of themes that can be accessed.
  $custom_theme = menu_get_custom_theme();
  $theme = $custom_theme && isset($themes[$custom_theme]) && drupal_theme_access($themes[$custom_theme]) ? $custom_theme : $theme;
Dries's avatar
   
Dries committed
76
77
78
79

  // Store the identifier for retrieving theme settings with.
  $theme_key = $theme;

80
81
82
83
  // Find all our ancestor themes and put them in an array.
  $base_theme = array();
  $ancestor = $theme;
  while ($ancestor && isset($themes[$ancestor]->base_theme)) {
84
85
    $base_theme[] = $new_base_theme = $themes[$themes[$ancestor]->base_theme];
    $ancestor = $themes[$ancestor]->base_theme;
86
  }
87
  _drupal_theme_initialize($themes[$theme], array_reverse($base_theme));
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
}

/**
 * Initialize the theme system given already loaded information. This
 * function is useful to initialize a theme when no database is present.
 *
 * @param $theme
 *   An object with the following information:
 *     filename
 *       The .info file for this theme. The 'path' to
 *       the theme will be in this file's directory. (Required)
 *     owner
 *       The path to the .theme file or the .engine file to load for
 *       the theme. (Required)
 *     stylesheet
 *       The primary stylesheet for the theme. (Optional)
 *     engine
 *       The name of theme engine to use. (Optional)
 * @param $base_theme
 *    An optional array of objects that represent the 'base theme' if the
 *    theme is meant to be derivative of another theme. It requires
 *    the same information as the $theme object. It should be in
 *    'oldest first' order, meaning the top level of the chain will
 *    be first.
112
113
 * @param $registry_callback
 *   The callback to invoke to set the theme registry.
114
 */
115
function _drupal_theme_initialize($theme, $base_theme = array(), $registry_callback = '_theme_load_registry') {
116
117
118
119
120
121
  global $theme_info, $base_theme_info, $theme_engine, $theme_path;
  $theme_info = $theme;
  $base_theme_info = $base_theme;

  $theme_path = dirname($theme->filename);

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
  // Prepare stylesheets from this theme as well as all ancestor themes.
  // We work it this way so that we can have child themes override parent
  // theme stylesheets easily.
  $final_stylesheets = array();

  // Grab stylesheets from base theme
  foreach ($base_theme as $base) {
    if (!empty($base->stylesheets)) {
      foreach ($base->stylesheets as $media => $stylesheets) {
        foreach ($stylesheets as $name => $stylesheet) {
          $final_stylesheets[$media][$name] = $stylesheet;
        }
      }
    }
  }

138
139
140
  // Add stylesheets used by this theme.
  if (!empty($theme->stylesheets)) {
    foreach ($theme->stylesheets as $media => $stylesheets) {
141
142
143
144
145
146
147
148
149
      foreach ($stylesheets as $name => $stylesheet) {
        $final_stylesheets[$media][$name] = $stylesheet;
      }
    }
  }

  // And now add the stylesheets properly
  foreach ($final_stylesheets as $media => $stylesheets) {
    foreach ($stylesheets as $stylesheet) {
150
      drupal_add_css($stylesheet, array('weight' => CSS_THEME, 'media' => $media));
151
152
153
154
155
156
157
158
159
160
161
    }
  }

  // Do basically the same as the above for scripts
  $final_scripts = array();

  // Grab scripts from base theme
  foreach ($base_theme as $base) {
    if (!empty($base->scripts)) {
      foreach ($base->scripts as $name => $script) {
        $final_scripts[$name] = $script;
162
      }
Dries's avatar
   
Dries committed
163
164
    }
  }
165

166
167
  // Add scripts used by this theme.
  if (!empty($theme->scripts)) {
168
169
    foreach ($theme->scripts as $name => $script) {
      $final_scripts[$name] = $script;
170
171
172
    }
  }

173
174
  // Add scripts used by this theme.
  foreach ($final_scripts as $script) {
175
    drupal_add_js($script, array('weight' => JS_THEME));
176
177
  }

178
179
180
181
182
  $theme_engine = NULL;

  // Initialize the theme.
  if (isset($theme->engine)) {
    // Include the engine.
183
    include_once DRUPAL_ROOT . '/' . $theme->owner;
184
185

    $theme_engine = $theme->engine;
186
    if (function_exists($theme_engine . '_init')) {
187
      foreach ($base_theme as $base) {
188
        call_user_func($theme_engine . '_init', $base);
189
      }
190
      call_user_func($theme_engine . '_init', $theme);
191
192
193
194
195
196
197
    }
  }
  else {
    // include non-engine theme files
    foreach ($base_theme as $base) {
      // Include the theme file or the engine.
      if (!empty($base->owner)) {
198
        include_once DRUPAL_ROOT . '/' . $base->owner;
199
200
201
202
      }
    }
    // and our theme gets one too.
    if (!empty($theme->owner)) {
203
      include_once DRUPAL_ROOT . '/' . $theme->owner;
Dries's avatar
   
Dries committed
204
205
    }
  }
206

207
  if (function_exists($registry_callback)) {
208
209
    $registry_callback($theme, $base_theme, $theme_engine);
  }
Dries's avatar
   
Dries committed
210
211
}

212
/**
213
 * Get the theme registry.
214
215
 * @return
 *   The theme registry array if it has been stored in memory, NULL otherwise.
216
 */
217
218
function theme_get_registry() {
  return _theme_set_registry();
219
220
221
222
}

/**
 * Store the theme registry in memory.
223
224
 * @param $registry
 *   A registry array as returned by _theme_build_registry()
225
 * @return
226
 *   The theme registry array stored in memory
227
 */
228
229
function _theme_set_registry($registry = NULL) {
  static $theme_registry = NULL;
230

231
232
233
  if (isset($registry)) {
    $theme_registry = $registry;
  }
234

235
  return $theme_registry;
236
237
238
}

/**
239
 * Get the theme_registry cache from the database; if it doesn't exist, build it.
240
241
 *
 * @param $theme
242
 *   The loaded $theme object as returned by list_themes().
243
244
245
246
247
 * @param $base_theme
 *   An array of loaded $theme objects representing the ancestor themes in
 *   oldest first order.
 * @param theme_engine
 *   The name of the theme engine.
248
 */
249
250
251
function _theme_load_registry($theme, $base_theme = NULL, $theme_engine = NULL) {
  // Check the theme registry cache; if it exists, use it.
  $cache = cache_get("theme_registry:$theme->name", 'cache');
252
  if (isset($cache->data)) {
253
    $registry = $cache->data;
254
255
  }
  else {
256
257
    // If not, build one and cache it.
    $registry = _theme_build_registry($theme, $base_theme, $theme_engine);
258
259
260
261
262
263
264
265
266
    _theme_save_registry($theme, $registry);
  }
  _theme_set_registry($registry);
}

/**
 * Write the theme_registry cache into the database.
 */
function _theme_save_registry($theme, $registry) {
267
  cache_set("theme_registry:$theme->name", $registry);
268
269
270
271
272
273
274
}

/**
 * Force the system to rebuild the theme registry; this should be called
 * when modules are added to the system, or when a dynamic system needs
 * to add more theme hooks.
 */
275
function drupal_theme_rebuild() {
276
277
278
279
  cache_clear_all('theme_registry', 'cache', TRUE);
}

/**
280
 * Process a single implementation of hook_theme().
281
 *
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
 * @param $cache
 *   The theme registry that will eventually be cached; It is an associative
 *   array keyed by theme hooks, whose values are associative arrays describing
 *   the hook:
 *   - 'type': The passed in $type.
 *   - 'theme path': The passed in $path.
 *   - 'function': The name of the function generating output for this theme
 *     hook. Either defined explicitly in hook_theme() or, if neither 'function'
 *     nor 'template' is defined, then the default theme function name is used.
 *     The default theme function name is the theme hook prefixed by either
 *     'theme_' for modules or '$name_' for everything else. If 'function' is
 *     defined, 'template' is not used.
 *   - 'template': The filename of the template generating output for this
 *     theme hook. The template is in the directory defined by the 'path' key of
 *     hook_theme() or defaults to $path.
 *   - 'arguments': The arguments for this theme hook as defined in
 *     hook_theme(). If there is more than one implementation and 'arguments' is
 *     not specified in a later one, then the previous definition is kept.
 *   - 'theme paths': The paths where implementations of a theme hook can be
 *     found. Its definition is similarly inherited like 'arguments'. Each time
 *     _theme_process_registry() is called for this theme hook, either the
 *     'path' key from hook_theme() (if defined) or $path is added.
 *   - 'preprocess functions': See theme() for detailed documentation.
305
 *   - 'process functions': See theme() for detailed documentation.
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
 * @param $name
 *   The name of the module, theme engine, base theme engine, theme or base
 *   theme implementing hook_theme().
 * @param $type
 *   One of 'module', 'theme_engine', 'base_theme_engine', 'theme', or
 *   'base_theme'. Unlike regular hooks that can only be implemented by modules,
 *   each of these can implement hook_theme(). _theme_process_registry() is
 *   called in aforementioned order and new entries override older ones. For
 *   example, if a theme hook is both defined by a module and a theme, then the
 *   definition in the theme will be used.
 * @param $theme
 *   The loaded $theme object as returned from list_themes().
 * @param $path
 *   The directory where $name is. For example, modules/system or
 *   themes/garland.
321
 *
322
323
324
325
 * @see theme()
 * @see _theme_process_registry()
 * @see hook_theme()
 * @see list_themes()
326
 */
327
function _theme_process_registry(&$cache, $name, $type, $theme, $path) {
328
  $result = array();
329
  $function = $name . '_theme';
330

331
  // Processor functions work in two distinct phases with the process
332
  // functions always being executed after the preprocess functions.
333
  $variable_process_phases = array(
334
335
336
337
    'preprocess functions' => 'preprocess',
    'process functions'    => 'process',
  );

338
  if (function_exists($function)) {
339
    $result = $function($cache, $type, $theme, $path);
340
341
    foreach ($result as $hook => $info) {
      $result[$hook]['type'] = $type;
342
      $result[$hook]['theme path'] = $path;
343
344
      // if function and file are left out, default to standard naming
      // conventions.
345
      if (!isset($info['template']) && !isset($info['function'])) {
346
        $result[$hook]['function'] = ($type == 'module' ? 'theme_' : $name . '_') . $hook;
347
      }
348
349
350
351
352
      // If a path is set in the info, use what was set. Otherwise use the
      // default path. This is mostly so system.module can declare theme
      // functions on behalf of core .include files.
      // All files are included to be safe. Conditionally included
      // files can prevent them from getting registered.
353
354
      if (isset($cache[$hook]['includes'])) {
        $result[$hook]['includes'] = $cache[$hook]['includes'];
355
      }
356
357
358
359
360
      if (isset($info['file'])) {
        $include_file = isset($info['path']) ? $info['path'] : $path;
        $include_file .= '/' . $info['file'];
        include_once DRUPAL_ROOT . '/' . $include_file;
        $result[$hook]['includes'][] = $include_file;
361
      }
362

363
364
365
366
367
368
      // If 'arguments' have been defined previously, carry them forward.
      // This should happen if a theme overrides a Drupal defined theme
      // function, for example.
      if (!isset($info['arguments']) && isset($cache[$hook])) {
        $result[$hook]['arguments'] = $cache[$hook]['arguments'];
      }
369
370
371
372
373
374

      // The following apply only to theming hooks implemented as templates.
      if (isset($info['template'])) {
        // Prepend the current theming path when none is set.
        if (!isset($info['path'])) {
          $result[$hook]['template'] = $path . '/' . $info['template'];
375
376
        }

377
378
379
380
381
382
383
        // These are used for template naming suggestions. Theme implementations
        // can occur in multiple paths. Suggestions should follow.
        if (!isset($info['theme paths']) && isset($cache[$hook])) {
          $result[$hook]['theme paths'] = $cache[$hook]['theme paths'];
        }
        // Check for sub-directories.
        $result[$hook]['theme paths'][] = isset($info['path']) ? $info['path'] : $path;
384
      }
385

386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
      // Allow variable processors for all theming hooks, whether the hook is
      // implemented as a template or as a function.
      foreach ($variable_process_phases as $phase_key => $phase) {
        // Check for existing variable processors. Ensure arrayness.
        if (!isset($info[$phase_key]) || !is_array($info[$phase_key])) {
          $info[$phase_key] = array();
          $prefixes = array();
          if ($type == 'module') {
            // Default variable processor prefix.
            $prefixes[] = 'template';
            // Add all modules so they can intervene with their own variable
            // processors. This allows them to provide variable processors even
            // if they are not the owner of the current hook.
            $prefixes += module_list();
          }
          elseif ($type == 'theme_engine' || $type == 'base_theme_engine') {
            // Theme engines get an extra set that come before the normally
            // named variable processors.
            $prefixes[] = $name . '_engine';
            // The theme engine registers on behalf of the theme using the
            // theme's name.
            $prefixes[] = $theme;
408
          }
409
410
411
412
          else {
            // This applies when the theme manually registers their own variable
            // processors.
            $prefixes[] = $name;
413
          }
414
415
416
417
418
419
420
421
422
          foreach ($prefixes as $prefix) {
            // Only use non-hook-specific variable processors for theming hooks
            // implemented as templates. @see theme().
            if (isset($info['template']) && function_exists($prefix . '_' . $phase)) {
              $info[$phase_key][] = $prefix . '_' . $phase;
            }
            if (function_exists($prefix . '_' . $phase . '_' . $hook)) {
              $info[$phase_key][] = $prefix . '_' . $phase . '_' . $hook;
            }
423
          }
424
        }
425
426
427
428
429
430
431
432
433
434
435
        // Check for the override flag and prevent the cached variable
        // processors from being used. This allows themes or theme engines to
        // remove variable processors set earlier in the registry build.
        if (!empty($info['override ' . $phase_key])) {
          // Flag not needed inside the registry.
          unset($result[$hook]['override ' . $phase_key]);
        }
        elseif (isset($cache[$hook][$phase_key]) && is_array($cache[$hook][$phase_key])) {
          $info[$phase_key] = array_merge($cache[$hook][$phase_key], $info[$phase_key]);
        }
        $result[$hook][$phase_key] = $info[$phase_key];
436
      }
437
438
    }

439
    // Merge the newly created theme hooks into the existing cache.
440
441
    $cache = array_merge($cache, $result);
  }
442

443
  // Let themes have variable processors even if they didn't register a template.
444
445
  if ($type == 'theme' || $type == 'base_theme') {
    foreach ($cache as $hook => $info) {
446
447
448
      // Check only if not registered by the theme or engine.
      if (empty($result[$hook])) {
        foreach ($variable_process_phases as $phase_key => $phase) {
449
450
451
          if (!isset($info[$phase_key])) {
            $cache[$hook][$phase_key] = array();
          }
452
453
454
455
          // Only use non-hook-specific variable processors for theming hooks
          // implemented as templates. @see theme().
          if (isset($info['template']) && function_exists($name . '_' . $phase)) {
            $cache[$hook][$phase_key][] = $name . '_' . $phase;
456
          }
457
458
          if (function_exists($name . '_' . $phase . '_' . $hook)) {
            $cache[$hook][$phase_key][] = $name . '_' . $phase . '_' . $hook;
459
460
461
          }
          // Ensure uniqueness.
          $cache[$hook][$phase_key] = array_unique($cache[$hook][$phase_key]);
462
463
464
465
        }
      }
    }
  }
466
467
468
}

/**
469
 * Rebuild the theme registry cache.
470
471
 *
 * @param $theme
472
 *   The loaded $theme object as returned by list_themes().
473
474
475
476
477
 * @param $base_theme
 *   An array of loaded $theme objects representing the ancestor themes in
 *   oldest first order.
 * @param theme_engine
 *   The name of the theme engine.
478
 */
479
function _theme_build_registry($theme, $base_theme, $theme_engine) {
480
  $cache = array();
481
482
  // First, process the theme hooks advertised by modules. This will
  // serve as the basic registry.
483
  foreach (module_implements('theme') as $module) {
484
485
486
487
488
    _theme_process_registry($cache, $module, 'module', $module, drupal_get_path('module', $module));
  }

  // Process each base theme.
  foreach ($base_theme as $base) {
489
    // If the base theme uses a theme engine, process its hooks.
490
491
492
493
494
    $base_path = dirname($base->filename);
    if ($theme_engine) {
      _theme_process_registry($cache, $theme_engine, 'base_theme_engine', $base->name, $base_path);
    }
    _theme_process_registry($cache, $base->name, 'base_theme', $base->name, $base_path);
495
496
  }

497
  // And then the same thing, but for the theme.
498
  if ($theme_engine) {
499
    _theme_process_registry($cache, $theme_engine, 'theme_engine', $theme->name, dirname($theme->filename));
500
501
  }

502
503
  // Finally, hooks provided by the theme itself.
  _theme_process_registry($cache, $theme->name, 'theme', $theme->name, dirname($theme->filename));
504

505
  // Let modules alter the registry.
506
  drupal_alter('theme_registry', $cache);
507
508
509
510
511
512
513
514
515

  // Optimize the registry to not have empty arrays for functions.
  foreach ($cache as $hook => $info) {
    foreach (array('preprocess functions', 'process functions') as $phase) {
      if (empty($info[$phase])) {
        unset($cache[$hook][$phase]);
      }
    }
  }
516
517
518
  return $cache;
}

Dries's avatar
   
Dries committed
519
/**
520
 * Return a list of all currently available themes.
Dries's avatar
   
Dries committed
521
 *
522
523
 * Retrieved from the database, if available and the site is not in maintenance
 * mode; otherwise compiled freshly from the filesystem.
524
 *
Dries's avatar
   
Dries committed
525
 * @param $refresh
526
 *   Whether to reload the list of themes from the database. Defaults to FALSE.
527
 * @return
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
 *   An associative array of the currently available themes. The keys are the
 *   names of the themes and the values are objects having the following
 *   properties:
 *   - 'filename': The name of the .info file.
 *   - 'name': The name of the theme.
 *   - 'status': 1 for enabled, 0 for disabled themes.
 *   - 'info': The contents of the .info file.
 *   - 'stylesheets': A two dimensional array, using the first key for the
 *     'media' attribute (e.g. 'all'), the second for the name of the file
 *     (e.g. style.css). The value is a complete filepath
 *     (e.g. themes/garland/style.css).
 *   - 'scripts': An associative array of JavaScripts, using the filename as key
 *     and the complete filepath as value.
 *   - 'engine': The name of the theme engine.
 *   - 'base theme': The name of the base theme.
Dries's avatar
   
Dries committed
543
 */
544
function list_themes($refresh = FALSE) {
545
  static $list = array();
Dries's avatar
   
Dries committed
546
547

  if ($refresh) {
548
    $list = array();
Dries's avatar
   
Dries committed
549
550
  }

551
  if (empty($list)) {
Dries's avatar
   
Dries committed
552
    $list = array();
553
554
    $themes = array();
    // Extract from the database only when it is available.
555
556
    // Also check that the site is not in the middle of an install or update.
    if (db_is_active() && !defined('MAINTENANCE_MODE')) {
557
558
      $result = db_query("SELECT * FROM {system} WHERE type = :theme", array(':theme' => 'theme'));
      foreach ($result as $theme) {
559
560
561
        if (file_exists($theme->filename)) {
          $theme->info = unserialize($theme->info);
          $themes[] = $theme;
562
        }
563
564
565
      }
    }
    else {
566
      // Scan the installation when the database should not be read.
567
      $themes = _system_get_theme_data();
568
569
570
571
572
    }

    foreach ($themes as $theme) {
      foreach ($theme->info['stylesheets'] as $media => $stylesheets) {
        foreach ($stylesheets as $stylesheet => $path) {
573
          $theme->stylesheets[$media][$stylesheet] = $path;
574
        }
575
576
577
578
      }
      foreach ($theme->info['scripts'] as $script => $path) {
        if (file_exists($path)) {
          $theme->scripts[$script] = $path;
579
        }
Dries's avatar
   
Dries committed
580
      }
581
582
      if (isset($theme->info['engine'])) {
        $theme->engine = $theme->info['engine'];
Dries's avatar
   
Dries committed
583
      }
584
585
586
      if (isset($theme->info['base theme'])) {
        $theme->base_theme = $theme->info['base theme'];
      }
587
588
589
590
591
      // Status is normally retrieved from the database. Add zero values when
      // read from the installation directory to prevent notices.
      if (!isset($theme->status)) {
        $theme->status = 0;
      }
592
      $list[$theme->name] = $theme;
Dries's avatar
   
Dries committed
593
594
595
596
597
598
    }
  }

  return $list;
}

Dries's avatar
   
Dries committed
599
/**
600
601
602
603
604
605
606
607
 * Generate the themed output.
 *
 * All requests for theme hooks must go through this function. It examines
 * the request and routes it to the appropriate theme function. The theme
 * registry is checked to determine which implementation to use, which may
 * be a function or a template.
 *
 * If the implementation is a template, the arguments are converted to a
608
609
610
 * $variables array. This array is then modified by the module implementing
 * the hook, theme engine (if applicable) and the theme. The following
 * functions may be used to modify the $variables array. They are processed in
611
612
 * two distinct phases; "preprocess" and "process" functions. The order it is
 * listed here is the order in which it will execute.
613
 *
614
615
 * - template_preprocess(&$variables)
 *   This sets a default set of variables for all template implementations.
616
 *
617
618
619
 * - template_preprocess_HOOK(&$variables)
 *   This is the first preprocessor called specific to the hook; it should be
 *   implemented by the module that registers it.
620
 *
621
622
623
 * - MODULE_preprocess(&$variables)
 *   This will be called for all templates; it should only be used if there
 *   is a real need. It's purpose is similar to template_preprocess().
624
 *
625
626
627
 * - MODULE_preprocess_HOOK(&$variables)
 *   This is for modules that want to alter or provide extra variables for
 *   theming hooks not registered to itself. For example, if a module named
628
 *   "foo" wanted to alter the $classes_array variable for the hook "node" a
629
630
 *   preprocess function of foo_preprocess_node() can be created to intercept
 *   and alter the variable.
631
 *
632
633
634
 * - ENGINE_engine_preprocess(&$variables)
 *   This function should only be implemented by theme engines and exists
 *   so that it can set necessary variables for all hooks.
635
 *
636
637
638
639
640
 * - ENGINE_engine_preprocess_HOOK(&$variables)
 *   This is the same as the previous function, but it is called for a single
 *   theming hook.
 *
 * - THEME_preprocess(&$variables)
641
 *   This is for themes that want to alter or provide extra variables. For
642
643
 *   example, if a theme named "foo" wanted to alter the $classes_array variable
 *   for the hook "node" a preprocess function of foo_preprocess_node() can be
644
 *   created to intercept and alter the variable.
645
 *
646
647
648
 * - THEME_preprocess_HOOK(&$variables)
 *   The same applies from the previous function, but it is called for a
 *   specific hook.
Dries's avatar
   
Dries committed
649
 *
650
651
652
653
654
655
656
657
658
659
660
661
662
663
 * - template_process(&$variables)
 *   This sets a default set of variables for all template implementations.
 *
 * - template_process_HOOK(&$variables)
 *   This is the first processor called specific to the hook; it should be
 *   implemented by the module that registers it.
 *
 * - MODULE_process(&$variables)
 *   This will be called for all templates; it should only be used if there
 *   is a real need. It's purpose is similar to template_process().
 *
 * - MODULE_process_HOOK(&$variables)
 *   This is for modules that want to alter or provide extra variables for
 *   theming hooks not registered to itself. For example, if a module named
664
 *   "foo" wanted to alter the $classes_array variable for the hook "node" a
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
 *   process function of foo_process_node() can be created to intercept
 *   and alter the variable.
 *
 * - ENGINE_engine_process(&$variables)
 *   This function should only be implemented by theme engines and exists
 *   so that it can set necessary variables for all hooks.
 *
 * - ENGINE_engine_process_HOOK(&$variables)
 *   This is the same as the previous function, but it is called for a single
 *   theming hook.
 *
 * - ENGINE_process(&$variables)
 *   This is meant to be used by themes that utilize a theme engine. It is
 *   provided so that the processor is not locked into a specific theme.
 *   This makes it easy to share and transport code but theme authors must be
 *   careful to prevent fatal re-declaration errors when using sub-themes that
 *   have their own processor named exactly the same as its base theme. In
 *   the default theme engine (PHPTemplate), sub-themes will load their own
 *   template.php file in addition to the one used for its parent theme. This
 *   increases the risk for these errors. A good practice is to use the engine
 *   name for the base theme and the theme name for the sub-themes to minimize
 *   this possibility.
 *
 * - ENGINE_process_HOOK(&$variables)
 *   The same applies from the previous function, but it is called for a
 *   specific hook.
 *
 * - THEME_process(&$variables)
 *   These functions are based upon the raw theme; they should primarily be
 *   used by themes that do not use an engine or by sub-themes. It serves the
 *   same purpose as ENGINE_process().
 *
 * - THEME_process_HOOK(&$variables)
 *   The same applies from the previous function, but it is called for a
 *   specific hook.
 *
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
 * If the implementation is a function, only the hook-specific preprocess
 * and process functions (the ones ending in _HOOK) are called from the
 * above list. There are two reasons why the non-hook-specific preprocess
 * and process functions (the ones not ending in _HOOK) are not called for
 * function-implemented theme hooks:
 *
 * - Function-implemented theme hooks need to be fast, and calling the
 *   non-hook-specific preprocess and process functions on them would incur
 *   a noticeable performance penalty.
 *
 * - Function-implemented theme hooks can only make use of variables
 *   declared as arguments within the hook_theme() function that registers
 *   the theme hook, and cannot make use of additional generic variables.
 *   For the most part, non-hook-specific preprocess and process functions
 *   add/modify variables other than the theme hook's arguments, variables
 *   that are potentially useful in template files, but unavailable to
 *   function implementations.
 *
 * For template-implemented theme hooks, there are two special variables that
 * these preprocess and process functions can set:
721
722
723
724
 *   'template_file' and 'template_files'. These will be merged together
 *   to form a list of 'suggested' alternate template files to use, in
 *   reverse order of priority. template_file will always be a higher
 *   priority than items in template_files. theme() will then look for these
725
726
727
728
729
730
731
732
733
734
735
736
 *   files, one at a time, and use the first one that exists. If none exists,
 *   theme() will use the original registered file for the theme hook.
 *
 * For function-implemented theme hooks, there are two special variables that
 * these preprocess and process functions can set:
 *   'theme_function' and 'theme_functions'. These will be merged together
 *   to form a list of 'suggested' alternate functions to use, in
 *   reverse order of priority. theme_function will always be a higher
 *   priority than items in theme_functions. theme() will then call the
 *   highest priority function that exists. If none exists, theme() will call
 *   the original registered function for the theme hook.
 *
737
 * @param $hook
738
739
740
741
742
743
 *   The name of the theme function to call. May be an array, in which
 *   case the first hook that actually has an implementation registered
 *   will be used. This can be used to choose 'fallback' theme implementations,
 *   so that if the specific theme hook isn't implemented anywhere, a more
 *   generic one will be used. This can allow themes to create specific theme
 *   implementations for named objects.
744
745
746
747
 * @param ...
 *   Additional arguments to pass along to the theme function.
 * @return
 *   An HTML string that generates the themed output.
Dries's avatar
   
Dries committed
748
 */
Dries's avatar
   
Dries committed
749
function theme() {
750
  $args = func_get_args();
751
  $hook = array_shift($args);
752

753
754
  static $hooks = NULL;
  if (!isset($hooks)) {
755
    drupal_theme_initialize();
756
    $hooks = theme_get_registry();
757
  }
758

759
760
761
762
763
764
765
766
767
  if (is_array($hook)) {
    foreach ($hook as $candidate) {
      if (isset($hooks[$candidate])) {
        break;
      }
    }
    $hook = $candidate;
  }

768
769
  if (!isset($hooks[$hook])) {
    return;
770
771
  }

772
  $info = $hooks[$hook];
773
774
775
  global $theme_path;
  $temp = $theme_path;
  // point path_to_theme() to the currently used theme path:
776
  $theme_path = $info['theme path'];
Dries's avatar
   
Dries committed
777

778
  // Include a file if the theme function or variable processor is held elsewhere.
779
780
781
  if (!empty($info['includes'])) {
    foreach ($info['includes'] as $include_file) {
      include_once DRUPAL_ROOT . '/' . $include_file;
782
783
    }
  }
784
785
  if (isset($info['function'])) {
    // The theme call is a function.
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820

    // If a theme function that does not expect a renderable array is called
    // with a renderable array as the only argument (via drupal_render), then
    // we take the arguments from the properties of the renderable array. If
    // missing, use hook_theme() defaults.
    if (isset($args[0]) && is_array($args[0]) && isset($args[0]['#theme']) && count($info['arguments']) > 1) {
      $new_args = array();
      foreach ($info['arguments'] as $name => $default) {
        $new_args[] = isset($args[0]["#$name"]) ? $args[0]["#$name"] : $default;
      }
      $args = $new_args;
    }

    // Invoke the variable processors, if any.
    // We minimize the overhead for theming hooks that have no processors and
    // are called many times per page request by caching '_no_processors'. If
    // we do have processors, then the overhead of calling them overshadows the
    // overhead of calling empty().
    if (!isset($info['_no_processors'])) {
      if (!empty($info['preprocess functions']) || !empty($info['process functions'])) {
        $variables = array(
          'theme_functions' => array(),
        );
        if (!empty($info['arguments'])) {
          $count = 0;
          foreach ($info['arguments'] as $name => $default) {
            $variables[$name] = isset($args[$count]) ? $args[$count] : $default;
            $count++;
          }
        }
        // We don't want a poorly behaved process function changing $hook.
        $hook_clone = $hook;
        foreach (array('preprocess functions', 'process functions') as $phase) {
          if (!empty($info[$phase])) {
            foreach ($info[$phase] as $processor_function) {
821
              if (function_exists($processor_function)) {
822
823
824
825
                $processor_function($variables, $hook_clone);
              }
            }
          }
826
        }
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
        if (!empty($info['arguments'])) {
          $count = 0;
          foreach ($info['arguments'] as $name => $default) {
            $args[$count] = $variables[$name];
            $count++;
          }
        }

        // Get suggestions for alternate functions out of the variables that
        // were set. This lets us dynamically choose a function from a list.
        // The order is FILO, so this array is ordered from least appropriate
        // functions to most appropriate last.
        $suggestions = array();
        if (isset($variables['theme_functions'])) {
          $suggestions = $variables['theme_functions'];
        }
        if (isset($variables['theme_function'])) {
          $suggestions[] = $variables['theme_function'];
        }
        foreach (array_reverse($suggestions) as $suggestion) {
847
          if (function_exists($suggestion)) {
848
849
850
851
852
853
854
            $info['function'] = $suggestion;
            break;
          }
        }
      }
      else {
        $hooks[$hook]['_no_processors'] = TRUE;
855
      }
856
857
858
    }

    // Call the function.
859
    if (function_exists($info['function'])) {
Dries's avatar
   
Dries committed
860
861
      $output = call_user_func_array($info['function'], $args);
    }
Dries's avatar
   
Dries committed
862
  }
863
864
865
866
867
868
869
870
871
872
873
874
  else {
    // The theme call is a template.
    $variables = array(
      'template_files' => array()
    );
    if (!empty($info['arguments'])) {
      $count = 0;
      foreach ($info['arguments'] as $name => $default) {
        $variables[$name] = isset($args[$count]) ? $args[$count] : $default;
        $count++;
      }
    }
Dries's avatar
   
Dries committed
875

876
877
878
879
880
881
882
883
884
    // default render function and extension.
    $render_function = 'theme_render_template';
    $extension = '.tpl.php';

    // Run through the theme engine variables, if necessary
    global $theme_engine;
    if (isset($theme_engine)) {
      // If theme or theme engine is implementing this, it may have
      // a different extension and a different renderer.
885
      if ($info['type'] != 'module') {
886
887
        if (function_exists($theme_engine . '_render_template')) {
          $render_function = $theme_engine . '_render_template';
888
        }
889
        $extension_function = $theme_engine . '_extension';
890
891
892
893
894
895
        if (function_exists($extension_function)) {
          $extension = $extension_function();
        }
      }
    }

896
897
898
    // This construct ensures that we can keep a reference through
    // call_user_func_array.
    $args = array(&$variables, $hook);
899
900
901
    foreach (array('preprocess functions', 'process functions') as $phase) {
      if (!empty($info[$phase])) {
        foreach ($info[$phase] as $processor_function) {
902
          if (function_exists($processor_function)) {
903
904
            call_user_func_array($processor_function, $args);
          }
905
        }
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
      }
    }

    // Get suggestions for alternate templates out of the variables
    // that were set. This lets us dynamically choose a template
    // from a list. The order is FILO, so this array is ordered from
    // least appropriate first to most appropriate last.
    $suggestions = array();

    if (isset($variables['template_files'])) {
      $suggestions = $variables['template_files'];
    }
    if (isset($variables['template_file'])) {
      $suggestions[] = $variables['template_file'];
    }

    if ($suggestions) {
923
      $template_file = drupal_discover_template($info['theme paths'], $suggestions, $extension);
924
925
926
    }

    if (empty($template_file)) {
927
928
      $template_file = $info['template'] . $extension;
      if (isset($info['path'])) {
929
        $template_file = $info['path'] . '/' . $template_file;
930
931
      }
    }
932
    $output = $render_function($template_file, $variables);
Dries's avatar
   
Dries committed
933
  }
934
935
936
  // restore path_to_theme()
  $theme_path = $temp;
  return $output;
937
938
939
}

/**
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
 * Determine and return which template file will generate the output.
 *
 * This helper allows the theme system to pick the template at runtime instead
 * of build time.
 *
 * @see template_page_suggestions()
 * @see template_preprocess_block()
 *
 * @param $paths
 *   The paths where templates can be found. See _theme_process_registry()
 *   'theme paths' for more information.
 * @param $suggestions
 *   The possible template names. These are derived from
 *   $variables['template_files'] and $variables['template_file], defined by
 *   preprocess functions. Each file is checked on every path in the order of
 *   precedence defined by theme().
 * @return
 *   The filepath to the template that will generate the output. If none is
 *   found, then theme() will use the 'template' as set by
 *   _theme_process_registry().
 *
 * @see _theme_process_registry()
 * @see theme()
963
 */
964
function drupal_discover_template($paths, $suggestions, $extension = '.tpl.php') {
965
966
  global $theme_engine;

967
968
969
970
  // Remove slashes or null to prevent files from being included from
  // an unexpected location (especially on Windows servers).
  $extension = str_replace(array("/", "\\", "\0"), '', $extension);

971
  // Loop through all paths and suggestions in FIFO order.
972
  $suggestions = array_reverse($suggestions);
973
  $paths = array_reverse($paths);
974
  foreach ($suggestions as $suggestion) {
975
    if (!empty($suggestion)) {
976
      $suggestion = str_replace(array("/", "\\", "\0"), '', $suggestion);
977
      foreach ($paths as $path) {
978
        if (file_exists($file = $path . '/' . $suggestion . $extension)) {
979
980
981
          return $file;
        }
      }
982
    }
Dries's avatar
   
Dries committed
983
984
985
986
  }
}

/**
987
988
989
990
991
992
993
994
 * Return the path to the current themed element.
 *
 * It can point to the active theme or the module handling a themed implementation.
 * For example, when invoked within the scope of a theming call it will depend
 * on where the theming function is handled. If implemented from a module, it
 * will point to the module. If implemented from the active theme, it will point
 * to the active theme. When called outside the scope of a theming call, it will
 * always point to the active theme.
Dries's avatar
   
Dries committed
995
 */
Dries's avatar
   
Dries committed
996
function path_to_theme() {
997
  global $theme_path;
Dries's avatar
   
Dries committed
998

999
  if (!isset($theme_path)) {
1000
    drupal_theme_initialize();
1001
1002
  }

1003
  return $theme_path;
1004
1005
}

1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
/**
 * Find overridden theme functions. Called by themes and/or theme engines to
 * easily discover theme functions.
 *
 * @param $cache
 *   The existing cache of theme hooks to test against.
 * @param $prefixes
 *   An array of prefixes to test, in reverse order of importance.
 *
 * @return $templates
 *   The functions found, suitable for returning from hook_theme;
 */
function drupal_find_theme_functions($cache, $prefixes) {
  $templates = array();
  $functions = get_defined_functions();

  foreach ($cache as $hook => $info) {
    foreach ($prefixes as $prefix) {
      if (!empty($info['pattern'])) {
1025
        $matches = preg_grep('/^' . $prefix . '_' . $info['pattern'] . '/', $functions['user']);
1026
1027
        if ($matches) {
          foreach ($matches as $match) {
1028
            $new_hook = str_replace($prefix . '_', '', $match);
1029
1030
1031
1032
1033
1034
1035
            $templates[$new_hook] = array(
              'function' => $match,
              'arguments' => $info['arguments'],
            );
          }
        }
      }
1036
      if (function_exists($prefix . '_' . $hook)) {
1037
        $templates[$hook] = array(
1038
          'function' => $prefix . '_' . $hook,
1039
        );
1040
1041
1042
1043
1044
1045
        // Ensure that the pattern is maintained from base themes to its sub-themes.
        // Each sub-theme will have their functions scanned so the pattern must be
        // held for subsequent runs.
        if (isset($info['pattern'])) {
          $templates[$hook]['pattern'] = $info['pattern'];
        }
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
      }
    }
  }

  return $templates;
}

/**
 * Find overridden theme templates. Called by themes and/or theme engines to
 * easily discover templates.
 *
 * @param $cache
 *   The existing cache of theme hooks to test against.
 * @param $extension
 *   The extension that these templates will have.
 * @param $path
 *   The path to search.
 */
function drupal_find_theme_templates($cache, $extension, $path) {
  $templates = array();

1067
1068
1069
1070
  // Collect paths to all sub-themes grouped by base themes. These will be
  // used for filtering. This allows base themes to have sub-themes in its
  // folder hierarchy without affecting the base themes template discovery.
  $theme_paths = array();
1071
  foreach (list_themes() as $theme_info) {
1072
1073
1074
1075
1076
1077
1078
1079
1080
    if (!empty($theme_info->base_theme)) {
      $theme_paths[$theme_info->base_theme][$theme_info->name] = dirname($theme_info->filename);
    }
  }
  foreach ($theme_paths as $basetheme => $subthemes) {
    foreach ($subthemes as $subtheme => $subtheme_path) {
      if (isset($theme_paths[$subtheme])) {
        $theme_paths[$basetheme] = array_merge($theme_paths[$basetheme], $theme_paths[$subtheme]);
      }
1081
1082
    }
  }
1083
1084
  global $theme;
  $subtheme_paths = isset($theme_paths[$theme]) ? $theme_paths[$theme] : array();
1085

1086
  // Escape the periods in the extension.
1087
  $regex = '/' . str_replace('.', '\.', $extension) . '$/';
1088
1089
1090
1091
  // Because drupal_system_listing works the way it does, we check for real
  // templates separately from checking for patterns.
  $files = drupal_system_listing($regex, $path, 'name', 0);
  foreach ($files as $template => $file) {
1092
    // Ignore sub-theme templates for the current theme.
1093
    if (strpos($file->uri, str_replace($subtheme_paths, '', $file->uri)) !== 0) {
1094
1095
      continue;
    }
1096
1097
1098
1099
1100
1101
    // Chop off the remaining extensions if there are any. $template already
    // has the rightmost extension removed, but there might still be more,
    // such as with .tpl.php, which still has .tpl in $template at this point.
    if (($pos = strpos($template, '.')) !== FALSE) {
      $template = substr($template, 0, $pos);
    }
1102
1103
1104
1105
1106
    // Transform - in filenames to _ to match function naming scheme
    // for the purposes of searching.
    $hook = strtr($template, '-', '_');
    if (isset($cache[$hook])) {
      $templates[$hook] = array(
1107
        'template' => $template,
1108
        'path' => dirname($file->uri),
1109
1110
      );
    }
1111
1112
1113
1114
1115
1116
    // Ensure that the pattern is maintained from base themes to its sub-themes.
    // Each sub-theme will have their templates scanned so the pattern must be
    // held for subsequent runs.
    if (isset($cache[$hook]['pattern'])) {
      $templates[$hook]['pattern'] = $cache[$hook]['pattern'];
    }
1117
1118
1119
1120
1121
1122
  }

  $patterns = array_keys($files);

  foreach ($cache as $hook => $info) {
    if (!empty($info['pattern'])) {
1123
1124
1125
1126
      // Transform _ in pattern to - to match file naming scheme
      // for the purposes of searching.
      $pattern = strtr($info['pattern'], '_', '-');

1127
      $matches = preg_grep('/^' . $pattern . '/', $patterns);
1128
1129
1130
      if ($matches) {
        foreach ($matches as $match) {
          $file = substr($match, 0, strpos($match, '.'));
1131
1132
          // Put the underscores back in for the hook name and register this pattern.
          $templates[strtr($file, '-', '_')] = array(
1133
            'template' => $file,
1134
            'path' => dirname($files[$match]->uri),
1135
1136
1137
1138
1139
1140
1141
1142
1143
            'arguments' => $info['arguments'],
          );
        }
      }
    }
  }
  return $templates;
}

Dries's avatar
   
Dries committed
1144
1145
1146
/**
 * Retrieve an associative array containing the settings for a theme.
 *
1147
 * The final settings are arrived at by merging the default settings,
Dries's avatar
   
Dries committed
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
 * the site-wide settings, and the settings defined for the specific theme.
 * If no $key was specified, only the site-wide theme defaults are retrieved.
 *
 * The default values for each of settings are also defined in this function.
 * To add new settings, add their default values here, and then add form elements
 * to system_theme_settings() in system.module.
 *
 * @param $key
 *  The template/style value for a given theme.
 *
 * @return
 *   An associative array containing theme settings.
 */
1161
function theme_get_settings($key = NULL) {
Dries's avatar
   
Dries committed
1162
  $defaults = array(
1163
1164
1165
1166
    'default_logo'                     =>  1,
    'logo_path'                        =>  '',
    'default_favicon'                  =>  1,
    'favicon_path'                     =>  '',
1167
1168
    // Use the IANA-registered MIME type for ICO files as default.
    'favicon_mimetype'                 =>  'image/vnd.microsoft.icon',
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
    'main_menu'                        =>  1,
    'secondary_menu'                   =>  1,
    'toggle_logo'                      =>  1,
    'toggle_favicon'                   =>  1,
    'toggle_name'                      =>  1,
    'toggle_search'                    =>  0,
    'toggle_slogan'                    =>  0,
    'toggle_node_user_picture'         =>  0,
    'toggle_comment_user_picture'      =>  0,
    'toggle_comment_user_verification' =>  1,
    'toggle_main_menu'                 =>  1,
    'toggle_secondary_menu'            =>  1,
Dries's avatar
   
Dries committed
1181
1182
1183
1184
1185
  );

  $settings = array_merge($defaults, variable_get('theme_settings', array()));

  if ($key) {
1186
    $settings = array_merge($settings, variable_get(str_replace('/', '_', 'theme_' . $key . '_settings'), array()));
Dries's avatar
   
Dries committed
1187
1188
  }

1189
  // Only offer search box if search.module is enabled.
1190
1191
  if (!defined('MAINTENANCE_MODE') && module_exists('search') && user_access('search content')) {
    $settings['toggle_search'] = 1;
1192
1193
  }

Dries's avatar
   
Dries committed
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
  return $settings;
}

/**
 * Retrieve a setting for the current theme.
 * This function is designed for use from within themes & engines
 * to determine theme settings made in the admin interface.
 *
 * Caches values for speed (use $refresh = TRUE to refresh cache)
 *
 * @param $setting_name
 *  The name of the setting to be retrieved.
 *
 * @param $refresh
 *  Whether to reload the cache of settings.
 *
 * @return
 *   The value of the requested setting, NULL if the setting does not exist.
 */
1213
function theme_get_setting($setting_name, $refresh = FALSE) {
1214
  global $theme_key;
Dries's avatar
   
Dries committed
1215
1216
1217
  static $settings;

  if (empty($settings) || $refresh) {
1218
    $settings = theme_get_settings($theme_key);
Dries's avatar
   
Dries committed
1219
1220
1221
1222
1223
1224