summaryrefslogtreecommitdiffstats
path: root/includes/omega.inc
blob: 5d944260c47b37996b98932c461f038b7dc77317 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
<?php

/**
 * @file
 * Helper functions for the Omega base theme.
 */

/**
 * Retrieve a setting for the current theme or for a given theme.
 *
 * The final setting is obtained from the last value found in the following
 * sources:
 * - the default global settings specified in this function
 * - the default theme-specific settings defined in any base theme's .info file
 * - the default theme-specific settings defined in the theme's .info file
 * - the saved values from the global theme settings form
 * - the saved values from the theme's settings form
 * To only retrieve the default global theme setting, an empty string should be
 * given for $theme.
 *
 * @param $setting_name
 *   The name of the setting to be retrieved.
 * @param $default
 *   (optional) A default value. Defaults to NULL.
 * @param $theme
 *   (optional) The name of a given theme. Defaults to the NULL which
 *   evaluates to the current theme.
 *
 * @return
 *   The value of the requested setting, or the $default value if the setting
 *   does not exist.
 *
 * @see theme_get_setting().
 */
function omega_theme_get_setting($setting_name, $default = NULL, $theme = NULL) {
  $cache = &drupal_static('theme_get_setting', array());

  // If no key is given, use the current theme if we can determine it.
  if (!isset($theme)) {
    $theme = !empty($GLOBALS['theme_key']) ? $GLOBALS['theme_key'] : '';
  }

  if (empty($cache[$theme])) {
    // If the cache has not been filled yet, invoke theme_get_setting to
    // retrieve the value. This will populate the cache and make it available
    // for subsequent requests.
    if (($setting = theme_get_setting($setting_name, $theme)) !== NULL) {
      // Use the default value if the setting does not exist.
      return $setting;
    }
  }
  else {
    // Retrieve the value from the cache.
    if (isset($cache[$theme][$setting_name])) {
      return $cache[$theme][$setting_name];
    }
  }

  // Use the default value if the settingdoes not exist.
  return $default;
}

/**
 * Builds the full theme trail (deepest base theme first, subtheme last) for a
 * theme.
 *
 * @param $theme
 *   (Optional) The key (machine-readable name) of a theme. Defaults to the key
 *   of the current theme.
 *
 * @return array
 *   An array of all themes in the trail, keyed by theme key.
 */
function omega_theme_trail($theme = NULL) {
  $theme = isset($theme) ? $theme : $GLOBALS['theme_key'];
  $cache = &drupal_static(__FUNCTION__);

  if (!isset($cache[$theme])) {
    $cache[$theme] = array();

    if ($theme == $GLOBALS['theme'] && isset($GLOBALS['theme_info']->base_themes)) {
      $cache[$theme] = $GLOBALS['theme_info']->base_themes;
    }

    $themes = list_themes();
    if (empty($cache[$theme]) && isset($themes[$theme]->info['base theme'])) {
      $cache[$theme] = system_find_base_themes($themes, $theme);
    }

    // Add our current subtheme ($key) to that array.
    $cache[$theme][$theme] = $themes[$theme]->info['name'];
  }

  return $cache[$theme];
}

/**
 * Pre-processes CSS files so that CSS files that have 'preprocess_media' set to
 * TRUE are set to media="all" while having their former media query added to
 * the file content.
 *
 * @param $elements
 *   An array of CSS files as in drupal_pre_render_styles().
 *
 * @return array
 *   An array of preprocessed CSS files.
 *
 * @see drupal_pre_render_styles()
 */
function omega_css_preprocessor($elements) {
  foreach ($elements['#items'] as &$item) {
    if ($item['type'] == 'file' && $item['preprocess'] && $item['media'] != 'all') {
      $item['data'] = omega_css_cache_media_queries($item);
      $item['media'] = 'all';
    }
  }

  return $elements;
}

