css.inc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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 bool $filter
  141. * If TRUE the css will be filtered. If FALSE the text will be cached
  142. * as-is.
  143. *
  144. * @return string
  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. drupal_set_message(t('Unable to create CTools CSS cache directory. Check the permissions on your files directory.'), 'error');
  155. return;
  156. }
  157. // @todo Is this slow? Does it matter if it is?
  158. $filename = $path . '/' . md5($css) . '.css';
  159. // Generally md5 is considered unique enough to sign file downloads.
  160. // So this replaces already existing files based on the assumption that two
  161. // files with the same hash are identical content wise.
  162. // If we rename, the cache folder can potentially fill up with thousands of
  163. // files with the same content.
  164. $filename = file_unmanaged_save_data($css, $filename, FILE_EXISTS_REPLACE);
  165. return $filename;
  166. }
  167. /**
  168. * Filter a chunk of CSS text.
  169. *
  170. * This function disassembles the CSS into a raw format that makes it easier
  171. * for our tool to work, then runs it through the filter and reassembles it.
  172. * If you find that you want the raw data for some reason or another, you
  173. * can use the disassemble/assemble functions yourself.
  174. *
  175. * @param $css
  176. * The CSS text to filter.
  177. * @param $compressed
  178. * If true, generate compressed output; if false, generate pretty output.
  179. * Defaults to TRUE.
  180. */
  181. function ctools_css_filter($css, $compressed = TRUE) {
  182. $css_data = ctools_css_disassemble($css);
  183. // Note: By using this function yourself you can control the allowed
  184. // properties and values list.
  185. $filtered = ctools_css_filter_css_data($css_data);
  186. return $compressed ? ctools_css_compress($filtered) : ctools_css_assemble($filtered);
  187. }
  188. /**
  189. * Re-assemble a css string and format it nicely.
  190. *
  191. * @param array $css_data
  192. * An array of css data, as produced by @see ctools_css_disassemble()
  193. * disassembler and the @see ctools_css_filter_css_data() filter.
  194. *
  195. * @return string
  196. * css optimized for human viewing.
  197. */
  198. function ctools_css_assemble($css_data) {
  199. // Initialize the output.
  200. $css = '';
  201. // Iterate through all the statements.
  202. foreach ($css_data as $selector_str => $declaration) {
  203. // Add the selectors, separating them with commas and line feeds.
  204. $css .= strpos($selector_str, ',') === FALSE ? $selector_str : str_replace(", ", ",\n", $selector_str);
  205. // Add the opening curly brace.
  206. $css .= " {\n";
  207. // Iterate through all the declarations.
  208. foreach ($declaration as $property => $value) {
  209. $css .= " " . $property . ": " . $value . ";\n";
  210. }
  211. // Add the closing curly brace.
  212. $css .= "}\n\n";
  213. }
  214. // Return the output.
  215. return $css;
  216. }
  217. /**
  218. * Compress css data (filter it first!) to optimize for use on view.
  219. *
  220. * @param array $css_data
  221. * An array of css data, as produced by @see ctools_css_disassemble()
  222. * disassembler and the @see ctools_css_filter_css_data() filter.
  223. *
  224. * @return string
  225. * css optimized for use.
  226. */
  227. function ctools_css_compress($css_data) {
  228. // Initialize the output.
  229. $css = '';
  230. // Iterate through all the statements.
  231. foreach ($css_data as $selector_str => $declaration) {
  232. if (empty($declaration)) {
  233. // Skip this statement if filtering removed all parts of the declaration.
  234. continue;
  235. }
  236. // Add the selectors, separating them with commas.
  237. $css .= $selector_str;
  238. // And, the opening curly brace.
  239. $css .= "{";
  240. // Iterate through all the statement properties.
  241. foreach ($declaration as $property => $value) {
  242. $css .= $property . ':' . $value . ';';
  243. }
  244. // Add the closing curly brace.
  245. $css .= "}";
  246. }
  247. // Return the output.
  248. return $css;
  249. }
  250. /**
  251. * Disassemble the css string.
  252. *
  253. * Strip the css of irrelevant characters, invalid/malformed selectors and
  254. * declarations, and otherwise prepare it for processing.
  255. *
  256. * @param string $css
  257. * A string containing the css to be disassembled.
  258. *
  259. * @return array
  260. * An array of disassembled, slightly cleaned-up/formatted css statements.
  261. */
  262. function ctools_css_disassemble($css) {
  263. $disassembled_css = array();
  264. // Remove comments.
  265. $css = preg_replace("/\/\*(.*)?\*\//Usi", "", $css);
  266. // Split out each statement. Match either a right curly brace or a semi-colon
  267. // that precedes a left curly brace with no right curly brace separating them.
  268. $statements = preg_split('/}|;(?=[^}]*{)/', $css);
  269. // If we have any statements, parse them.
  270. if (!empty($statements)) {
  271. // Iterate through all of the statements.
  272. foreach ($statements as $statement) {
  273. // Get the selector(s) and declaration.
  274. if (empty($statement) || !strpos($statement, '{')) {
  275. continue;
  276. }
  277. list($selector_str, $declaration) = explode('{', $statement);
  278. // If the selector exists, then disassemble it, check it, and regenerate
  279. // the selector string.
  280. $selector_str = empty($selector_str) ? FALSE : _ctools_css_disassemble_selector($selector_str);
  281. if (empty($selector_str)) {
  282. // No valid selectors. Bomb out and start the next item.
  283. continue;
  284. }
  285. // Disassemble the declaration, check it and tuck it into an array.
  286. if (!isset($disassembled_css[$selector_str])) {
  287. $disassembled_css[$selector_str] = array();
  288. }
  289. $disassembled_css[$selector_str] += _ctools_css_disassemble_declaration($declaration);
  290. }
  291. }
  292. return $disassembled_css;
  293. }
  294. function _ctools_css_disassemble_selector($selector_str) {
  295. // Get all selectors individually.
  296. $selectors = explode(",", trim($selector_str));
  297. // Iterate through all the selectors, sanity check them and return if they
  298. // pass. Note that this handles 0, 1, or more valid selectors gracefully.
  299. foreach ($selectors as $key => $selector) {
  300. // Replace un-needed characters and do a little cleanup.
  301. $selector = preg_replace("/[\n|\t|\\|\s]+/", ' ', trim($selector));
  302. // Make sure this is still a real selector after cleanup.
  303. if (!empty($selector)) {
  304. $selectors[$key] = $selector;
  305. }
  306. else {
  307. // Selector is no good, so we scrap it.
  308. unset($selectors[$key]);
  309. }
  310. }
  311. // Check for malformed selectors; if found, we skip this declaration.
  312. if (empty($selectors)) {
  313. return FALSE;
  314. }
  315. return implode(', ', $selectors);
  316. }
  317. function _ctools_css_disassemble_declaration($declaration) {
  318. $formatted_statement = array();
  319. $propval_pairs = explode(";", $declaration);
  320. // Make sure we actually have some properties to work with.
  321. if (!empty($propval_pairs)) {
  322. // Iterate through the remains and parse them.
  323. foreach ($propval_pairs as $key => $propval_pair) {
  324. // Check that we have a ':', otherwise it's an invalid pair.
  325. if (strpos($propval_pair, ':') === FALSE) {
  326. continue;
  327. }
  328. // Clean up the current property-value pair.
  329. $propval_pair = preg_replace("/[\n|\t|\\|\s]+/", ' ', trim($propval_pair));
  330. // Explode the remaining fragements some more, but clean them up first.
  331. list($property, $value) = explode(':', $propval_pair, 2);
  332. // If the property survived, toss it onto the stack.
  333. if (!empty($property)) {
  334. $formatted_statement[trim($property)] = trim($value);
  335. }
  336. }
  337. }
  338. return $formatted_statement;
  339. }
  340. /**
  341. * Run disassembled $css through the filter.
  342. *
  343. * @param $css
  344. * CSS code disassembled by ctools_dss_disassemble().
  345. * @param $allowed_properties
  346. * A list of properties that are allowed by the filter. If empty
  347. * ctools_css_filter_default_allowed_properties() will provide the
  348. * list.
  349. * @param $allowed_values
  350. * A list of values that are allowed by the filter. If empty
  351. * ctools_css_filter_default_allowed_values() will provide the
  352. * list.
  353. *
  354. * @return
  355. * An array of disassembled, filtered CSS.
  356. */
  357. function ctools_css_filter_css_data($css, $allowed_properties = array(), $allowed_values = array(), $allowed_values_regex = '', $disallowed_values_regex = '') {
  358. // Retrieve the default list of allowed properties if none is provided.
  359. $allowed_properties = !empty($allowed_properties) ? $allowed_properties : ctools_css_filter_default_allowed_properties();
  360. // Retrieve the default list of allowed values if none is provided.
  361. $allowed_values = !empty($allowed_values) ? $allowed_values : ctools_css_filter_default_allowed_values();
  362. // Define allowed values regex if none is provided.
  363. $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|%|,|\))?)/';
  364. // Define disallowed url() value contents, if none is provided.
  365. $disallowed_values_regex = !empty($disallowed_values_regex) ? $disallowed_values_regex : '/(url|expression)/';
  366. foreach ($css as $selector_str => $declaration) {
  367. foreach ($declaration as $property => $value) {
  368. if (!in_array($property, $allowed_properties)) {
  369. // $filtered['properties'][$selector_str][$property] = $value;.
  370. unset($css[$selector_str][$property]);
  371. continue;
  372. }
  373. $value = str_replace('!important', '', $value);
  374. if (preg_match($disallowed_values_regex, $value) || !(in_array($value, $allowed_values) || preg_match($allowed_values_regex, $value))) {
  375. // $filtered['values'][$selector_str][$property] = $value;.
  376. unset($css[$selector_str][$property]);
  377. continue;
  378. }
  379. }
  380. }
  381. return $css;
  382. }
  383. /**
  384. * Provide a deafult list of allowed properties by the filter.
  385. */
  386. function ctools_css_filter_default_allowed_properties() {
  387. return array(
  388. 'azimuth',
  389. 'background',
  390. 'background-color',
  391. 'background-image',
  392. 'background-repeat',
  393. 'background-attachment',
  394. 'background-position',
  395. 'border',
  396. 'border-top-width',
  397. 'border-right-width',
  398. 'border-bottom-width',
  399. 'border-left-width',
  400. 'border-width',
  401. 'border-top-color',
  402. 'border-right-color',
  403. 'border-bottom-color',
  404. 'border-left-color',
  405. 'border-color',
  406. 'border-top-style',
  407. 'border-right-style',
  408. 'border-bottom-style',
  409. 'border-left-style',
  410. 'border-style',
  411. 'border-top',
  412. 'border-right',
  413. 'border-bottom',
  414. 'border-left',
  415. 'clear',
  416. 'color',
  417. 'cursor',
  418. 'direction',
  419. 'display',
  420. 'elevation',
  421. 'float',
  422. 'font',
  423. 'font-family',
  424. 'font-size',
  425. 'font-style',
  426. 'font-variant',
  427. 'font-weight',
  428. 'height',
  429. 'letter-spacing',
  430. 'line-height',
  431. 'margin',
  432. 'margin-top',
  433. 'margin-right',
  434. 'margin-bottom',
  435. 'margin-left',
  436. 'overflow',
  437. 'padding',
  438. 'padding-top',
  439. 'padding-right',
  440. 'padding-bottom',
  441. 'padding-left',
  442. 'pause',
  443. 'pause-after',
  444. 'pause-before',
  445. 'pitch',
  446. 'pitch-range',
  447. 'richness',
  448. 'speak',
  449. 'speak-header',
  450. 'speak-numeral',
  451. 'speak-punctuation',
  452. 'speech-rate',
  453. 'stress',
  454. 'text-align',
  455. 'text-decoration',
  456. 'text-indent',
  457. 'text-transform',
  458. 'unicode-bidi',
  459. 'vertical-align',
  460. 'voice-family',
  461. 'volume',
  462. 'white-space',
  463. 'width',
  464. 'fill',
  465. 'fill-opacity',
  466. 'fill-rule',
  467. 'stroke',
  468. 'stroke-width',
  469. 'stroke-linecap',
  470. 'stroke-linejoin',
  471. 'stroke-opacity',
  472. );
  473. }
  474. /**
  475. * Provide a default list of allowed values by the filter.
  476. */
  477. function ctools_css_filter_default_allowed_values() {
  478. return array(
  479. 'auto',
  480. 'aqua',
  481. 'black',
  482. 'block',
  483. 'blue',
  484. 'bold',
  485. 'both',
  486. 'bottom',
  487. 'brown',
  488. 'capitalize',
  489. 'center',
  490. 'collapse',
  491. 'dashed',
  492. 'dotted',
  493. 'fuchsia',
  494. 'gray',
  495. 'green',
  496. 'italic',
  497. 'inherit',
  498. 'left',
  499. 'lime',
  500. 'lowercase',
  501. 'maroon',
  502. 'medium',
  503. 'navy',
  504. 'normal',
  505. 'nowrap',
  506. 'olive',
  507. 'pointer',
  508. 'purple',
  509. 'red',
  510. 'right',
  511. 'solid',
  512. 'silver',
  513. 'teal',
  514. 'top',
  515. 'transparent',
  516. 'underline',
  517. 'uppercase',
  518. 'white',
  519. 'yellow',
  520. );
  521. }
  522. /**
  523. * Delegated implementation of hook_flush_caches()
  524. */
  525. function ctools_css_flush_caches() {
  526. // Remove all generated files.
  527. // @see http://drupal.org/node/573292
  528. // file_unmanaged_delete_recursive('public://render');
  529. $filedir = file_default_scheme() . '://ctools/css';
  530. if (drupal_realpath($filedir) && file_exists($filedir)) {
  531. // We use the @ because it's possible that files created by the webserver
  532. // cannot be deleted while using drush to clear the cache. We don't really
  533. // care that much about that, to be honest, so we use the @ to suppress
  534. // the error message.
  535. @file_unmanaged_delete_recursive($filedir);
  536. }
  537. db_delete('ctools_css_cache')->execute();
  538. }