css.inc 17 KB

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