/**
 * Optimizes CSS aggregation by creating a cached version of each CSS file that,
 * instead of using the 'media' attribute on the styles tag, writes the media
 * query into the file itself using the '@media { ... }' syntax.
 *
 * This prevents unnecessary sprouting of new CSS aggregation.
 *
 * @see drupal_build_css_cache().
 */
function omega_css_cache_media_queries($item) {
  $map = variable_get('drupal_css_cache_files', array());
  $key = hash('sha256', serialize($item));
  $uri = isset($map[$key]) ? $map[$key] : NULL;

  if (empty($uri) || !file_exists($uri)) {
    // Build the base URL of this CSS file: start with the full URL.
    $base = file_create_url($item['data']);
    $base = substr($base, 0, strrpos($base, '/'));

    if (substr($base, 0, strlen($GLOBALS['base_theme'])) == $GLOBALS['base_theme']) {
      $base = substr($base, strlen($GLOBALS['base_theme']));
    }

    _drupal_build_css_path(NULL, $base . '/');

    $data = drupal_load_stylesheet($item['data'], TRUE);

    // Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
    $data = preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', '_drupal_build_css_path', $data);
    $data = '@media ' . $item['media'] . '{' . $data . '}';

    // Create the css/ within the files folder.
    $directory = 'public://css';
    $uri = $directory . '/css_' . drupal_hash_base64($data) . '.css';

    // Create the CSS file.
    file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
    if (!file_exists($uri) && !file_unmanaged_save_data($data, $uri, FILE_EXISTS_REPLACE)) {
      return FALSE;
    }

    // If CSS gzip compression is enabled, clean URLs are enabled (which means
    // that rewrite rules are working) and the zlib extension is available then
    // create a gzipped version of this file. This file is served conditionally
    // to browsers that accept gzip using .htaccess rules.
    if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
      if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
        return FALSE;
      }
    }

    // Save the updated map.
    $map[$key] = $uri;

    // Write the updated map into the variable.
    variable_set('drupal_css_cache_files', $map);
  }

  return $uri;
}

/**
 * Helper function for eliminating elements from an array using a simplified
 * regex pattern.
 *
 * @param $elements
 *   The array of elements that should have some elements nuked.
 * @param $exclude
 *   An array of strings that should be matched against the keys of the array
 *   of elements.
 *
 * @return array
 *   The purged array.
 */
function omega_exclude_assets(&$elements, $exclude) {
  // For optimization reasons we load the theme trail to check whether a
  // namespace matches the machine-readable name of one of the themes in the
  // trail.
  $trail = omega_theme_trail();

  foreach ($exclude as $item) {
    $path = '';
    // The first segment (everything before the first slash) is the namespace.
    list($namespace) = explode('/', $item);

    // Check if the namespace refers to a file residing in the 'misc' folder.
    if ($namespace == 'misc') {
      $path = DRUPAL_ROOT . '/misc';
    }
    // Check if the namespace refers to a theme.
    elseif (array_key_exists($namespace, $trail)) {
      $path = drupal_get_path('theme', $namespace);
    }
    else {
      // Otherwise, check if it refers to a module, profile or theme engine.
      foreach (array('module', 'profile', 'theme_engine') as $type) {
        if ($path = drupal_get_path($type, $namespace)) {
          break;
        }
      }
    }

    // If a namespace could be identified, use its path as a prefix, otherwise
    // use the plain file path as provided.
    $item = $path ? $path . '/' . substr($item, strlen($namespace) + 1) : $item;
    $item = preg_quote($item, '/');
    // Turn the * wildcards into actual regex wildcards and make sure that, if
    // a .css file is targeted directly we are also removing the RTL version of
    // that file.
    $item = str_replace(array('\*', '\.css'), array('(.*)', '(\.css|-rtl\.css)'), $item);

    // Look up all elements that match this exclusion pattern.
    $filtered = preg_grep("/^$item$/", array_keys($elements));
    $elements = array_diff_key($elements, array_flip($filtered));
  }
}

