PageRenderTime 133ms CodeModel.GetById 3ms app.highlight 116ms RepoModel.GetById 2ms app.codeStats 0ms

/includes/theme.inc

https://bitbucket.org/smerrill/drupalcamp-hudson
Pascal | 2028 lines | 1156 code | 112 blank | 760 comment | 166 complexity | 3a6a3c6b695cee6bb9f034d3f8f259d4 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2// $Id: theme.inc,v 1.415.2.27 2010/03/01 10:02:01 goba Exp $
   3
   4/**
   5 * @file
   6 * The theme system, which controls the output of Drupal.
   7 *
   8 * The theme system allows for nearly all output of the Drupal system to be
   9 * customized by user themes.
  10 *
  11 * @ingroup themeable
  12 */
  13
  14/**
  15 * @name Content markers
  16 * @{
  17 * Markers used by theme_mark() and node_mark() to designate content.
  18 * @see theme_mark(), node_mark()
  19 */
  20define('MARK_READ',    0);
  21define('MARK_NEW',     1);
  22define('MARK_UPDATED', 2);
  23/**
  24 * @} End of "Content markers".
  25 */
  26
  27/**
  28 * Initialize the theme system by loading the theme.
  29 */
  30function init_theme() {
  31  global $theme, $user, $custom_theme, $theme_key;
  32
  33  // If $theme is already set, assume the others are set, too, and do nothing
  34  if (isset($theme)) {
  35    return;
  36  }
  37
  38  drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
  39  $themes = list_themes();
  40
  41  // Only select the user selected theme if it is available in the
  42  // list of enabled themes.
  43  $theme = !empty($user->theme) && !empty($themes[$user->theme]->status) ? $user->theme : variable_get('theme_default', 'garland');
  44
  45  // Allow modules to override the present theme... only select custom theme
  46  // if it is available in the list of installed themes.
  47  $theme = $custom_theme && $themes[$custom_theme] ? $custom_theme : $theme;
  48
  49  // Store the identifier for retrieving theme settings with.
  50  $theme_key = $theme;
  51
  52  // Find all our ancestor themes and put them in an array.
  53  $base_theme = array();
  54  $ancestor = $theme;
  55  while ($ancestor && isset($themes[$ancestor]->base_theme)) {
  56    $base_theme[] = $new_base_theme = $themes[$themes[$ancestor]->base_theme];
  57    $ancestor = $themes[$ancestor]->base_theme;
  58  }
  59  _init_theme($themes[$theme], array_reverse($base_theme));
  60}
  61
  62/**
  63 * Initialize the theme system given already loaded information. This
  64 * function is useful to initialize a theme when no database is present.
  65 *
  66 * @param $theme
  67 *   An object with the following information:
  68 *     filename
  69 *       The .info file for this theme. The 'path' to
  70 *       the theme will be in this file's directory. (Required)
  71 *     owner
  72 *       The path to the .theme file or the .engine file to load for
  73 *       the theme. (Required)
  74 *     stylesheet
  75 *       The primary stylesheet for the theme. (Optional)
  76 *     engine
  77 *       The name of theme engine to use. (Optional)
  78 * @param $base_theme
  79 *    An optional array of objects that represent the 'base theme' if the
  80 *    theme is meant to be derivative of another theme. It requires
  81 *    the same information as the $theme object. It should be in
  82 *    'oldest first' order, meaning the top level of the chain will
  83 *    be first.
  84 * @param $registry_callback
  85 *   The callback to invoke to set the theme registry.
  86 */
  87function _init_theme($theme, $base_theme = array(), $registry_callback = '_theme_load_registry') {
  88  global $theme_info, $base_theme_info, $theme_engine, $theme_path;
  89  $theme_info = $theme;
  90  $base_theme_info = $base_theme;
  91
  92  $theme_path = dirname($theme->filename);
  93
  94  // Prepare stylesheets from this theme as well as all ancestor themes.
  95  // We work it this way so that we can have child themes override parent
  96  // theme stylesheets easily.
  97  $final_stylesheets = array();
  98
  99  // Grab stylesheets from base theme
 100  foreach ($base_theme as $base) {
 101    if (!empty($base->stylesheets)) {
 102      foreach ($base->stylesheets as $media => $stylesheets) {
 103        foreach ($stylesheets as $name => $stylesheet) {
 104          $final_stylesheets[$media][$name] = $stylesheet;
 105        }
 106      }
 107    }
 108  }
 109
 110  // Add stylesheets used by this theme.
 111  if (!empty($theme->stylesheets)) {
 112    foreach ($theme->stylesheets as $media => $stylesheets) {
 113      foreach ($stylesheets as $name => $stylesheet) {
 114        $final_stylesheets[$media][$name] = $stylesheet;
 115      }
 116    }
 117  }
 118
 119  // And now add the stylesheets properly
 120  foreach ($final_stylesheets as $media => $stylesheets) {
 121    foreach ($stylesheets as $stylesheet) {
 122      drupal_add_css($stylesheet, 'theme', $media);
 123    }
 124  }
 125
 126  // Do basically the same as the above for scripts
 127  $final_scripts = array();
 128
 129  // Grab scripts from base theme
 130  foreach ($base_theme as $base) {
 131    if (!empty($base->scripts)) {
 132      foreach ($base->scripts as $name => $script) {
 133        $final_scripts[$name] = $script;
 134      }
 135    }
 136  }
 137
 138  // Add scripts used by this theme.
 139  if (!empty($theme->scripts)) {
 140    foreach ($theme->scripts as $name => $script) {
 141      $final_scripts[$name] = $script;
 142    }
 143  }
 144
 145  // Add scripts used by this theme.
 146  foreach ($final_scripts as $script) {
 147    drupal_add_js($script, 'theme');
 148  }
 149
 150  $theme_engine = NULL;
 151
 152  // Initialize the theme.
 153  if (isset($theme->engine)) {
 154    // Include the engine.
 155    include_once './'. $theme->owner;
 156
 157    $theme_engine = $theme->engine;
 158    if (function_exists($theme_engine .'_init')) {
 159      foreach ($base_theme as $base) {
 160        call_user_func($theme_engine .'_init', $base);
 161      }
 162      call_user_func($theme_engine .'_init', $theme);
 163    }
 164  }
 165  else {
 166    // include non-engine theme files
 167    foreach ($base_theme as $base) {
 168      // Include the theme file or the engine.
 169      if (!empty($base->owner)) {
 170        include_once './'. $base->owner;
 171      }
 172    }
 173    // and our theme gets one too.
 174    if (!empty($theme->owner)) {
 175      include_once './'. $theme->owner;
 176    }
 177  }
 178
 179  $registry_callback($theme, $base_theme, $theme_engine);
 180}
 181
 182/**
 183 * Retrieve the stored theme registry. If the theme registry is already
 184 * in memory it will be returned; otherwise it will attempt to load the
 185 * registry from cache. If this fails, it will construct the registry and
 186 * cache it.
 187 */
 188function theme_get_registry($registry = NULL) {
 189  static $theme_registry = NULL;
 190  if (isset($registry)) {
 191    $theme_registry = $registry;
 192  }
 193
 194  return $theme_registry;
 195}
 196
 197/**
 198 * Store the theme registry in memory.
 199 */
 200function _theme_set_registry($registry) {
 201  // Pass through for setting of static variable.
 202  return theme_get_registry($registry);
 203}
 204
 205/**
 206 * Get the theme_registry cache from the database; if it doesn't exist, build
 207 * it.
 208 *
 209 * @param $theme
 210 *   The loaded $theme object.
 211 * @param $base_theme
 212 *   An array of loaded $theme objects representing the ancestor themes in
 213 *   oldest first order.
 214 * @param theme_engine
 215 *   The name of the theme engine.
 216 */
 217function _theme_load_registry($theme, $base_theme = NULL, $theme_engine = NULL) {
 218  // Check the theme registry cache; if it exists, use it.
 219  $cache = cache_get("theme_registry:$theme->name", 'cache');
 220  if (isset($cache->data)) {
 221    $registry = $cache->data;
 222  }
 223  else {
 224    // If not, build one and cache it.
 225    $registry = _theme_build_registry($theme, $base_theme, $theme_engine);
 226    _theme_save_registry($theme, $registry);
 227  }
 228  _theme_set_registry($registry);
 229}
 230
 231/**
 232 * Write the theme_registry cache into the database.
 233 */
 234function _theme_save_registry($theme, $registry) {
 235  cache_set("theme_registry:$theme->name", $registry);
 236}
 237
 238/**
 239 * Force the system to rebuild the theme registry; this should be called
 240 * when modules are added to the system, or when a dynamic system needs
 241 * to add more theme hooks.
 242 */
 243function drupal_rebuild_theme_registry() {
 244  cache_clear_all('theme_registry', 'cache', TRUE);
 245}
 246
 247/**
 248 * Process a single invocation of the theme hook. $type will be one
 249 * of 'module', 'theme_engine', 'base_theme_engine', 'theme', or 'base_theme'
 250 * and it tells us some important information.
 251 *
 252 * Because $cache is a reference, the cache will be continually
 253 * expanded upon; new entries will replace old entries in the
 254 * array_merge, but we are careful to ensure some data is carried
 255 * forward, such as the arguments a theme hook needs.
 256 *
 257 * An override flag can be set for preprocess functions. When detected the
 258 * cached preprocessors for the hook will not be merged with the newly set.
 259 * This can be useful to themes and theme engines by giving them more control
 260 * over how and when the preprocess functions are run.
 261 */
 262function _theme_process_registry(&$cache, $name, $type, $theme, $path) {
 263  $result = array();
 264  $function = $name .'_theme';
 265  if (function_exists($function)) {
 266    $result = $function($cache, $type, $theme, $path);
 267
 268    foreach ($result as $hook => $info) {
 269      $result[$hook]['type'] = $type;
 270      $result[$hook]['theme path'] = $path;
 271      // if function and file are left out, default to standard naming
 272      // conventions.
 273      if (!isset($info['template']) && !isset($info['function'])) {
 274        $result[$hook]['function'] = ($type == 'module' ? 'theme_' : $name .'_') . $hook;
 275      }
 276
 277      // Make sure include files is set so we don't generate notices later.
 278      if (!isset($info['include files'])) {
 279        $result[$hook]['include files'] = array();
 280      }
 281
 282      // If a path is set in the info, use what was set. Otherwise use the
 283      // default path. This is mostly so system.module can declare theme
 284      // functions on behalf of core .include files.
 285      // All files are included to be safe. Conditionally included
 286      // files can prevent them from getting registered.
 287      if (isset($info['file']) && !isset($info['path'])) {
 288        // First, check to see if the fully qualified file exists.
 289        $filename = './'. $path .'/'. $info['file'];
 290        if (file_exists($filename)) {
 291          require_once $filename;
 292          $result[$hook]['include files'][] = $filename;
 293        }
 294        else {
 295          $filename = './'. $info['file'];
 296          if (file_exists($filename)) {
 297            require_once $filename;
 298            $result[$hook]['include files'][] = $filename;
 299          }
 300        }
 301      }
 302      elseif (isset($info['file']) && isset($info['path'])) {
 303        $filename = './'. $info['path'] .'/'. $info['file'];
 304        if (file_exists($filename)) {
 305          require_once $filename;
 306          $result[$hook]['include files'][] = $filename;
 307        }
 308      }
 309
 310
 311      if (isset($info['template']) && !isset($info['path'])) {
 312        $result[$hook]['template'] = $path .'/'. $info['template'];
 313      }
 314      // If 'arguments' have been defined previously, carry them forward.
 315      // This should happen if a theme overrides a Drupal defined theme
 316      // function, for example.
 317      if (!isset($info['arguments']) && isset($cache[$hook])) {
 318        $result[$hook]['arguments'] = $cache[$hook]['arguments'];
 319      }
 320      // Likewise with theme paths. These are used for template naming suggestions.
 321      // Theme implementations can occur in multiple paths. Suggestions should follow.
 322      if (!isset($info['theme paths']) && isset($cache[$hook])) {
 323        $result[$hook]['theme paths'] = $cache[$hook]['theme paths'];
 324      }
 325      // Check for sub-directories.
 326      $result[$hook]['theme paths'][] = isset($info['path']) ? $info['path'] : $path;
 327
 328      // Check for default _preprocess_ functions. Ensure arrayness.
 329      if (!isset($info['preprocess functions']) || !is_array($info['preprocess functions'])) {
 330        $info['preprocess functions'] = array();
 331        $prefixes = array();
 332        if ($type == 'module') {
 333          // Default preprocessor prefix.
 334          $prefixes[] = 'template';
 335          // Add all modules so they can intervene with their own preprocessors. This allows them
 336          // to provide preprocess functions even if they are not the owner of the current hook.
 337          $prefixes += module_list();
 338        }
 339        elseif ($type == 'theme_engine' || $type == 'base_theme_engine') {
 340          // Theme engines get an extra set that come before the normally named preprocessors.
 341          $prefixes[] = $name .'_engine';
 342          // The theme engine also registers on behalf of the theme. The theme or engine name can be used.
 343          $prefixes[] = $name;
 344          $prefixes[] = $theme;
 345        }
 346        else {
 347          // This applies when the theme manually registers their own preprocessors.
 348          $prefixes[] = $name;
 349        }
 350
 351        foreach ($prefixes as $prefix) {
 352          if (function_exists($prefix .'_preprocess')) {
 353            $info['preprocess functions'][] = $prefix .'_preprocess';
 354          }
 355
 356          if (function_exists($prefix .'_preprocess_'. $hook)) {
 357            $info['preprocess functions'][] = $prefix .'_preprocess_'. $hook;
 358          }
 359
 360          if (!empty($info['original hook']) && function_exists($prefix .'_preprocess_'. $info['original hook'])) {
 361            $info['preprocess functions'][] = $prefix .'_preprocess_'. $info['original hook'];
 362          }
 363        }
 364      }
 365      // Check for the override flag and prevent the cached preprocess functions from being used.
 366      // This allows themes or theme engines to remove preprocessors set earlier in the registry build.
 367      if (!empty($info['override preprocess functions'])) {
 368        // Flag not needed inside the registry.
 369        unset($result[$hook]['override preprocess functions']);
 370      }
 371      elseif (isset($cache[$hook]['preprocess functions']) && is_array($cache[$hook]['preprocess functions'])) {
 372        $info['preprocess functions'] = array_merge($cache[$hook]['preprocess functions'], $info['preprocess functions']);
 373      }
 374      elseif (isset($info['original hook']) && isset($cache[$info['original hook']]['preprocess functions']) && is_array($cache[$info['original hook']]['preprocess functions'])) {
 375        $info['preprocess functions'] = array_merge($cache[$info['original hook']]['preprocess functions'], $info['preprocess functions']);
 376      }
 377      $result[$hook]['preprocess functions'] = $info['preprocess functions'];
 378    }
 379
 380    // Merge the newly created theme hooks into the existing cache.
 381    $cache = array_merge($cache, $result);
 382  }
 383
 384  // Let themes have preprocess functions even if they didn't register a template.
 385  if ($type == 'theme' || $type == 'base_theme') {
 386    foreach ($cache as $hook => $info) {
 387      // Check only if it's a template and not registered by the theme or engine.
 388      if (!empty($info['template']) && empty($result[$hook])) {
 389        if (!isset($info['preprocess functions'])) {
 390          $cache[$hook]['preprocess functions'] = array();
 391        }
 392        if (function_exists($name .'_preprocess')) {
 393          $cache[$hook]['preprocess functions'][] = $name .'_preprocess';
 394        }
 395        if (function_exists($name .'_preprocess_'. $hook)) {
 396          $cache[$hook]['preprocess functions'][] = $name .'_preprocess_'. $hook;
 397        }
 398        // Ensure uniqueness.
 399        $cache[$hook]['preprocess functions'] = array_unique($cache[$hook]['preprocess functions']);
 400      }
 401    }
 402  }
 403}
 404
 405/**
 406 * Rebuild the hook theme_registry cache.
 407 *
 408 * @param $theme
 409 *   The loaded $theme object.
 410 * @param $base_theme
 411 *   An array of loaded $theme objects representing the ancestor themes in
 412 *   oldest first order.
 413 * @param theme_engine
 414 *   The name of the theme engine.
 415 */
 416function _theme_build_registry($theme, $base_theme, $theme_engine) {
 417  $cache = array();
 418  // First, process the theme hooks advertised by modules. This will
 419  // serve as the basic registry.
 420  foreach (module_implements('theme') as $module) {
 421    _theme_process_registry($cache, $module, 'module', $module, drupal_get_path('module', $module));
 422  }
 423
 424  // Process each base theme.
 425  foreach ($base_theme as $base) {
 426    // If the base theme uses a theme engine, process its hooks.
 427    $base_path = dirname($base->filename);
 428    if ($theme_engine) {
 429      _theme_process_registry($cache, $theme_engine, 'base_theme_engine', $base->name, $base_path);
 430    }
 431    _theme_process_registry($cache, $base->name, 'base_theme', $base->name, $base_path);
 432  }
 433
 434  // And then the same thing, but for the theme.
 435  if ($theme_engine) {
 436    _theme_process_registry($cache, $theme_engine, 'theme_engine', $theme->name, dirname($theme->filename));
 437  }
 438
 439  // Finally, hooks provided by the theme itself.
 440  _theme_process_registry($cache, $theme->name, 'theme', $theme->name, dirname($theme->filename));
 441
 442  // Let modules alter the registry
 443  drupal_alter('theme_registry', $cache);
 444  return $cache;
 445}
 446
 447/**
 448 * Provides a list of currently available themes.
 449 *
 450 * If the database is active then it will be retrieved from the database.
 451 * Otherwise it will retrieve a new list.
 452 *
 453 * @param $refresh
 454 *   Whether to reload the list of themes from the database.
 455 * @return
 456 *   An array of the currently available themes.
 457 */
 458function list_themes($refresh = FALSE) {
 459  static $list = array();
 460
 461  if ($refresh) {
 462    $list = array();
 463  }
 464
 465  if (empty($list)) {
 466    $list = array();
 467    $themes = array();
 468    // Extract from the database only when it is available.
 469    // Also check that the site is not in the middle of an install or update.
 470    if (db_is_active() && !defined('MAINTENANCE_MODE')) {
 471      $result = db_query("SELECT * FROM {system} WHERE type = '%s'", 'theme');
 472      while ($theme = db_fetch_object($result)) {
 473        if (file_exists($theme->filename)) {
 474          $theme->info = unserialize($theme->info);
 475          $themes[] = $theme;
 476        }
 477      }
 478    }
 479    else {
 480      // Scan the installation when the database should not be read.
 481      $themes = _system_theme_data();
 482    }
 483
 484    foreach ($themes as $theme) {
 485      foreach ($theme->info['stylesheets'] as $media => $stylesheets) {
 486        foreach ($stylesheets as $stylesheet => $path) {
 487          $theme->stylesheets[$media][$stylesheet] = $path;
 488        }
 489      }
 490      foreach ($theme->info['scripts'] as $script => $path) {
 491        if (file_exists($path)) {
 492          $theme->scripts[$script] = $path;
 493        }
 494      }
 495      if (isset($theme->info['engine'])) {
 496        $theme->engine = $theme->info['engine'];
 497      }
 498      if (isset($theme->info['base theme'])) {
 499        $theme->base_theme = $theme->info['base theme'];
 500      }
 501      // Status is normally retrieved from the database. Add zero values when
 502      // read from the installation directory to prevent notices.
 503      if (!isset($theme->status)) {
 504        $theme->status = 0;
 505      }
 506      $list[$theme->name] = $theme;
 507    }
 508  }
 509
 510  return $list;
 511}
 512
 513/**
 514 * Generate the themed output.
 515 *
 516 * All requests for theme hooks must go through this function. It examines
 517 * the request and routes it to the appropriate theme function. The theme
 518 * registry is checked to determine which implementation to use, which may
 519 * be a function or a template.
 520 *
 521 * If the implementation is a function, it is executed and its return value
 522 * passed along.
 523 *
 524 * If the implementation is a template, the arguments are converted to a
 525 * $variables array. This array is then modified by the module implementing
 526 * the hook, theme engine (if applicable) and the theme. The following
 527 * functions may be used to modify the $variables array. They are processed in
 528 * this order when available:
 529 *
 530 * - template_preprocess(&$variables)
 531 *   This sets a default set of variables for all template implementations.
 532 *
 533 * - template_preprocess_HOOK(&$variables)
 534 *   This is the first preprocessor called specific to the hook; it should be
 535 *   implemented by the module that registers it.
 536 *
 537 * - MODULE_preprocess(&$variables)
 538 *   This will be called for all templates; it should only be used if there
 539 *   is a real need. It's purpose is similar to template_preprocess().
 540 *
 541 * - MODULE_preprocess_HOOK(&$variables)
 542 *   This is for modules that want to alter or provide extra variables for
 543 *   theming hooks not registered to itself. For example, if a module named
 544 *   "foo" wanted to alter the $submitted variable for the hook "node" a
 545 *   preprocess function of foo_preprocess_node() can be created to intercept
 546 *   and alter the variable.
 547 *
 548 * - ENGINE_engine_preprocess(&$variables)
 549 *   This function should only be implemented by theme engines and exists
 550 *   so that it can set necessary variables for all hooks.
 551 *
 552 * - ENGINE_engine_preprocess_HOOK(&$variables)
 553 *   This is the same as the previous function, but it is called for a single
 554 *   theming hook.
 555 *
 556 * - ENGINE_preprocess(&$variables)
 557 *   This is meant to be used by themes that utilize a theme engine. It is
 558 *   provided so that the preprocessor is not locked into a specific theme.
 559 *   This makes it easy to share and transport code but theme authors must be
 560 *   careful to prevent fatal re-declaration errors when using sub-themes that
 561 *   have their own preprocessor named exactly the same as its base theme. In
 562 *   the default theme engine (PHPTemplate), sub-themes will load their own
 563 *   template.php file in addition to the one used for its parent theme. This
 564 *   increases the risk for these errors. A good practice is to use the engine
 565 *   name for the base theme and the theme name for the sub-themes to minimize
 566 *   this possibility.
 567 *
 568 * - ENGINE_preprocess_HOOK(&$variables)
 569 *   The same applies from the previous function, but it is called for a
 570 *   specific hook.
 571 *
 572 * - THEME_preprocess(&$variables)
 573 *   These functions are based upon the raw theme; they should primarily be
 574 *   used by themes that do not use an engine or by sub-themes. It serves the
 575 *   same purpose as ENGINE_preprocess().
 576 *
 577 * - THEME_preprocess_HOOK(&$variables)
 578 *   The same applies from the previous function, but it is called for a
 579 *   specific hook.
 580 *
 581 * There are two special variables that these hooks can set:
 582 *   'template_file' and 'template_files'. These will be merged together
 583 *   to form a list of 'suggested' alternate template files to use, in
 584 *   reverse order of priority. template_file will always be a higher
 585 *   priority than items in template_files. theme() will then look for these
 586 *   files, one at a time, and use the first one
 587 *   that exists.
 588 * @param $hook
 589 *   The name of the theme function to call. May be an array, in which
 590 *   case the first hook that actually has an implementation registered
 591 *   will be used. This can be used to choose 'fallback' theme implementations,
 592 *   so that if the specific theme hook isn't implemented anywhere, a more
 593 *   generic one will be used. This can allow themes to create specific theme
 594 *   implementations for named objects.
 595 * @param ...
 596 *   Additional arguments to pass along to the theme function.
 597 * @return
 598 *   An HTML string that generates the themed output.
 599 */
 600function theme() {
 601  $args = func_get_args();
 602  $hook = array_shift($args);
 603
 604  static $hooks = NULL;
 605  if (!isset($hooks)) {
 606    init_theme();
 607    $hooks = theme_get_registry();
 608  }
 609
 610  if (is_array($hook)) {
 611    foreach ($hook as $candidate) {
 612      if (isset($hooks[$candidate])) {
 613        break;
 614      }
 615    }
 616    $hook = $candidate;
 617  }
 618
 619  if (!isset($hooks[$hook])) {
 620    return;
 621  }
 622
 623  $info = $hooks[$hook];
 624  global $theme_path;
 625  $temp = $theme_path;
 626  // point path_to_theme() to the currently used theme path:
 627  $theme_path = $hooks[$hook]['theme path'];
 628
 629  // Include a file if the theme function or preprocess function is held elsewhere.
 630  if (!empty($info['include files'])) {
 631    foreach ($info['include files'] as $include_file) {
 632      include_once($include_file);
 633    }
 634  }
 635
 636  // Handle compatibility with theme_registry_alters to prevent failures.
 637  if (!empty($info['file'])) {
 638    static $included_files = array();
 639    $include_file = $info['file'];
 640    if (!empty($info['path'])) {
 641      $include_file = $info['path'] .'/'. $include_file;
 642    }
 643
 644    if (empty($included_files[$include_file])) {
 645      // Statically cache files we've already tried to include so we don't
 646      // run unnecessary file_exists calls.
 647      $included_files[$include_file] = TRUE;
 648      if (file_exists('./'. $include_file)) {
 649        include_once('./'. $include_file);
 650      }
 651    }
 652  }
 653
 654  if (isset($info['function'])) {
 655    // The theme call is a function.
 656    $output = call_user_func_array($info['function'], $args);
 657  }
 658  else {
 659    // The theme call is a template.
 660    $variables = array(
 661      'template_files' => array()
 662    );
 663    if (!empty($info['arguments'])) {
 664      $count = 0;
 665      foreach ($info['arguments'] as $name => $default) {
 666        $variables[$name] = isset($args[$count]) ? $args[$count] : $default;
 667        $count++;
 668      }
 669    }
 670
 671    // default render function and extension.
 672    $render_function = 'theme_render_template';
 673    $extension = '.tpl.php';
 674
 675    // Run through the theme engine variables, if necessary
 676    global $theme_engine;
 677    if (isset($theme_engine)) {
 678      // If theme or theme engine is implementing this, it may have
 679      // a different extension and a different renderer.
 680      if ($hooks[$hook]['type'] != 'module') {
 681        if (function_exists($theme_engine .'_render_template')) {
 682          $render_function = $theme_engine .'_render_template';
 683        }
 684        $extension_function = $theme_engine .'_extension';
 685        if (function_exists($extension_function)) {
 686          $extension = $extension_function();
 687        }
 688      }
 689    }
 690
 691    if (isset($info['preprocess functions']) && is_array($info['preprocess functions'])) {
 692      // This construct ensures that we can keep a reference through
 693      // call_user_func_array.
 694      $args = array(&$variables, $hook);
 695      foreach ($info['preprocess functions'] as $preprocess_function) {
 696        if (function_exists($preprocess_function)) {
 697          call_user_func_array($preprocess_function, $args);
 698        }
 699      }
 700    }
 701
 702    // Get suggestions for alternate templates out of the variables
 703    // that were set. This lets us dynamically choose a template
 704    // from a list. The order is FILO, so this array is ordered from
 705    // least appropriate first to most appropriate last.
 706    $suggestions = array();
 707
 708    if (isset($variables['template_files'])) {
 709      $suggestions = $variables['template_files'];
 710    }
 711    if (isset($variables['template_file'])) {
 712      $suggestions[] = $variables['template_file'];
 713    }
 714
 715    if ($suggestions) {
 716      $template_file = drupal_discover_template($info['theme paths'], $suggestions, $extension);
 717    }
 718
 719    if (empty($template_file)) {
 720      $template_file = $hooks[$hook]['template'] . $extension;
 721      if (isset($hooks[$hook]['path'])) {
 722        $template_file = $hooks[$hook]['path'] .'/'. $template_file;
 723      }
 724    }
 725    $output = $render_function($template_file, $variables);
 726  }
 727  // restore path_to_theme()
 728  $theme_path = $temp;
 729  // Add final markup to the full page.
 730  if ($hook == 'page' || $hook == 'book_export_html') {
 731    $output = drupal_final_markup($output);
 732  }
 733  return $output;
 734}
 735
 736/**
 737 * Choose which template file to actually render. These are all suggested
 738 * templates from themes and modules. Theming implementations can occur on
 739 * multiple levels. All paths are checked to account for this.
 740 */
 741function drupal_discover_template($paths, $suggestions, $extension = '.tpl.php') {
 742  global $theme_engine;
 743
 744  // Remove slashes or null to prevent files from being included from
 745  // an unexpected location (especially on Windows servers).
 746  $extension = str_replace(array("/", "\\", "\0"), '', $extension);
 747
 748  // Loop through all paths and suggestions in FIFO order.
 749  $suggestions = array_reverse($suggestions);
 750  $paths = array_reverse($paths);
 751  foreach ($suggestions as $suggestion) {
 752    if (!empty($suggestion)) {
 753      $suggestion = str_replace(array("/", "\\", "\0"), '', $suggestion);
 754      foreach ($paths as $path) {
 755        if (file_exists($file = $path .'/'. $suggestion . $extension)) {
 756          return $file;
 757        }
 758      }
 759    }
 760  }
 761}
 762
 763/**
 764 * Return the path to the current themed element.
 765 *
 766 * It can point to the active theme or the module handling a themed implementation.
 767 * For example, when invoked within the scope of a theming call it will depend
 768 * on where the theming function is handled. If implemented from a module, it
 769 * will point to the module. If implemented from the active theme, it will point
 770 * to the active theme. When called outside the scope of a theming call, it will
 771 * always point to the active theme.
 772 */
 773function path_to_theme() {
 774  global $theme_path;
 775
 776  if (!isset($theme_path)) {
 777    init_theme();
 778  }
 779
 780  return $theme_path;
 781}
 782
 783/**
 784 * Find overridden theme functions. Called by themes and/or theme engines to
 785 * easily discover theme functions.
 786 *
 787 * @param $cache
 788 *   The existing cache of theme hooks to test against.
 789 * @param $prefixes
 790 *   An array of prefixes to test, in reverse order of importance.
 791 *
 792 * @return $templates
 793 *   The functions found, suitable for returning from hook_theme;
 794 */
 795function drupal_find_theme_functions($cache, $prefixes) {
 796  $templates = array();
 797  $functions = get_defined_functions();
 798
 799  foreach ($cache as $hook => $info) {
 800    foreach ($prefixes as $prefix) {
 801      if (!empty($info['pattern'])) {
 802        $matches = preg_grep('/^'. $prefix .'_'. $info['pattern'] .'/', $functions['user']);
 803        if ($matches) {
 804          foreach ($matches as $match) {
 805            $new_hook = str_replace($prefix .'_', '', $match);
 806            $templates[$new_hook] = array(
 807              'function' => $match,
 808              'arguments' => $info['arguments'],
 809              'original hook' => $hook,
 810              'include files' => $info['include files'],
 811            );
 812          }
 813        }
 814      }
 815
 816      if (function_exists($prefix .'_'. $hook)) {
 817        $templates[$hook] = array(
 818          'function' => $prefix .'_'. $hook,
 819          'include files' => $info['include files'],
 820        );
 821        // Ensure that the pattern is maintained from base themes to its sub-themes.
 822        // Each sub-theme will have their functions scanned so the pattern must be
 823        // held for subsequent runs.
 824        if (isset($info['pattern'])) {
 825          $templates[$hook]['pattern'] = $info['pattern'];
 826        }
 827        // Also ensure that the 'file' property is maintained, because it probably
 828        // contains the preprocess.
 829      }
 830    }
 831  }
 832
 833  return $templates;
 834}
 835
 836/**
 837 * Find overridden theme templates. Called by themes and/or theme engines to
 838 * easily discover templates.
 839 *
 840 * @param $cache
 841 *   The existing cache of theme hooks to test against.
 842 * @param $extension
 843 *   The extension that these templates will have.
 844 * @param $path
 845 *   The path to search.
 846 */
 847function drupal_find_theme_templates($cache, $extension, $path) {
 848  $templates = array();
 849
 850  // Collect paths to all sub-themes grouped by base themes. These will be
 851  // used for filtering. This allows base themes to have sub-themes in its
 852  // folder hierarchy without affecting the base themes template discovery.
 853  $theme_paths = array();
 854  foreach (list_themes() as $theme_info) {
 855    if (!empty($theme_info->base_theme)) {
 856      $theme_paths[$theme_info->base_theme][$theme_info->name] = dirname($theme_info->filename);
 857    }
 858  }
 859  foreach ($theme_paths as $basetheme => $subthemes) {
 860    foreach ($subthemes as $subtheme => $subtheme_path) {
 861      if (isset($theme_paths[$subtheme])) {
 862        $theme_paths[$basetheme] = array_merge($theme_paths[$basetheme], $theme_paths[$subtheme]);
 863      }
 864    }
 865  }
 866  global $theme;
 867  $subtheme_paths = isset($theme_paths[$theme]) ? $theme_paths[$theme] : array();
 868
 869  // Escape the periods in the extension.
 870  $regex = str_replace('.', '\.', $extension) .'$';
 871  // Because drupal_system_listing works the way it does, we check for real
 872  // templates separately from checking for patterns.
 873  $files = drupal_system_listing($regex, $path, 'name', 0);
 874  foreach ($files as $template => $file) {
 875    // Ignore sub-theme templates for the current theme.
 876    if (strpos($file->filename, str_replace($subtheme_paths, '', $file->filename)) !== 0) {
 877      continue;
 878    }
 879    // Chop off the remaining extensions if there are any. $template already
 880    // has the rightmost extension removed, but there might still be more,
 881    // such as with .tpl.php, which still has .tpl in $template at this point.
 882    if (($pos = strpos($template, '.')) !== FALSE) {
 883      $template = substr($template, 0, $pos);
 884    }
 885    // Transform - in filenames to _ to match function naming scheme
 886    // for the purposes of searching.
 887    $hook = strtr($template, '-', '_');
 888    if (isset($cache[$hook])) {
 889      $templates[$hook] = array(
 890        'template' => $template,
 891        'path' => dirname($file->filename),
 892        'include files' => $cache[$hook]['include files'],
 893      );
 894    }
 895    // Ensure that the pattern is maintained from base themes to its sub-themes.
 896    // Each sub-theme will have their templates scanned so the pattern must be
 897    // held for subsequent runs.
 898    if (isset($cache[$hook]['pattern'])) {
 899      $templates[$hook]['pattern'] = $cache[$hook]['pattern'];
 900    }
 901  }
 902
 903  $patterns = array_keys($files);
 904
 905  foreach ($cache as $hook => $info) {
 906    if (!empty($info['pattern'])) {
 907      // Transform _ in pattern to - to match file naming scheme
 908      // for the purposes of searching.
 909      $pattern = strtr($info['pattern'], '_', '-');
 910
 911      $matches = preg_grep('/^'. $pattern .'/', $patterns);
 912      if ($matches) {
 913        foreach ($matches as $match) {
 914          $file = substr($match, 0, strpos($match, '.'));
 915          // Put the underscores back in for the hook name and register this pattern.
 916          $templates[strtr($file, '-', '_')] = array(
 917            'template' => $file,
 918            'path' => dirname($files[$match]->filename),
 919            'arguments' => $info['arguments'],
 920            'original hook' => $hook,
 921            'include files' => $info['include files'],
 922          );
 923        }
 924      }
 925    }
 926  }
 927  return $templates;
 928}
 929
 930/**
 931 * Retrieve an associative array containing the settings for a theme.
 932 *
 933 * The final settings are arrived at by merging the default settings,
 934 * the site-wide settings, and the settings defined for the specific theme.
 935 * If no $key was specified, only the site-wide theme defaults are retrieved.
 936 *
 937 * The default values for each of settings are also defined in this function.
 938 * To add new settings, add their default values here, and then add form elements
 939 * to system_theme_settings() in system.module.
 940 *
 941 * @param $key
 942 *  The template/style value for a given theme.
 943 *
 944 * @return
 945 *   An associative array containing theme settings.
 946 */
 947function theme_get_settings($key = NULL) {
 948  $defaults = array(
 949    'mission'                       =>  '',
 950    'default_logo'                  =>  1,
 951    'logo_path'                     =>  '',
 952    'default_favicon'               =>  1,
 953    'favicon_path'                  =>  '',
 954    'primary_links'                 =>  1,
 955    'secondary_links'               =>  1,
 956    'toggle_logo'                   =>  1,
 957    'toggle_favicon'                =>  1,
 958    'toggle_name'                   =>  1,
 959    'toggle_search'                 =>  1,
 960    'toggle_slogan'                 =>  0,
 961    'toggle_mission'                =>  1,
 962    'toggle_node_user_picture'      =>  0,
 963    'toggle_comment_user_picture'   =>  0,
 964    'toggle_primary_links'          =>  1,
 965    'toggle_secondary_links'        =>  1,
 966  );
 967
 968  if (module_exists('node')) {
 969    foreach (node_get_types() as $type => $name) {
 970      $defaults['toggle_node_info_'. $type] = 1;
 971    }
 972  }
 973  $settings = array_merge($defaults, variable_get('theme_settings', array()));
 974
 975  if ($key) {
 976    $settings = array_merge($settings, variable_get(str_replace('/', '_', 'theme_'. $key .'_settings'), array()));
 977  }
 978
 979  // Only offer search box if search.module is enabled.
 980  if (!module_exists('search') || !user_access('search content')) {
 981    $settings['toggle_search'] = 0;
 982  }
 983
 984  return $settings;
 985}
 986
 987/**
 988 * Retrieve a setting for the current theme.
 989 * This function is designed for use from within themes & engines
 990 * to determine theme settings made in the admin interface.
 991 *
 992 * Caches values for speed (use $refresh = TRUE to refresh cache)
 993 *
 994 * @param $setting_name
 995 *  The name of the setting to be retrieved.
 996 *
 997 * @param $refresh
 998 *  Whether to reload the cache of settings.
 999 *
1000 * @return
1001 *   The value of the requested setting, NULL if the setting does not exist.
1002 */
1003function theme_get_setting($setting_name, $refresh = FALSE) {
1004  global $theme_key;
1005  static $settings;
1006
1007  if (empty($settings) || $refresh) {
1008    $settings = theme_get_settings($theme_key);
1009
1010    $themes = list_themes();
1011    $theme_object = $themes[$theme_key];
1012
1013    if ($settings['mission'] == '') {
1014      $settings['mission'] = variable_get('site_mission', '');
1015    }
1016
1017    if (!$settings['toggle_mission']) {
1018      $settings['mission'] = '';
1019    }
1020
1021    if ($settings['toggle_logo']) {
1022      if ($settings['default_logo']) {
1023        $settings['logo'] = file_create_url(dirname($theme_object->filename) .'/logo.png');
1024      }
1025      elseif ($settings['logo_path']) {
1026        $settings['logo'] = file_create_url($settings['logo_path']);
1027      }
1028    }
1029
1030    if ($settings['toggle_favicon']) {
1031      if ($settings['default_favicon']) {
1032        if (file_exists($favicon = dirname($theme_object->filename) .'/favicon.ico')) {
1033          $settings['favicon'] = file_create_url($favicon);
1034        }
1035        else {
1036          $settings['favicon'] = file_create_url('misc/favicon.ico');
1037        }
1038      }
1039      elseif ($settings['favicon_path']) {
1040        $settings['favicon'] = file_create_url($settings['favicon_path']);
1041      }
1042      else {
1043        $settings['toggle_favicon'] = FALSE;
1044      }
1045    }
1046  }
1047
1048  return isset($settings[$setting_name]) ? $settings[$setting_name] : NULL;
1049}
1050
1051/**
1052 * Render a system default template, which is essentially a PHP template.
1053 *
1054 * @param $template_file
1055 *   The filename of the template to render. Note that this will overwrite
1056 *   anything stored in $variables['template_file'] if using a preprocess hook.
1057 * @param $variables
1058 *   A keyed array of variables that will appear in the output.
1059 *
1060 * @return
1061 *   The output generated by the template.
1062 */
1063function theme_render_template($template_file, $variables) {
1064  extract($variables, EXTR_SKIP);  // Extract the variables to a local namespace
1065  ob_start();                      // Start output buffering
1066  include "./$template_file";      // Include the template file
1067  $contents = ob_get_contents();   // Get the contents of the buffer
1068  ob_end_clean();                  // End buffering and discard
1069  return $contents;                // Return the contents
1070}
1071
1072/**
1073 * @defgroup themeable Default theme implementations
1074 * @{
1075 * Functions and templates that present output to the user, and can be
1076 * implemented by themes.
1077 *
1078 * Drupal's presentation layer is a pluggable system known as the theme
1079 * layer. Each theme can take control over most of Drupal's output, and
1080 * has complete control over the CSS.
1081 *
1082 * Inside Drupal, the theme layer is utilized by the use of the theme()
1083 * function, which is passed the name of a component (the theme hook)
1084 * and several arguments. For example, theme('table', $header, $rows);
1085 * Additionally, the theme() function can take an array of theme
1086 * hooks, which can be used to provide 'fallback' implementations to
1087 * allow for more specific control of output. For example, the function:
1088 * theme(array('table__foo', 'table'), $header, $rows) would look to see if
1089 * 'table__foo' is registered anywhere; if it is not, it would 'fall back'
1090 * to the generic 'table' implementation. This can be used to attach specific
1091 * theme functions to named objects, allowing the themer more control over
1092 * specific types of output.
1093 *
1094 * As of Drupal 6, every theme hook is required to be registered by the
1095 * module that owns it, so that Drupal can tell what to do with it and
1096 * to make it simple for themes to identify and override the behavior
1097 * for these calls.
1098 *
1099 * The theme hooks are registered via hook_theme(), which returns an
1100 * array of arrays with information about the hook. It describes the
1101 * arguments the function or template will need, and provides
1102 * defaults for the template in case they are not filled in. If the default
1103 * implementation is a function, by convention it is named theme_HOOK().
1104 *
1105 * Each module should provide a default implementation for theme_hooks that
1106 * it registers. This implementation may be either a function or a template;
1107 * if it is a function it must be specified via hook_theme(). By convention,
1108 * default implementations of theme hooks are named theme_HOOK. Default
1109 * template implementations are stored in the module directory.
1110 *
1111 * Drupal's default template renderer is a simple PHP parsing engine that
1112 * includes the template and stores the output. Drupal's theme engines
1113 * can provide alternate template engines, such as XTemplate, Smarty and
1114 * PHPTal. The most common template engine is PHPTemplate (included with
1115 * Drupal and implemented in phptemplate.engine, which uses Drupal's default
1116 * template renderer.
1117 *
1118 * In order to create theme-specific implementations of these hooks,
1119 * themes can implement their own version of theme hooks, either as functions
1120 * or templates. These implementations will be used instead of the default
1121 * implementation. If using a pure .theme without an engine, the .theme is
1122 * required to implement its own version of hook_theme() to tell Drupal what
1123 * it is implementing; themes utilizing an engine will have their well-named
1124 * theming functions automatically registered for them. While this can vary
1125 * based upon the theme engine, the standard set by phptemplate is that theme
1126 * functions should be named either phptemplate_HOOK or THEMENAME_HOOK. For
1127 * example, for Drupal's default theme (Garland) to implement the 'table' hook,
1128 * the phptemplate.engine would find phptemplate_table() or garland_table().
1129 * The ENGINE_HOOK() syntax is preferred, as this can be used by sub-themes
1130 * (which are themes that share code but use different stylesheets).
1131 *
1132 * The theme system is described and defined in theme.inc.
1133 *
1134 * @see theme()
1135 * @see hook_theme()
1136 */
1137
1138/**
1139 * Formats text for emphasized display in a placeholder inside a sentence.
1140 * Used automatically by t().
1141 *
1142 * @param $text
1143 *   The text to format (plain-text).
1144 * @return
1145 *   The formatted text (html).
1146 */
1147function theme_placeholder($text) {
1148  return '<em>'. check_plain($text) .'</em>';
1149}
1150
1151/**
1152 * Return a themed set of status and/or error messages. The messages are grouped
1153 * by type.
1154 *
1155 * @param $display
1156 *   (optional) Set to 'status' or 'error' to display only messages of that type.
1157 *
1158 * @return
1159 *   A string containing the messages.
1160 */
1161function theme_status_messages($display = NULL) {
1162  $output = '';
1163  foreach (drupal_get_messages($display) as $type => $messages) {
1164    $output .= "<div class=\"messages $type\">\n";
1165    if (count($messages) > 1) {
1166      $output .= " <ul>\n";
1167      foreach ($messages as $message) {
1168        $output .= '  <li>'. $message ."</li>\n";
1169      }
1170      $output .= " </ul>\n";
1171    }
1172    else {
1173      $output .= $messages[0];
1174    }
1175    $output .= "</div>\n";
1176  }
1177  return $output;
1178}
1179
1180/**
1181 * Return a themed set of links.
1182 *
1183 * @param $links
1184 *   A keyed array of links to be themed.
1185 * @param $attributes
1186 *   A keyed array of attributes
1187 * @return
1188 *   A string containing an unordered list of links.
1189 */
1190function theme_links($links, $attributes = array('class' => 'links')) {
1191  global $language;
1192  $output = '';
1193
1194  if (count($links) > 0) {
1195    $output = '<ul'. drupal_attributes($attributes) .'>';
1196
1197    $num_links = count($links);
1198    $i = 1;
1199
1200    foreach ($links as $key => $link) {
1201      $class = $key;
1202
1203      // Add first, last and active classes to the list of links to help out themers.
1204      if ($i == 1) {
1205        $class .= ' first';
1206      }
1207      if ($i == $num_links) {
1208        $class .= ' last';
1209      }
1210      if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))
1211          && (empty($link['language']) || $link['language']->language == $language->language)) {
1212        $class .= ' active';
1213      }
1214      $output .= '<li'. drupal_attributes(array('class' => $class)) .'>';
1215
1216      if (isset($link['href'])) {
1217        // Pass in $link as $options, they share the same keys.
1218        $output .= l($link['title'], $link['href'], $link);
1219      }
1220      else if (!empty($link['title'])) {
1221        // Some links are actually not links, but we wrap these in <span> for adding title and class attributes
1222        if (empty($link['html'])) {
1223          $link['title'] = check_plain($link['title']);
1224        }
1225        $span_attributes = '';
1226        if (isset($link['attributes'])) {
1227          $span_attributes = drupal_attributes($link['attributes']);
1228        }
1229        $output .= '<span'. $span_attributes .'>'. $link['title'] .'</span>';
1230      }
1231
1232      $i++;
1233      $output .= "</li>\n";
1234    }
1235
1236    $output .= '</ul>';
1237  }
1238
1239  return $output;
1240}
1241
1242/**
1243 * Return a themed image.
1244 *
1245 * @param $path
1246 *   Either the path of the image file (relative to base_path()) or a full URL.
1247 * @param $alt
1248 *   The alternative text for text-based browsers.
1249 * @param $title
1250 *   The title text is displayed when the image is hovered in some popular browsers.
1251 * @param $attributes
1252 *   Associative array of attributes to be placed in the img tag.
1253 * @param $getsize
1254 *   If set to TRUE, the image's dimension are fetched and added as width/height attributes.
1255 * @return
1256 *   A string containing the image tag.
1257 */
1258function theme_image($path, $alt = '', $title = '', $attributes = NULL, $getsize = TRUE) {
1259  if (!$getsize || (is_file($path) && (list($width, $height, $type, $image_attributes) = @getimagesize($path)))) {
1260    $attributes = drupal_attributes($attributes);
1261    $url = (url($path) == $path) ? $path : file_create_url($path);
1262    return '<img src="'. check_url($url) .'" alt="'. check_plain($alt) .'" title="'. check_plain($title) .'" '. (isset($image_attributes) ? $image_attributes : '') . $attributes .' />';
1263  }
1264}
1265
1266/**
1267 * Return a themed breadcrumb trail.
1268 *
1269 * @param $breadcrumb
1270 *   An array containing the breadcrumb links.
1271 * @return a string containing the breadcrumb output.
1272 */
1273function theme_breadcrumb($breadcrumb) {
1274  if (!empty($breadcrumb)) {
1275    return '<div class="breadcrumb">'. implode(' ? ', $breadcrumb) .'</div>';
1276  }
1277}
1278
1279/**
1280 * Return a themed help message.
1281 *
1282 * @return a string containing the helptext for the current page.
1283 */
1284function theme_help() {
1285  if ($help = menu_get_active_help()) {
1286    return '<div class="help">'. $help .'</div>';
1287  }
1288}
1289
1290/**
1291 * Return a themed submenu, typically displayed under the tabs.
1292 *
1293 * @param $links
1294 *   An array of links.
1295 */
1296function theme_submenu($links) {
1297  return '<div class="submenu">'. implode(' | ', $links) .'</div>';
1298}
1299
1300/**
1301 * Return a themed table.
1302 *
1303 * @param $header
1304 *   An array containing the table headers. Each element of the array can be
1305 *   either a localized string or an associative array with the following keys:
1306 *   - "data": The localized title of the table column.
1307 *   - "field": The database field represented in the table column (required if
1308 *     user is to be able to sort on this column).
1309 *   - "sort": A default sort order for this column ("asc" or "desc").
1310 *   - Any HTML attributes, such as "colspan", to apply to the column header cell.
1311 * @param $rows
1312 *   An array of table rows. Every row is an array of cells, or an associative
1313 *   array with the following keys:
1314 *   - "data": an array of cells
1315 *   - Any HTML attributes, such as "class", to apply to the table row.
1316 *
1317 *   Each cell can be either a string or an associative array with the following keys:
1318 *   - "data": The string to display in the table cell.
1319 *   - "header": Indicates this cell is a header.
1320 *   - Any HTML attributes, such as "colspan", to apply to the table cell.
1321 *
1322 *   Here's an example for $rows:
1323 *   @code
1324 *   $rows = array(
1325 *     // Simple row
1326 *     array(
1327 *       'Cell 1', 'Cell 2', 'Cell 3'
1328 *     ),
1329 *     // Row with attributes on the row and some of its cells.
1330 *     array(
1331 *       'data' => array('Cell 1', array('data' => 'Cell 2', 'colspan' => 2)), 'class' => 'funky'
1332 *     )
1333 *   );
1334 *   @endcode
1335 *
1336 * @param $attributes
1337 *   An array of HTML attributes to apply to the table tag.
1338 * @param $caption
1339 *   A localized string to use for the <caption> tag.
1340 * @return
1341 *   An HTML string representing the table.
1342 */
1343function theme_table($header, $rows, $attributes = array(), $caption = NULL) {
1344
1345  // Add sticky headers, if applicable.
1346  if (count($header)) {
1347    drupal_add_js('misc/tableheader.js');
1348    // Add 'sticky-enabled' class to the table to identify it for JS.
1349    // This is needed to target tables constructed by this function.
1350    $attributes['class'] = empty($attributes['class']) ? 'sticky-enabled' : ($attributes['class'] .' sticky-enabled');
1351  }
1352
1353  $output = '<table'. drupal_attributes($attributes) .">\n";
1354
1355  if (isset($caption)) {
1356    $output .= '<caption>'. $caption ."</caption>\n";
1357  }
1358
1359  // Format the table header:
1360  if (count($header)) {
1361    $ts = tablesort_init($header);
1362    // HTML requires that the thead tag has tr tags in it followed by tbody
1363    // tags. Using ternary operator to check and see if we have any rows.
1364    $output .= (count($rows) ? ' <thead><tr>' : ' <tr>');
1365    foreach ($header as $cell) {
1366      $cell = tablesort_header($cell, $header, $ts);
1367      $output .= _theme_table_cell($cell, TRUE);
1368    }
1369    // Using ternary operator to close the tags based on whether or not there are rows
1370    $output .= (count($rows) ? " </tr></thead>\n" : "</tr>\n");
1371  }
1372  else {
1373    $ts = array();
1374  }
1375
1376  // Format the table rows:
1377  if (count($rows)) {
1378    $output .= "<tbody>\n";
1379    $flip = array('even' => 'odd', 'odd' => 'even');
1380    $class = 'even';
1381    foreach ($rows as $number => $row) {
1382      $attributes = array();
1383
1384      // Check if we're dealing with a simple or complex row
1385      if (isset($row['data'])) {
1386        foreach ($row as $key => $value) {
1387          if ($key == 'data') {
1388            $cells = $value;
1389          }
1390          else {
1391            $attributes[$key] = $value;
1392          }
1393        }
1394      }
1395      else {
1396        $cells = $row;
1397      }
1398      if (count($cells)) {
1399        // Add odd/even class
1400        $class = $flip[$class];
1401        if (isset($attributes['class'])) {
1402          $attributes['class'] .= ' '. $class;
1403        }
1404        else {
1405          $attributes['class'] = $class;
1406        }
1407
1408        // Build row
1409  

Large files files are truncated, but you can click here to view the full file