-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstyle_settings.module
657 lines (616 loc) · 20.8 KB
/
style_settings.module
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
<?php
/**
* @file
* Use any (custom) theme setting or backdrop variable in any of your theme or
* module style sheets (see https://backdrop.org/project/style_settings).
*/
define('STYLE_SETTINGS_STYLESHEET_DIR', 'public://style_settings/');
/**
* Implements hook_config_info().
*/
function style_settings_config_info() {
$prefixes['style_settings.settings'] = array(
'label' => t('Style settings'),
'group' => t('Configuration'),
);
return $prefixes;
}
/**
* Implements hook_init().
*/
function style_settings_init() {
backdrop_add_css(backdrop_get_path('module', 'style_settings') . '/css/style_settings.css', array(
'group' => CSS_DEFAULT,
'every_page' => TRUE,
));
// Make sure the site's custom CSS is processed last.
backdrop_add_css(backdrop_get_path('module', 'style_settings') . '/css/custom.css', array(
'group' => CSS_THEME,
'every_page' => TRUE,
'weight' => 99,
));
}
/**
* Implements hook_css_alter().
*/
function style_settings_css_alter(&$css) {
// When _backdrop_flush_css_js() changes the 'css_js_query_string', we will use
// this as a directive to bypass the caching of the rewritten paths.
$css_js_query_string_changed = state_get('css_js_query_string', '0') != config_get('style_settings.settings', 'style_settings_last_css_js_query_string', '0');
// Get all themes that use Style (CSS) Settings.
// They got 'soft_dependencies[] = style_settings' in their '.info' file.
$themes = array_keys(array_filter(system_get_info('theme'), function($ar) {
if (isset($ar['soft_dependencies'])) {
return in_array('style_settings', $ar['soft_dependencies']);
}
elseif (isset($ar['dependencies'])) {
return in_array('style_settings', $ar['dependencies']);
}
}));
// Process each theme that has a (soft-)dependency.
foreach ($themes as $theme) {
if (style_settings_theme_exists($theme)) {
$path_to_theme = backdrop_get_path('theme', $theme);
// Process each style sheet of a theme.
foreach ($css as $path => $stylesheet) {
if (file_exists($path) && strpos($path, $path_to_theme) !== FALSE) {
if ($new_path = style_settings_rewrite($path, $css_js_query_string_changed, $theme)) {
$relative_uri = file_create_relative_uri($new_path);
$css[$relative_uri] = $css[$path];
$css[$relative_uri]['data'] = $relative_uri;
unset($css[$path]);
}
}
}
}
}
// Get all modules that use Style (CSS) Settings.
// They got 'soft_dependencies[] = style_settings' in their '.info' file.
$modules = array_keys(array_filter(system_get_info('module'), function($ar) {
if (isset($ar['soft_dependencies'])) {
return in_array('style_settings', $ar['soft_dependencies']);
}
elseif (isset($ar['dependencies'])) {
return in_array('style_settings', $ar['dependencies']);
}
}));
// Process submodules first.
$modules = array_reverse($modules);
// Process each module that has a (soft-)dependency.
foreach ($modules as $module) {
if (module_exists($module)) {
$path_to_module = backdrop_get_path('module', $module);
// Process each style sheet of a module.
foreach ($css as $path => $stylesheet) {
if (file_exists($path) && strpos($path, $path_to_module) !== FALSE) {
if ($new_path = style_settings_rewrite($path, $css_js_query_string_changed, $module)) {
$relative_uri = file_create_relative_uri($new_path);
$css[$relative_uri] = $css[$path];
$css[$relative_uri]['data'] = $relative_uri;
unset($css[$path]);
}
}
}
}
}
if ($css_js_query_string_changed) {
config_set('style_settings.settings', 'style_settings_last_css_js_query_string', state_get('css_js_query_string', '0'));
}
}
/**
* Rewrite a style sheet and return the path to the rewritten one.
*/
function style_settings_rewrite($path, $reset = FALSE, $project) {
// Get the active theme and all available persistent variables ($conf).
global $conf;
// Caching hashed 'new paths' as it is expensive to calculate these values.
$cid = 'style_settings_' . $path;
$new_path_cached = cache_get($cid);
$new_path = isset($new_path_cached->data) ? $new_path_cached->data : FALSE;
// We need a new unique key (and rewrite) if the original CSS file changed.
$change = (string) @filectime($path);
// Detect remote files where 'filectime()' returns FALSE.
$remote = empty($change);
// Exclude variables that change on each page load.
unset($conf['backdrop_css_cache_files']);
unset($conf['backdrop_js_cache_files']);
if (!$new_path || $reset) {
// Get all settings of the current theme or module.
$json_string = config_get_config_directory('active') . '/' . $project . '.settings.json';
$jsondata = file_exists($json_string) ? file_get_contents($json_string) : NULL;
$settings = json_decode($jsondata, true);
// Generate a unique key based on theme settings, variables and file date.
$checksum = md5(serialize($settings) . serialize($conf) . $change);
// Generate the filename for the customized CSS file.
$new_path = STYLE_SETTINGS_STYLESHEET_DIR . $checksum . '.' . basename($path);
cache_set($cid, $new_path);
}
// Generate the customized CSS file itself if it doesn't exist yet.
if ($remote || !file_exists($new_path)) {
$realpath = backdrop_realpath($new_path);
$dirname = dirname($realpath);
file_prepare_directory($dirname, FILE_CREATE_DIRECTORY);
$old_data = file_get_contents(file_create_url($path));
// Prefix all paths, ignoring absolute paths.
_backdrop_build_css_path(NULL, base_path() . dirname($path) . '/');
$new_data = preg_replace_callback('/url\([\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\)/i', '_backdrop_build_css_path', $old_data);
// Replace all custom css. We make use of an anonymous function to be able
// to pass the variable '$project'.
// See http://php.net/manual/en/functions.anonymous.php.
$new_data = preg_replace_callback('/\/\*\s*(setting|variable)\s*:\s*([a-z0-9_]+)\s*\*\/(.*)\/\*\s*.*\s*\*\//iU', function ($matches) use($project) {
global $theme_key;
$type = $matches[1];
$name = $matches[2];
$original = $matches[3];
// Cache settings for next calls.
if ($type == 'setting') {
$setting = theme_get_setting($name);
}
// Variable.
if ($type == 'variable') {
$replacement = config_get($project . '.settings', $name);
if (empty($replacement)) {
$replacement = variable_get($name, NULL);
}
if (!$replacement || !(is_string($replacement) || is_numeric($replacement))) {
return $original;
}
}
// Theme setting.
else {
$replacement = $setting;
if (!$replacement) {
return $original;
}
}
// Since a comment cannot be in url(), we have to add this around the
// replacement (if the user doesn't).
if (preg_match('/url\(.*\)/i', $original) && !preg_match('/url\(.*\)/i', $replacement)) {
// Prefix path, ignoring absolute paths.
if (!preg_match('/^([a-z]+:|\/+)/', $replacement)) {
$replacement = base_path() . $replacement;
}
$replacement = 'url(\'' . $replacement . '\')';
}
return $replacement;
}, $new_data, $limit = -1, $count);
// Only rewrite a CSS file if any replacements were made.
if ($count > 0) {
file_unmanaged_save_data($new_data, $new_path, FILE_EXISTS_REPLACE);
$watchdog = l(t('Recent log messages'), 'admin/reports/dblog', array(
'attributes' => array(
'title' => t('Home » Administration » Reports'),
),
));
backdrop_set_message(t('Style Settings CSS files have been rewritten successfully. Check !watchdog for details.', array('!watchdog' => $watchdog)), 'status', FALSE);
watchdog('style_settings', 'Rewritten successfully %path to %new_path', array('%path' => $path, '%new_path' => $new_path));
}
}
// Cleanup leftover files.
$generated_files = glob(backdrop_realpath(STYLE_SETTINGS_STYLESHEET_DIR) . '/*');
$fileinfo = pathinfo($path);
foreach ($generated_files as $generated_file) {
if (strpos($generated_file, $fileinfo['basename']) !== FALSE && $generated_file != backdrop_realpath($new_path)) {
file_unmanaged_delete($generated_file);
}
}
// Return the new path if the file exists.
if (file_exists($new_path)) {
return $new_path;
}
else {
return FALSE;
}
}
/**
* Callback for creating a relative uri from a streamwrapper.
*/
function file_create_relative_uri($path) {
global $base_url;
$url = file_create_url($path);
$relative_uri = str_replace($base_url . '/', '', $url);
return $relative_uri;
}
/**
* Like backdrop's core 'module_exists()' but for enabled themes.
*/
function style_settings_theme_exists($theme_name) {
$themes = list_themes();
return isset($themes[$theme_name]) && $themes[$theme_name]->status == 1;
}
/**
* Implements hook_element_info().
*/
function style_settings_element_info() {
$colornames = l(t('valid color names'), 'https://en.wikipedia.org/wiki/Web_colors#X11_color_names', array(
'attributes' => array(
'title' => t('Web colors - Wikipedia, the free encyclopedia'),
'target' => '_blank',
),
));
$types['style_settings_colorpicker'] = array(
'#input' => TRUE,
'#type' => 'textfield',
'#theme' => array('textfield'),
'#theme_wrappers' => array('form_element'),
'#autocomplete_path' => FALSE,
'#element_validate' => array('style_settings_color_validate'),
'#size' => 12,
'#maxlength' => 20,
'#description' => t('Also shorthand (like #fff) and !colornames are accepted.', array('!colornames' => $colornames)),
'#prefix' => '<div class="form-item form-type-style-settings-colorpicker">',
'#suffix' => '<div class="style_settings-picker"></div></div>',
'#default_value' => '',
'#attributes' => array('class' => array('style_settings-colorpicker')),
'#attached' => array(
'library' => array(array('system', 'farbtastic')),
'js' => array(backdrop_get_path('module', 'style_settings') . '/js/style_settings-farbtastic.js'),
),
);
$types['style_settings_number'] = array(
'#input' => TRUE,
'#min' => 0,
'#size' => 4,
'#process' => array('ajax_process_form'),
'#element_validate' => array('style_settings_validate_number'),
'#value_callback' => '_style_settings_number_value_callback',
'#theme' => 'style_settings_number',
'#theme_wrappers' => array('form_element'),
'#input_help' => TRUE,
'#attributes' => array('class' => array('style-settings-form-align')),
);
$types['style_settings_slider'] = array(
'#input' => TRUE,
'#step' => 0.01,
'#min' => 0,
'#max' => 1,
'#process' => array('ajax_process_form'),
'#element_validate' => array('style_settings_validate_number'),
'#value_callback' => '_style_settings_number_value_callback',
'#theme' => 'style_settings_slider',
'#theme_wrappers' => array('form_element'),
);
$types['style_settings_imgurl'] = array(
'#input' => TRUE,
'#theme' => 'style_settings_imgurl',
'#theme_wrappers' => array('form_element'),
'#element_validate' => array('style_settings_imgurl_validate'),
'#suffix' => '</div>',
'#size' => 60,
'#maxlength' => 160,
);
return $types;
}
/**
* Validates that the input value matches a hexadecimal color.
*/
function style_settings_color_validate($element, &$form_state) {
if (!empty($element['#value'])) {
// Double check that we really have an hexadecimal value.
if (style_settings_validate_html_color($element['#value'], 1) == FALSE) {
form_error($element, '<em>' . check_plain($element['#value']) . '</em> ' . t('is not a valid color'));
}
}
}
/**
* Validates hex color. Checks for a Color Name first to prevent error if a name
* was entered (optional).
*
* $color: The color hex value stirng to Validates $named: (optional), set to
* 1 or TRUE to first test if a Named color was passed instead of a Hex value.
*/
function style_settings_validate_html_color($color, $named = TRUE) {
if ($named) {
$named = array(
'aliceblue',
'antiquewhite',
'aqua',
'aquamarine',
'azure',
'beige',
'bisque',
'black',
'blanchedalmond',
'blue',
'blueviolet',
'brown',
'burlywood',
'cadetblue',
'chartreuse',
'chocolate',
'coral',
'cornflowerblue',
'cornsilk',
'crimson',
'cyan',
'darkblue',
'darkcyan',
'darkgoldenrod',
'darkgray',
'darkgreen',
'darkkhaki',
'darkmagenta',
'darkolivegreen',
'darkorange',
'darkorchid',
'darkred',
'darksalmon',
'darkseagreen',
'darkslateblue',
'darkslategray',
'darkturquoise',
'darkviolet',
'deeppink',
'deepskyblue',
'dimgray',
'dodgerblue',
'firebrick',
'floralwhite',
'forestgreen',
'fuchsia',
'gainsboro',
'ghostwhite',
'gold',
'goldenrod',
'gray',
'green',
'greenyellow',
'honeydew',
'hotpink',
'indianred',
'indigo',
'ivory',
'khaki',
'lavender',
'lavenderblush',
'lawngreen',
'lemonchiffon',
'lightblue',
'lightcoral',
'lightcyan',
'lightgoldenrodyellow',
'lightgreen',
'lightgrey',
'lightpink',
'lightsalmon',
'lightseagreen',
'lightskyblue',
'lightslategray',
'lightsteelblue',
'lightyellow',
'lime',
'limegreen',
'linen',
'magenta',
'maroon',
'mediumaquamarine',
'mediumblue',
'mediumorchid',
'mediumpurple',
'mediumseagreen',
'mediumslateblue',
'mediumspringgreen',
'mediumturquoise',
'mediumvioletred',
'midnightblue',
'mintcream',
'mistyrose',
'moccasin',
'navajowhite',
'navy',
'oldlace',
'olive',
'olivedrab',
'orange',
'orangered',
'orchid',
'palegoldenrod',
'palegreen',
'paleturquoise',
'palevioletred',
'papayawhip',
'peachpuff',
'peru',
'pink',
'plum',
'powderblue',
'purple',
'red',
'rosybrown',
'royalblue',
'saddlebrown',
'salmon',
'sandybrown',
'seagreen',
'seashell',
'sienna',
'silver',
'skyblue',
'slateblue',
'slategray',
'snow',
'springgreen',
'steelblue',
'tan',
'teal',
'thistle',
'tomato',
'turquoise',
'violet',
'wheat',
'white',
'whitesmoke',
'yellow',
'yellowgreen',
);
if (in_array(strtolower($color), $named)) {
return $color;
}
}
if (preg_match('/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i', $color)) {
return $color;
}
return FALSE;
}
/**
* Form element validation handler for #type 'style_settings_number'.
*
* Note that #required is validated by _form_validate() already.
*/
function style_settings_validate_number(&$element, &$form_state) {
$element['#value'] = floatval($element['#value']);
$value = $element['#value'];
if ($value === '') {
return;
}
$name = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];
// Ensure the input is numeric.
if (!is_numeric($value)) {
form_error($element, t('%name must be a number.', array('%name' => $name)));
return;
}
// Ensure that the input is greater than the #min property, if set.
if (isset($element['#min']) && $value < $element['#min']) {
form_error($element, t('%name must be higher or equal to %min.', array('%name' => $name, '%min' => $element['#min'])));
}
// Ensure that the input is less than the #max property, if set.
if (isset($element['#max']) && $value > $element['#max']) {
form_error($element, t('%name must be below or equal to %max.', array('%name' => $name, '%max' => $element['#max'])));
}
if (isset($element['#step']) && strtolower($element['#step']) != 'any') {
// Check that the input is an allowed multiple of #step (offset by #min if
// #min is set).
$offset = isset($element['#min']) ? $element['#min'] : 0.0;
if (!style_settings_valid_number_step($value, $element['#step'], $offset)) {
form_error($element, t('%name is not a multiple of %step.', array('%name' => $name, '%step' => $element['#step'])));
}
}
}
/**
* Verifies that a number is a multiple of a given step.
*
* The implementation assumes it is dealing with IEEE 754 double precision
* floating point numbers that are used by PHP on most systems.
*
* This is based on the number/range verification methods of webkit.
*
* @param $value
* The value that needs to be checked.
* @param $step
* The step scale factor. Must be positive.
* @param $offset
* (optional) An offset, to which the difference must be a multiple of the
* given step.
*
* @return bool
* TRUE if no step mismatch has occured, or FALSE otherwise.
*
* @see http://opensource.apple.com/source/WebCore/WebCore-1298/html/NumberInputType.cpp
*/
function style_settings_valid_number_step($value, $step, $offset = 0.0) {
$double_value = (double) abs($value - $offset);
// The fractional part of a double has 53 bits. The greatest number that could
// be represented with that is 2^53. If the given value is even bigger than
// $step * 2^53, then dividing by $step will result in a very small remainder.
// Since that remainder can't even be represented with a single precision
// float the following computation of the remainder makes no sense and we can
// safely ignore it instead.
if ($double_value / pow(2.0, 53) > $step) {
return TRUE;
}
// Now compute that remainder of a division by $step.
$remainder = (double) abs($double_value - $step * round($double_value / $step));
// $remainder is a double precision floating point number. Remainders that
// can't be represented with single precision floats are acceptable. The
// fractional part of a float has 24 bits. That means remainders smaller than
// $step * 2^-24 are acceptable.
$computed_acceptable_error = (double) ($step / pow(2.0, 24));
return $computed_acceptable_error >= $remainder || $remainder >= ($step - $computed_acceptable_error);
}
/**
* Validates an image URL if not empty.
* Checks syntax, existence and being an image.
*/
function style_settings_imgurl_validate(&$element, &$form_state) {
// An image URL with leading or trailing whitespace is still valid in CSS.
$url = trim($element['#value']);
$name = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];
// An empty image URL resulting in url('') is still valid in CSS.
if (!empty($url)) {
// Get the base URL.
global $base_url;
// For a relative URL append the base URL.
if (parse_url($url, PHP_URL_SCHEME) == '') {
$url = $base_url . $url;
}
$headers = @get_headers($url, 1);
if (isset($headers['Content-Type'])) {
// Generate an error if the URL isn't an image or returns a 404.
if (strpos($headers['Content-Type'], 'image/') === FALSE) {
form_set_error($element['#parents'][0], t('%name is not an image, does not exist or something else is wrong with it.', array('%name' => $name)));
}
}
else {
// No 'Content-Type' returned.
form_set_error($element['#parents'][0], t('%name is not a valid URL.', array('%name' => $name)));
}
}
}
/**
* Form element input handler for #type 'style_settings_number'.
*/
function _style_settings_number_value_callback($element, $input = FALSE, &$form_state) {
if ($input !== FALSE) {
if (isset($element['#field_suffix'])) {
// If the field suffix is a valid unit, use it.
if (in_array(strtolower($element['#field_suffix']), array(
'px',
'em',
'%',
'rem',
'cm',
'ex',
'in',
'mm',
'pc',
'pt',
'vh',
'vw',
'vmin',
))) {
return $form_state['input'][$element['#name']] . $element['#field_suffix'];
}
else {
return $form_state['input'][$element['#name']];
}
}
else {
return $form_state['input'][$element['#name']];
}
}
elseif (!empty($element['#default_value'])) {
return $element['#default_value'];
}
}
/**
* Implements hook_theme().
*/
function style_settings_theme() {
return array(
'style_settings_number' => array(
'arguments' => array('element' => NULL),
'render element' => 'element',
'file' => 'style_settings.theme.inc',
),
'style_settings_slider' => array(
'arguments' => array('element' => NULL),
'render element' => 'element',
'file' => 'style_settings.theme.inc',
),
'style_settings_imgurl' => array(
'arguments' => array('element' => NULL),
'render element' => 'element',
'file' => 'style_settings.theme.inc',
),
);
}