/**
 * Retrieves the array of enabled extensions for a theme. Extensions can be
 * registered through the .info file. Each extension can define a theme settings
 * form altering function named
 * 'THEMENAME_extension_EXTENSION_theme_settings_form_alter()' through a file
 * named 'THEME_ROOT/includes/EXTENSION/EXTENSION.settings.inc' to have it
 * automatically included whenever the theme settings form is displayed. Each
 * extension can also define a
 * 'THEMENAME_extension_EXTENSION_theme_registry_alter()' function through a
 * file named 'THEME_ROOT/includes/EXTENSION/EXTENSION.inc' to register custom
 * hooks with the theme registry.
 *
 * @param $theme
 *   (Optional) The key (machine-readable name) of a theme. Defaults to the key
 *   of the current theme.
 *
 * @return array
 *   The theme info array of the passed or current theme.
 *
 * @see _system_default_theme_features()
 * @see omega_extension_development_theme_settings_form_alter()
 * @see omega_extension_development_theme_registry_alter()
 */
function omega_extensions($theme = NULL) {
  $theme = isset($theme) ? $theme : $GLOBALS['theme_key'];
  $extensions = drupal_static(__FUNCTION__);

  if (!isset($extensions[$theme])) {
    if (($cache = cache_get('omega_extensions:' . $theme)) !== FALSE) {
      $extensions[$theme] = $cache->data;
    }
    else {
      // Extensions can't be hidden.
      $extensions[$theme] = omega_discovery('extension', $theme, TRUE);

      foreach ($extensions[$theme] as $extension => &$info) {
        // Make sure that the theme variable is never altered.
        $context = $theme;
        drupal_alter('omega_extension_info', $info, $context);

        // Determine if the extension is enabled.
        $info['enabled'] = omega_theme_get_setting('omega_toggle_extension_' . $extension, !empty($info['info']['enabled']));

        // Check if all dependencies are met.
        if ($info['enabled'] && !empty($info['dependencies'])) {
          foreach ($info['dependencies'] as $dependency) {
            $dependency = drupal_parse_dependency($dependency);

            if ((!$module = system_get_info('module', $dependency['name'])) || drupal_check_incompatibility($dependency, str_replace(DRUPAL_CORE_COMPATIBILITY . '-', '', $module['version']))) {
              $info['enabled'] = FALSE;
            }
          }
        }
      }

      // Write to the cache.
      cache_set('omega_extensions:' . $theme, $extensions[$theme]);
    }
  }

  return $extensions[$theme];
}

/**
 * Determines if an extension is enabled.
 *
 * @param $extension
 *   The machine-readable name of an extension.
 * @param $theme
 *   (Optional) The key (machine-readable name) of a theme. Defaults to the key
 *   of the current theme.
 *
 * @return bool
 *   TRUE if the extension is enabled, FALSE otherwise.
 */
function omega_extension_enabled($extension, $theme = NULL) {
  $theme = isset($theme) ? $theme : $GLOBALS['theme_key'];
  if (($extensions = omega_extensions($theme)) && isset($extensions[$extension])) {
    return $extensions[$extension]['enabled'];
  }
}

/**
 * Looks up the info array of all themes in the theme trail and retrieves a
 * particular info array element.
 */
function omega_theme_trail_info($element, $merge = TRUE, $theme = NULL) {
  $output = array();

  // Loop over all themes in the theme trail and look up $element in the .info
  // array.
  foreach (array_reverse(omega_theme_trail($theme)) as $key => $name) {
    $info = omega_theme_info($key);

    // If $merge is TRUE we combine all the results of all themes in the theme
    // trail. Otherwise we just return the first occurrence.
    if (isset($info[$element]) && is_array($info[$element])) {
      $output = array_merge($info[$element], $output);

      if (!$merge) {
        return array('theme' => $key, 'info' => $output);
      }
    }
  }

  return $output;
}

/**
 * Retrieves the full info array of a theme.
 *
 * @param $theme
 *   (Optional) The key (machine-readable name) of a theme. Defaults to the key
 *   of the current theme.
 *
 * @return array
 *   The theme info array of the passed or current theme.
 */
