css.inc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. <?php
  2. /*
  3. * @file
  4. * CSS filtering functions. Contains a disassembler, filter, compressor, and
  5. * decompressor.
  6. *
  7. * The general usage of this tool is:
  8. *
  9. * To simply filter CSS:
  10. * @code
  11. * $filtered_css = ctools_css_filter($css, TRUE);
  12. * @endcode
  13. *
  14. * In the above, if the second argument is TRUE, the returned CSS will
  15. * be compressed. Otherwise it will be returned in a well formatted
  16. * syntax.
  17. *
  18. * To cache unfiltered CSS in a file, which will be filtered:
  19. *
  20. * @code
  21. * $filename = ctools_css_cache($css, TRUE);
  22. * @endcode
  23. *
  24. * In the above, if the second argument is FALSE, the CSS will not be filtered.
  25. *
  26. * This file will be cached within the Drupal files system. This system cannot
  27. * detect when this file changes, so it is YOUR responsibility to remove and
  28. * re-cache this file when the CSS is changed. Your system should also contain
  29. * a backup method of re-generating the CSS cache in case it is removed, so
  30. * that it is easy to force a re-cache by simply deleting the contents of the
  31. * directory.
  32. *
  33. * Finally, if for some reason your application cannot store the filename
  34. * (which is true of Panels where the style can't force the display to
  35. * resave unconditionally) you can use the ctools storage mechanism. You
  36. * simply have to come up with a unique Id:
  37. *
  38. * @code
  39. * $filename = ctools_css_store($id, $css, TRUE);
  40. * @endcode
  41. *
  42. * Then later on:
  43. * @code
  44. * $filename = ctools_css_retrieve($id);
  45. * drupal_add_css($filename);
  46. * @endcode
  47. *
  48. * The CSS that was generated will be stored in the database, so even if the
  49. * file was removed the cached CSS will be used. If the CSS cache is
  50. * cleared you may be required to regenerate your CSS. This will normally
  51. * only be cleared by an administrator operation, not during normal usage.
  52. *
  53. * You may remove your stored CSS this way:
  54. *
  55. * @code
  56. * ctools_css_clear($id);
  57. * @endcode
  58. */
  59. /**
  60. * Store CSS with a given id and return the filename to use.
  61. *
  62. * This function associates a piece of CSS with an id, and stores the
  63. * cached filename and the actual CSS for later use with
  64. * ctools_css_retrieve.
  65. */
  66. function ctools_css_store($id, $css, $filter = TRUE) {
  67. $filename = db_query('SELECT filename FROM {ctools_css_cache} WHERE cid = :cid', array(':cid' => $id))->fetchField();
  68. if ($filename && file_exists($filename)) {
  69. file_unmanaged_delete($filename);
  70. }
  71. // Remove any previous records.
  72. db_delete('ctools_css_cache')
  73. ->condition('cid', $id)
  74. ->execute();
  75. $filename = ctools_css_cache($css, $filter);
  76. db_merge('ctools_css_cache')
  77. ->key(array('cid' => $id))
  78. ->fields(array(
  79. 'filename' => $filename,
  80. 'css' => $css,
  81. 'filter' => intval($filter),
  82. ))
  83. ->execute();
  84. return $filename;
  85. }
  86. /**
  87. * Retrieve a filename associated with an id of previously cached CSS.
  88. *
  89. * This will ensure the file still exists and, if not, create it.
  90. */
  91. function ctools_css_retrieve($id) {
  92. $cache = db_query('SELECT * FROM {ctools_css_cache} WHERE cid = :cid', array(':cid' => $id))->fetchObject();
  93. if (!$cache) {
  94. return;
  95. }
  96. if (!file_exists($cache->filename)) {
  97. $filename = ctools_css_cache($cache->css, $cache->filter);
  98. if ($filename != $cache->filename) {
  99. db_update('ctools_css_cache')
  100. ->fields(array('filename' => $filename))
  101. ->condition('cid', $id)
  102. ->execute();
  103. $cache->filename = $filename;
  104. }
  105. }
  106. return $cache->filename;
  107. }
  108. /**
  109. * Remove stored CSS and any associated file.
  110. */
  111. function ctools_css_clear($id) {
  112. $cache = db_query('SELECT * FROM {ctools_css_cache} WHERE cid = :cid', array(':cid' => $id))->fetchObject();
  113. if (!$cache) {
  114. return;
  115. }
  116. if (file_exists($cache->filename)) {
  117. file_unmanaged_delete($cache->filename);
  118. // If we remove an existing file, there may be cached pages that refer
  119. // to it. We must get rid of them: FIXME same format in D7?
  120. cache_clear_all();
  121. }
  122. db_delete('ctools_css_cache')
  123. ->condition('cid', $id)
  124. ->execute();
  125. }
  126. /**
  127. * Write a chunk of CSS to a temporary cache file and return the file name.
  128. *
  129. * This function optionally filters the CSS (always compressed, if so) and
  130. * generates a unique filename based upon md5. It returns that filename that
  131. * can be used with drupal_add_css(). Note that as a cache file, technically
  132. * this file is volatile so it should be checked before it is used to ensure
  133. * that it exists.
  134. *
  135. * You can use file_exists() to test for the file and file_delete() to remove
  136. * it if it needs to be cleared.
  137. *
  138. * @param $css
  139. * A chunk of well-formed CSS text to cache.
  140. * @param $filter
  141. * If TRUE the css will be filtered. If FALSE the text will be cached
  142. * as-is.
  143. *
  144. * @return $filename
  145. * The filename the CSS will be cached in.
  146. */
  147. function ctools_css_cache($css, $filter = TRUE) {
  148. if ($filter) {
  149. $css = ctools_css_filter($css);
  150. }
  151. // Create the css/ within the files folder.
  152. $path = 'public://ctools/css';
  153. if (!file_prepare_directory($path, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
  154. // if (!file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
  155. drupal_set_message(t('Unable to create CTools CSS cache directory. Check the permissions on your files directory.'), 'error');
  156. return;
  157. }
  158. // @todo Is this slow? Does it matter if it is?
  159. $filename = $path . '/' . md5($css) . '.css';
  160. // Generally md5 is considered unique enough to sign file downloads.
  161. // So this replaces already existing files based on the assumption that two
  162. // files with the same hash are identical content wise.
  163. // If we rename, the cache folder can potentially fill up with thousands of
  164. // files with the same content.
  165. $filename = file_unmanaged_save_data($css, $filename, FILE_EXISTS_REPLACE);
  166. return $filename;
  167. }
  168. /**
  169. * Filter a chunk of CSS text.
  170. *
  171. * This function disassembles the CSS into a raw format that makes it easier
  172. * for our tool to work, then runs it through the filter and reassembles it.
  173. * If you find that you want the raw data for some reason or another, you
  174. * can use the disassemble/assemble functions yourself.
  175. *
  176. * @param $css
  177. * The CSS text to filter.
  178. * @param $compressed
  179. * If true, generate compressed output; if false, generate pretty output.
  180. * Defaults to TRUE.
  181. */
  182. function ctools_css_filter($css, $compressed = TRUE) {
  183. $css_data = ctools_css_disassemble($css);
  184. // Note: By using this function yourself you can control the allowed
  185. // properties and values list.
  186. $filtered = ctools_css_filter_css_data($css_data);
  187. return $compressed ? ctools_css_compress($filtered) : ctools_css_assemble($filtered);
  188. }
  189. /**
  190. * Re-assemble a css string and format it nicely.
  191. *
  192. * @param array $css_data
  193. * An array of css data, as produced by @see ctools_css_disassemble()
  194. * disassembler and the @see ctools_css_filter_css_data() filter.
  195. *
  196. * @return string $css
  197. * css optimized for human viewing.
  198. */
  199. function ctools_css_assemble($css_data) {
  200. // Initialize the output.
  201. $css = '';
  202. // Iterate through all the statements.
  203. foreach ($css_data as $selector_str => $declaration) {
  204. // Add the selectors, separating them with commas and line feeds.
  205. $css .= strpos($selector_str, ',') === FALSE ? $selector_str : str_replace(", ", ",\n", $selector_str);
  206. // Add the opening curly brace.
  207. $css .= " {\n";
  208. // Iterate through all the declarations.
  209. foreach ($declaration as $property => $value) {
  210. $css .= " " . $property . ": " . $value . ";\n";
  211. }
  212. // Add the closing curly brace.
  213. $css .= "}\n\n";
  214. }
  215. // Return the output.
  216. return $css;
  217. }
  218. /**
  219. * Compress css data (filter it first!) to optimize for use on view.
  220. *
  221. * @param array $css_data
  222. * An array of css data, as produced by @see ctools_css_disassemble()
  223. * disassembler and the @see ctools_css_filter_css_data() filter.
  224. *
  225. * @return string $css
  226. * css optimized for use.
  227. */
  228. function ctools_css_compress($css_data) {
  229. // Initialize the output.
  230. $css = '';
  231. // Iterate through all the statements.
  232. foreach ($css_data as $selector_str => $declaration) {
  233. if (empty($declaration)) {
  234. // Skip this statement if filtering removed all parts of the declaration.
  235. continue;
  236. }
  237. // Add the selectors, separating them with commas.
  238. $css .= $selector_str;
  239. // And, the opening curly brace.
  240. $css .= "{";
  241. // Iterate through all the statement properties.
  242. foreach ($declaration as $property => $value) {
  243. $css .= $property . ':' . $value . ';';
  244. }
  245. // Add the closing curly brace.
  246. $css .= "}";
  247. }
  248. // Return the output.
  249. return $css;
  250. }
  251. /**
  252. * Disassemble the css string.
  253. *
  254. * Strip the css of irrelevant characters, invalid/malformed selectors and
  255. * declarations, and otherwise prepare it for processing.
  256. *
  257. * @param string $css
  258. * A string containing the css to be disassembled.
  259. *
  260. * @return array $disassembled_css
  261. * An array of disassembled, slightly cleaned-up/formatted css statements.
  262. */
  263. function ctools_css_disassemble($css) {
  264. $disassembled_css = array();
  265. // Remove comments.
  266. $css = preg_replace("/\/\*(.*)?\*\//Usi", "", $css);
  267. // Split out each statement. Match either a right curly brace or a semi-colon
  268. // that precedes a left curly brace with no right curly brace separating them.
  269. $statements = preg_split('/}|;(?=[^}]*{)/', $css);
  270. // If we have any statements, parse them.
  271. if (!empty($statements)) {
  272. // Iterate through all of the statements.
  273. foreach ($statements as $statement) {
  274. // Get the selector(s) and declaration.
  275. if (empty($statement) || !strpos($statement, '{')) {
  276. continue;
  277. }
  278. list($selector_str, $declaration) = explode('{', $statement);
  279. // If the selector exists, then disassemble it, check it, and regenerate
  280. // the selector string.
  281. $selector_str = empty($selector_str) ? FALSE : _ctools_css_disassemble_selector($selector_str);
  282. if (empty($selector_str)) {
  283. // No valid selectors. Bomb out and start the next item.
  284. continue;
  285. }
  286. // Disassemble the declaration, check it and tuck it into an array.
  287. if (!isset($disassembled_css[$selector_str])) {
  288. $disassembled_css[$selector_str] = array();
  289. }
  290. $disassembled_css[$selector_str] += _ctools_css_disassemble_declaration($declaration);
  291. }
  292. }
  293. return $disassembled_css;
  294. }
  295. function _ctools_css_disassemble_selector($selector_str) {
  296. // Get all selectors individually.
  297. $selectors = explode(",", trim($selector_str));
  298. // Iterate through all the selectors, sanity check them and return if they
  299. // pass. Note that this handles 0, 1, or more valid selectors gracefully.
  300. foreach ($selectors as $key => $selector) {
  301. // Replace un-needed characters and do a little cleanup.
  302. $selector = preg_replace("/[\n|\t|\\|\s]+/", ' ', trim($selector));
  303. // Make sure this is still a real selector after cleanup.
  304. if (!empty($selector)) {
  305. $selectors[$key] = $selector;
  306. }
  307. else {
  308. // Selector is no good, so we scrap it.
  309. unset($selectors[$key]);
  310. }
  311. }
  312. // Check for malformed selectors; if found, we skip this declaration.
  313. if (empty($selectors)) {
  314. return FALSE;
  315. }
  316. return implode(', ', $selectors);
  317. }
  318. function _ctools_css_disassemble_declaration($declaration) {
  319. $formatted_statement = array();
  320. $propval_pairs = explode(";", $declaration);
  321. // Make sure we actually have some properties to work with.
  322. if (!empty($propval_pairs)) {
  323. // Iterate through the remains and parse them.
  324. foreach ($propval_pairs as $key => $propval_pair) {
  325. // Check that we have a ':', otherwise it's an invalid pair.
  326. if (strpos($propval_pair, ':') === FALSE) {
  327. continue;
  328. }
  329. // Clean up the current property-value pair.
  330. $propval_pair = preg_replace("/[\n|\t|\\|\s]+/", ' ', trim($propval_pair));
  331. // Explode the remaining fragements some more, but clean them up first.
  332. list($property, $value) = explode(':', $propval_pair, 2);
  333. // If the property survived, toss it onto the stack.
  334. if (!empty($property)) {
  335. $formatted_statement[trim($property)] = trim($value);
  336. }
  337. }
  338. }
  339. return $formatted_statement;
  340. }
  341. /**
  342. * Run disassembled $css through the filter.
  343. *
  344. * @param $css
  345. * CSS code disassembled by ctools_dss_disassemble().
  346. * @param $allowed_properties
  347. * A list of properties that are allowed by the filter. If empty
  348. * ctools_css_filter_default_allowed_properties() will provide the
  349. * list.
  350. * @param $allowed_values
  351. * A list of values that are allowed by the filter. If empty
  352. * ctools_css_filter_default_allowed_values() will provide the
  353. * list.
  354. *
  355. * @return
  356. * An array of disassembled, filtered CSS.
  357. */
  358. function ctools_css_filter_css_data($css, $allowed_properties = array(), $allowed_values = array(), $allowed_values_regex = '', $disallowed_values_regex = '') {
  359. //function ctools_css_filter_css_data($css, &$filtered = NULL, $allowed_properties = array(), $allowed_values = array(), $allowed_values_regex = '', $disallowed_values_regex = '') {
  360. // Retrieve the default list of allowed properties if none is provided.
  361. $allowed_properties = !empty($allowed_properties) ? $allowed_properties : ctools_css_filter_default_allowed_properties();
  362. // Retrieve the default list of allowed values if none is provided.
  363. $allowed_values = !empty($allowed_values) ? $allowed_values : ctools_css_filter_default_allowed_values();
  364. // Define allowed values regex if none is provided.
  365. $allowed_values_regex = !empty($allowed_values_regex) ? $allowed_values_regex : '/(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)/';
  366. // Define disallowed url() value contents, if none is provided.
  367. // $disallowed_values_regex = !empty($disallowed_values_regex) ? $disallowed_values_regex : '/[url|expression]\s*\(\s*[^\s)]+?\s*\)\s*/';
  368. $disallowed_values_regex = !empty($disallowed_values_regex) ? $disallowed_values_regex : '/(url|expression)/';
  369. foreach ($css as $selector_str => $declaration) {
  370. foreach ($declaration as $property => $value) {
  371. if (!in_array($property, $allowed_properties)) {
  372. // $filtered['properties'][$selector_str][$property] = $value;
  373. unset($css[$selector_str][$property]);
  374. continue;
  375. }
  376. $value = str_replace('!important', '', $value);
  377. if (preg_match($disallowed_values_regex, $value) || !(in_array($value, $allowed_values) || preg_match($allowed_values_regex, $value))) {
  378. // $filtered['values'][$selector_str][$property] = $value;
  379. unset($css[$selector_str][$property]);
  380. continue;
  381. }
  382. }
  383. }
  384. return $css;
  385. }
  386. /**
  387. * Provide a deafult list of allowed properties by the filter.
  388. */
  389. function ctools_css_filter_default_allowed_properties() {
  390. return array(
  391. 'azimuth',
  392. 'background',
  393. 'background-color',
  394. 'background-image',
  395. 'background-repeat',
  396. 'background-attachment',
  397. 'background-position',
  398. 'border',
  399. 'border-top-width',
  400. 'border-right-width',
  401. 'border-bottom-width',
  402. 'border-left-width',
  403. 'border-width',
  404. 'border-top-color',
  405. 'border-right-color',
  406. 'border-bottom-color',
  407. 'border-left-color',
  408. 'border-color',
  409. 'border-top-style',
  410. 'border-right-style',
  411. 'border-bottom-style',
  412. 'border-left-style',
  413. 'border-style',
  414. 'border-top',
  415. 'border-right',
  416. 'border-bottom',
  417. 'border-left',
  418. 'clear',
  419. 'color',
  420. 'cursor',
  421. 'direction',
  422. 'display',
  423. 'elevation',
  424. 'float',
  425. 'font',
  426. 'font-family',
  427. 'font-size',
  428. 'font-style',
  429. 'font-variant',
  430. 'font-weight',
  431. 'height',
  432. 'letter-spacing',
  433. 'line-height',
  434. 'margin',
  435. 'margin-top',
  436. 'margin-right',
  437. 'margin-bottom',
  438. 'margin-left',
  439. 'overflow',
  440. 'padding',
  441. 'padding-top',
  442. 'padding-right',
  443. 'padding-bottom',
  444. 'padding-left',
  445. 'pause',
  446. 'pause-after',
  447. 'pause-before',
  448. 'pitch',
  449. 'pitch-range',
  450. 'richness',
  451. 'speak',
  452. 'speak-header',
  453. 'speak-numeral',
  454. 'speak-punctuation',
  455. 'speech-rate',
  456. 'stress',
  457. 'text-align',
  458. 'text-decoration',
  459. 'text-indent',
  460. 'text-transform',
  461. 'unicode-bidi',
  462. 'vertical-align',
  463. 'voice-family',
  464. 'volume',
  465. 'white-space',
  466. 'width',
  467. 'fill',
  468. 'fill-opacity',
  469. 'fill-rule',
  470. 'stroke',
  471. 'stroke-width',
  472. 'stroke-linecap',
  473. 'stroke-linejoin',
  474. 'stroke-opacity',
  475. );
  476. }
  477. /**
  478. * Provide a default list of allowed values by the filter.
  479. */
  480. function ctools_css_filter_default_allowed_values() {
  481. return array(
  482. 'auto',
  483. 'aqua',
  484. 'black',
  485. 'block',
  486. 'blue',
  487. 'bold',
  488. 'both',
  489. 'bottom',
  490. 'brown',
  491. 'capitalize',
  492. 'center',
  493. 'collapse',
  494. 'dashed',
  495. 'dotted',
  496. 'fuchsia',
  497. 'gray',
  498. 'green',
  499. 'italic',
  500. 'inherit',
  501. 'left',
  502. 'lime',
  503. 'lowercase',
  504. 'maroon',
  505. 'medium',
  506. 'navy',
  507. 'normal',
  508. 'nowrap',
  509. 'olive',
  510. 'pointer',
  511. 'purple',
  512. 'red',
  513. 'right',
  514. 'solid',
  515. 'silver',
  516. 'teal',
  517. 'top',
  518. 'transparent',
  519. 'underline',
  520. 'uppercase',
  521. 'white',
  522. 'yellow',
  523. );
  524. }
  525. /**
  526. * Delegated implementation of hook_flush_caches()
  527. */
  528. function ctools_css_flush_caches() {
  529. // Remove all generated files.
  530. // @see http://drupal.org/node/573292
  531. // file_unmanaged_delete_recursive('public://render');
  532. $filedir = file_default_scheme() . '://ctools/css';
  533. if (drupal_realpath($filedir) && file_exists($filedir)) {
  534. // We use the @ because it's possible that files created by the webserver
  535. // cannot be deleted while using drush to clear the cache. We don't really
  536. // care that much about that, to be honest, so we use the @ to suppress
  537. // the error message.
  538. @file_unmanaged_delete_recursive($filedir);
  539. }
  540. db_delete('ctools_css_cache')->execute();
  541. }