function omega_theme_info($theme = NULL) {
  $theme = isset($theme) ? $theme : $GLOBALS['theme_key'];

  // If this is the current theme, just load the theme info from the globals.
  // Note: The global 'theme_key' property is not reliable in this case because
  // it gets overridden on theme settings pages.
  if ($theme == $GLOBALS['theme']) {
    return $GLOBALS['theme_info']->info;
  }

  $themes = list_themes();
  return $themes[$theme]->info;
}

/**
 * Invoke a hook in all themes in the theme trail that implement it.
 *
 * @param $hook
 *   The name of the hook to invoke.
 * @param $theme
 *   (Optional) The key (machine-readable name) of a theme. Defaults to the key
 *   of the current theme.
 * @param ...
 *   Arguments to pass to the hook.
 *
 * @return array
 *   An array of return values of the hook implementations. If themes return
 *   arrays from their implementations, those are merged into one array.
 *
 * @see module_invoke_all()
 */
function omega_invoke_all($hook, $theme = NULL) {
  $theme = isset($theme) ? $theme : $GLOBALS['theme_key'];

  $args = func_get_args();
  // Remove $hook from the arguments.
  unset($args[0], $args[1]);

  $return = array();
  foreach (omega_theme_trail($theme) as $key => $name) {
    $function = $key . '_' . $hook;

    if (function_exists($function)) {
      $result = call_user_func_array($function, array_merge(array($theme), array_values($args)));
      if (isset($result) && is_array($result)) {
        // Append the 'theme' property to each array element.
        foreach ($result as &$item) {
          $item['theme'] = $key;
        }
        $return = array_merge_recursive($return, $result);
      }
      elseif (isset($result)) {
        $return[] = $result;
      }
    }
  }
  return $return;
}

/**
 * Custom implementation of drupal_array_get_nested_value() that also supports
 * objects instead of just arrays.
 *
 * @param $object
 *   The array or object from which to get the value.
 * @param $parents
 *   An array of parent keys of the value, starting with the outermost key.
 * @param $key_exists
 *   (optional) If given, an already defined variable that is altered by
 *   reference.
 *
 * @return mixed
 *   The requested nested value. Possibly NULL if the value is NULL or not all
 *   nested parent keys exist. $key_exists is altered by reference and is a
 *   Boolean that indicates whether all nested parent keys exist (TRUE) or not
 *   (FALSE). This allows to distinguish between the two possibilities when NULL
 *   is returned.
 *
 * @see drupal_array_get_nested_value()
 */
function omega_get_nested_value(&$object, array $parents, &$key_exists = NULL) {
  $ref = &$object;
  foreach ($parents as $parent) {
    if (is_array($ref) && array_key_exists($parent, $ref)) {
      $ref = &$ref[$parent];
    }
    elseif (is_object($ref) && property_exists($ref, $parent)) {
      $ref = &$ref->$parent;
    }
    else {
      $key_exists = FALSE;
      return NULL;
    }
  }
  $key_exists = TRUE;
  return $ref;
}

/**
 * Retrieves the info array for all available layouts.
 *
 * @param $theme
 *   (Optional) The key (machine-readable name) of a theme. Defaults to the key
 *   of the current theme.
 *
 * @return array
 *   An array of available layouts for the given theme.
 */
function omega_layouts_info($theme = NULL) {
  $theme = isset($theme) ? $theme : $GLOBALS['theme_key'];
  $layouts = drupal_static(__FUNCTION__);

  if (!isset($layouts[$theme])) {
    $layouts[$theme] = omega_discovery('layout', $theme);

    // A theme or base theme can explicitly restrict the available layouts to
    // a subset defined through the .info file.
    if ($filter = omega_theme_trail_info('layouts', TRUE, $theme)) {
      $layouts[$theme] = array_intersect_key($layouts[$theme], array_flip($filter));
    }

    foreach ($layouts[$theme] as $layout => &$info) {
      $info['attached'] = array();

      // Look up possible CSS and JS file overrides.
      if (isset($info['info']['stylesheets'])) {
        foreach ($info['info']['stylesheets'] as $media => $files) {
          foreach ($files as $key => $file) {
            $info['attached']['css'][$key] = array(
              'media' => $media,
              'data' => $info['path'] . '/' . $file,
              'group' => CSS_THEME,
              'every_page' => TRUE,
              'weight' => -10,
            );
          }
        }
      }

      // Look up possible CSS and JS file overrides.
      if (isset($info['info']['scripts'])) {
        foreach ($info['info']['scripts'] as $key => $file) {
          $info['attached']['js'][$key] = array(
            'data' => $info['path'] . '/' . $file,
            'group' => JS_THEME,
            'every_page' => TRUE,
            'weight' => -10,
          );
        }
      }
    }

    $context = $theme;

    // Give modules and themes a chance to alter the layout info array.
    drupal_alter('omega_layouts_info', $layouts[$theme], $context);
  }

  return $layouts[$theme];
}

/**
 * Retrieves the active layout for the current page.
 *
 * @return array|bool
 *   The info array for the active layout or FALSE if the current page does not
 *   use an alternative page layout.
 */
function omega_layout() {
  $cache = &drupal_static(__FUNCTION__);

  if (!isset($cache)) {
    $cache = FALSE;
    // Load the default layout from the theme settings.
    $layout = omega_theme_get_setting('omega_layout', 'epiqo');
    drupal_alter('omega_layout', $layout);

    $registry = theme_get_registry();
    if (isset($registry['page__layout__' . $layout]['layout'])) {
      $cache = $registry['page__layout__' . $layout]['layout'];
    }
  }

  return $cache;
}

/**
 * Allow themes to easily define libraries.
 *
 * @param $theme
 *   (Optional) The key (machine-readable name) of a theme. Defaults to the key
 *   of the current theme.
 *
 * @return array
 *   An array of libraries defined by themes in the theme trail of the given
 *   theme.
 */
function omega_theme_libraries_info($theme = NULL) {
  $theme = isset($theme) ? $theme : $GLOBALS['theme_key'];
  $libraries = drupal_static(__FUNCTION__);

  if (!isset($libraries[$theme])) {
    $libraries[$theme] = array();

    foreach (omega_invoke_all('omega_theme_libraries_info') as $library => $info) {
      $libraries[$theme][$library] = $info;
    }

    $context = $theme;

    // Give modules and themes a chance to alter the libraries info array.
    drupal_alter('omega_theme_libraries_info', $libraries[$theme], $context);
  }

  return $libraries[$theme];
}

/**
 * Helper function for discovering layouts, extensions or other pluggins of any
 * sort in the theme trail.
 *
 * @param $type
 *   A theme extension type (e.g. layout or extension).
 * @param $theme
 *   (Optional) The key (machine-readable name) of a theme. Defaults to the key
 *   of the current theme.
 * @param $all
 *   (Optional) Whether hidden elements should be listed. Defaults to FALSE.
 *
 * @return array
 *   An array containing the discovered definitions.
 */
function omega_discovery($type, $theme = NULL, $all = FALSE) {
  $discovery = array();
  $strlen = strlen($type) + 1;

  foreach (array_reverse(omega_theme_trail($theme)) as $key => $label) {
    $path = drupal_get_path('theme', $key);

    // Support files without '.inc' extension for backwards compatibilty.
    foreach (file_scan_directory($path, '/\.' . $type . '(\.inc)?$/', array('key' => 'name')) as $name => $file) {
      if (substr($name, -$strlen) === '.' . $type) {
        $name = substr($name, 0, strlen($name) - $strlen);
      }

      // The 'hidden' flag is used by starterkits/blueprints.
      if (($info = drupal_parse_info_file($file->uri)) && ($all || empty($info['hidden']))) {
        $discovery[$name] = array(
          'name' => $name,
          'path' => dirname($file->uri),
          'info' => $info,
          'theme' => $key,
        );
      }
    }
  }

  return $discovery;
}