less.module 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. <?php
  2. /**
  3. * @file
  4. * Handles compiling of .less files.
  5. *
  6. * The theme system allows for nearly all output of the Drupal system to be
  7. * customized by user themes.
  8. */
  9. define('LESS_PERMISSION', 'administer less');
  10. define('LESS_AUTOPREFIXER', 'less_autoprefixer');
  11. define('LESS_DEVEL', 'less_devel');
  12. define('LESS_WATCH', 'less_watch');
  13. define('LESS_SOURCE_MAPS', 'less_source_maps');
  14. define('LESS_DIRECTORY', 'public://less');
  15. require_once dirname(__FILE__) . '/includes/less.libraries.inc';
  16. require_once dirname(__FILE__) . '/includes/less.wysiwyg.inc';
  17. require_once dirname(__FILE__) . '/includes/less.theme.inc';
  18. /**
  19. * Implements hook_hook_info().
  20. */
  21. function less_hook_info() {
  22. $less_hooks = array(
  23. 'engines',
  24. 'variables',
  25. 'paths',
  26. 'functions',
  27. );
  28. $hooks = array();
  29. /**
  30. * We don't have to worry about less_HOOK_SYSTEM_NAME_alter variations here
  31. * as less_HOOK_alter is run immediately before and should include the
  32. * MODULE.less.inc file containing any
  33. * less_HOOK_SYSTEM_NAME_alter() implementations.
  34. */
  35. foreach ($less_hooks as $hook) {
  36. $hooks[] = 'less_' . $hook;
  37. $hooks[] = 'less_' . $hook . '_alter';
  38. }
  39. return array_fill_keys($hooks, array(
  40. 'group' => 'less',
  41. ));
  42. }
  43. /**
  44. * Implements hook_menu().
  45. */
  46. function less_menu() {
  47. $items = array();
  48. $items['admin/config/development/less'] = array(
  49. 'title' => 'LESS',
  50. 'description' => 'Administer LESS settings',
  51. 'page callback' => 'drupal_get_form',
  52. 'page arguments' => array('less_settings_form'),
  53. 'access arguments' => array(LESS_PERMISSION),
  54. 'file' => 'includes/less.admin.inc',
  55. 'type' => MENU_NORMAL_ITEM,
  56. );
  57. $items['admin/config/development/less/settings'] = array(
  58. 'title' => 'LESS Settings',
  59. 'type' => MENU_DEFAULT_LOCAL_TASK,
  60. );
  61. $items['ajax/less/watch'] = array(
  62. 'title' => 'LESS watch callback',
  63. 'type' => MENU_CALLBACK,
  64. 'page callback' => '_less_watch',
  65. 'access callback' => 'variable_get',
  66. 'access arguments' => array(LESS_WATCH, FALSE),
  67. 'delivery callback' => 'drupal_json_output',
  68. 'file' => 'includes/less.watch.inc',
  69. );
  70. return $items;
  71. }
  72. /**
  73. * Implements hook_permission().
  74. */
  75. function less_permission() {
  76. return array(
  77. LESS_PERMISSION => array(
  78. 'title' => t('Administer LESS'),
  79. 'description' => t('Access the LESS settings page and view debug messages.'),
  80. ),
  81. );
  82. }
  83. /**
  84. * Implements hook_element_info_alter().
  85. */
  86. function less_element_info_alter(&$type) {
  87. // Prepend to the list of #pre_render functions so it runs first.
  88. array_unshift($type['styles']['#pre_render'], '_less_pre_render');
  89. if (variable_get(LESS_DEVEL, FALSE)) {
  90. // Must run after drupal_pre_render_styles() to attach any attributes.
  91. array_push($type['styles']['#pre_render'], '_less_attach_src');
  92. }
  93. }
  94. /**
  95. * Add original .less file path as 'src' attribute to <link />.
  96. *
  97. * @param array $styles
  98. * CSS style tags after drupal_pre_render_styles() has run.
  99. *
  100. * @return array
  101. * Styles array with 'src' attributes on LESS files.
  102. *
  103. * @see drupal_pre_render_styles()
  104. */
  105. function _less_attach_src($styles) {
  106. foreach (element_children($styles) as $key) {
  107. // If its a <link />, then most likely its a compiled .less file.
  108. if ($styles[$key]['#tag'] == 'link') {
  109. // Hashes are generated based on the URL without the query portion.
  110. $file_url_parts = drupal_parse_url($styles[$key]['#attributes']['href']);
  111. // If we have a match, it means it is a compiled .less file.
  112. if ($cache = cache_get('less:watch:' . drupal_hash_base64($file_url_parts['path']))) {
  113. // Some inspectors allow 'src' attribute to open from a click.
  114. $styles[$key]['#attributes']['src'] = url($cache->data['less']['input_file']);
  115. }
  116. }
  117. }
  118. return $styles;
  119. }
  120. /**
  121. * Pre-render function for 'style' elements.
  122. *
  123. * Key place where .less files are detected and processed.
  124. *
  125. * @param array $styles
  126. * All 'style' elements that are to display on the page.
  127. *
  128. * @return array
  129. * Modified style elements pointing to compiled LESS output.
  130. */
  131. function _less_pre_render($styles) {
  132. $less_devel = (bool) variable_get(LESS_DEVEL, FALSE);
  133. if ($less_devel) {
  134. if (variable_get(LESS_WATCH, FALSE)) {
  135. drupal_add_js(drupal_get_path('module', 'less') . '/scripts/less.watch.js');
  136. }
  137. // Warn users once every hour that less is checking for file modifications.
  138. if (user_access(LESS_PERMISSION) && flood_is_allowed('less_devel_warning', 1)) {
  139. flood_register_event('less_devel_warning');
  140. $message_vars = array(
  141. '@url' => url('admin/config/development/less'),
  142. );
  143. drupal_set_message(t('LESS files are being checked for modifications on every request. Remember to <a href="@url">turn off</a> this feature on production websites.', $message_vars), 'status');
  144. }
  145. }
  146. $less_items = array_intersect_key($styles['#items'], array_flip(_less_children($styles['#items'])));
  147. if (!empty($less_items)) {
  148. require_once dirname(__FILE__) . '/includes/less.process.inc';
  149. // Attach settings to each item.
  150. array_walk($less_items, '_less_attach_settings');
  151. // Determine output path for each item.
  152. array_walk($less_items, '_less_output_path');
  153. // Check for rebuild each page.
  154. if ($less_devel) {
  155. array_walk($less_items, '_less_check_build');
  156. }
  157. // Compile '.less' files.
  158. array_walk($less_items, '_less_process_file');
  159. // Store cache information.
  160. if ($less_devel) {
  161. array_walk($less_items, '_less_store_cache_info');
  162. }
  163. $styles['#items'] = array_replace($styles['#items'], $less_items);
  164. }
  165. return $styles;
  166. }
  167. /**
  168. * Implements hook_admin_menu_cache_info().
  169. */
  170. function less_admin_menu_cache_info() {
  171. $caches = array();
  172. // Add item to admin_menu's flush caches menu.
  173. $caches['less'] = array(
  174. 'title' => t('LESS compiled files'),
  175. 'callback' => 'less_flush_caches',
  176. );
  177. return $caches;
  178. }
  179. /**
  180. * Implements hook_cron_queue_info().
  181. *
  182. * This hook runs before cache flush during cron. Reliably lets us know if its
  183. * cron or not.
  184. */
  185. function less_cron_queue_info() {
  186. drupal_static('less_cron', TRUE);
  187. }
  188. /**
  189. * Implements hook_flush_caches().
  190. *
  191. * Triggers rebuild of all LESS files during cache flush, except during cron.
  192. */
  193. function less_flush_caches() {
  194. if (!drupal_static('less_cron')) {
  195. // Rebuild the less files directory.
  196. _less_get_dir(TRUE);
  197. cache_clear_all('less:', 'cache', TRUE);
  198. }
  199. less_clear_css_cache();
  200. return array();
  201. }
  202. /**
  203. * Deletes all stale compiled LESS files that are no longer in use.
  204. *
  205. * @see drupal_delete_file_if_stale().
  206. */
  207. function less_clear_css_cache() {
  208. file_scan_directory(LESS_DIRECTORY, '/.+/', array('callback' => 'drupal_delete_file_if_stale'));
  209. }
  210. /**
  211. * Get/(re)generate current 'less_dir' variable.
  212. *
  213. * @param bool $rebuild
  214. * Flag to rebuild compiled output.
  215. *
  216. * @return string
  217. * current 'less_dir' Drupal variable value.
  218. */
  219. function _less_get_dir($rebuild = FALSE) {
  220. $less_dir = variable_get('less_dir');
  221. // If drupal variable 'less_dir' is not set, empty, or manually reset, then
  222. // generate a new unique id and save it.
  223. if ($rebuild || empty($less_dir)) {
  224. // Set the less directory variable.
  225. variable_set('less_dir', drupal_hash_base64(uniqid('', TRUE)));
  226. }
  227. return variable_get('less_dir');
  228. }
  229. /**
  230. * Loads the selected LESS engine, or 'lessphp' for legacy reasons.
  231. *
  232. * @return bool
  233. * TRUE if selected LESS engine is loaded.
  234. */
  235. function _less_inc() {
  236. static $loaded = NULL;
  237. if (!isset($loaded)) {
  238. $less_engine = variable_get('less_engine', 'lessphp');
  239. if (($less_engine_library = libraries_load($less_engine)) && $less_engine_library['installed']) {
  240. $loaded = $less_engine;
  241. }
  242. }
  243. return $loaded;
  244. }
  245. /**
  246. * Keeps track of .less file "ownership".
  247. *
  248. * This keeps track of which modules and themes own which .less files, and any
  249. * variable defaults those system items define.
  250. *
  251. * Only tracks .less files that are added through .info files.
  252. */
  253. function _less_registry() {
  254. $static_stylesheets = &drupal_static('less_stylesheets');
  255. $static_defaults = &drupal_static('less_defaults');
  256. if (!isset($static_stylesheets) || !isset($static_defaults)) {
  257. if (($cache_stylesheets = cache_get('less:stylesheets')) && ($cache_defaults = cache_get('less:defaults'))) {
  258. $static_stylesheets = $cache_stylesheets->data;
  259. $static_defaults = $cache_defaults->data;
  260. }
  261. else {
  262. $system_types = array(
  263. 'module_enabled',
  264. 'theme',
  265. );
  266. foreach ($system_types as $system_type) {
  267. $system_items = system_list($system_type);
  268. foreach ($system_items as $system_item_name => $system_item) {
  269. // Register all globally included .less stylesheets.
  270. if (!empty($system_item->info['stylesheets'])) {
  271. foreach ($system_item->info['stylesheets'] as $stylesheets) {
  272. foreach ($stylesheets as $stylesheet) {
  273. if (_less_is_less_filename($stylesheet)) {
  274. $static_stylesheets[$stylesheet] = $system_item_name;
  275. }
  276. }
  277. }
  278. }
  279. // Process LESS settings from .info files.
  280. if (isset($system_item->info['less']) && is_array($system_item->info['less'])) {
  281. // Register all non-global stylesheets.
  282. if (isset($system_item->info['less']['sheets']) && is_array($system_item->info['less']['sheets'])) {
  283. $system_item_path = drupal_get_path($system_item->type, $system_item->name);
  284. foreach ($system_item->info['less']['sheets'] as $stylesheet) {
  285. $static_stylesheets[$system_item_path . '/' . $stylesheet] = $system_item_name;
  286. }
  287. }
  288. // Register variable defaults.
  289. if (isset($system_item->info['less']['vars']) && is_array($system_item->info['less']['vars'])) {
  290. $static_defaults[$system_item_name] = $system_item->info['less']['vars'];
  291. }
  292. }
  293. // Invoke hook_less_variables(), results should be static.
  294. if (module_exists($system_item_name) && ($module_defaults = module_invoke($system_item_name, 'less_variables'))) {
  295. $static_defaults[$system_item_name] = array_replace((array) $static_defaults[$system_item_name], array_filter($module_defaults));
  296. }
  297. }
  298. }
  299. cache_set('less:stylesheets', $static_stylesheets);
  300. cache_set('less:defaults', $static_defaults);
  301. }
  302. }
  303. }
  304. /**
  305. * Returns .less file "owner".
  306. *
  307. * Returns the owning module/theme for a passed in .less file, or NULL.
  308. * Only can resolve .less files that are added using .info files.
  309. *
  310. * @param string $filepath
  311. * System path to .less file, relative to DRUPAL_ROOT.
  312. *
  313. * @return string|NULL
  314. * System name of .less file "owner" or NULL in case of no known "owner".
  315. */
  316. function _less_file_owner($filepath) {
  317. // Use the advanced drupal_static() pattern, since this is called very often.
  318. static $drupal_static_fast;
  319. if (!isset($drupal_static_fast)) {
  320. $drupal_static_fast['cache'] = &drupal_static('less_stylesheets');
  321. if (!isset($drupal_static_fast['cache'])) {
  322. _less_registry();
  323. }
  324. }
  325. $stylesheets_cache = &$drupal_static_fast['cache'];
  326. return isset($stylesheets_cache[$filepath]) ? $stylesheets_cache[$filepath] : NULL;
  327. }
  328. /**
  329. * Returns the compiled list of variables and functions for a module/theme.
  330. *
  331. * @param string $system_name
  332. * Module/theme system name. NULL is cast to empty string for array indexes.
  333. */
  334. function less_get_settings($system_name = NULL) {
  335. // Use the advanced drupal_static() pattern, since this is called very often.
  336. static $drupal_static_fast;
  337. if (!isset($drupal_static_fast)) {
  338. $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__);
  339. }
  340. $less_settings_static = &$drupal_static_fast['cache'];
  341. if (!isset($less_settings_static[$system_name])) {
  342. global $theme;
  343. $valid_module = !empty($system_name) && module_exists($system_name);
  344. $theme_settings = theme_get_setting('less', $theme);
  345. $defaults_cache = &drupal_static('less_defaults');
  346. if (!isset($defaults_cache)) {
  347. _less_registry();
  348. }
  349. // Defaults.
  350. $data = array(
  351. 'build_cache_id' => _less_get_dir(),
  352. 'variables' => array(),
  353. 'functions' => array(
  354. 'token' => '_less_token_replace',
  355. ),
  356. 'paths' => array(),
  357. LESS_AUTOPREFIXER => (bool) variable_get(LESS_AUTOPREFIXER, FALSE),
  358. LESS_DEVEL => (bool) variable_get(LESS_DEVEL, FALSE),
  359. LESS_SOURCE_MAPS => (bool) variable_get(LESS_SOURCE_MAPS, FALSE),
  360. 'theme' => $theme,
  361. );
  362. /*
  363. * Compile the LESS variables.
  364. */
  365. // Cached default variables from .info files and hook_less_variables().
  366. if (!empty($defaults_cache[$system_name])) {
  367. $data['variables'] = array_replace($data['variables'], array_filter($defaults_cache[$system_name]));
  368. }
  369. // Saved variable values from current theme.
  370. if (!is_null($theme_settings) && !empty($theme_settings[$system_name])) {
  371. $data['variables'] = array_replace($data['variables'], array_filter($theme_settings[$system_name]));
  372. }
  373. // Prevent $system_name from being altered.
  374. $alter_system_name = $system_name;
  375. // Invoke hook_less_variables_alter().
  376. drupal_alter('less_variables', $data['variables'], $alter_system_name);
  377. // Invoke hook_less_variables_SYSTEM_NAME_alter().
  378. drupal_alter('less_variables_' . $system_name, $data['variables']);
  379. /*
  380. * Grab the LESS functions.
  381. *
  382. * LESS functions are not stored in the cache table since they could be
  383. * anonymous functions.
  384. */
  385. if ($valid_module && module_hook($system_name, 'less_functions')) {
  386. $data['functions'] = array_replace($data['functions'], (array) module_invoke($system_name, 'less_functions'));
  387. }
  388. // Prevent $system_name from being altered.
  389. $alter_system_name = $system_name;
  390. // Invoke hook_less_functions_alter().
  391. drupal_alter('less_functions', $data['functions'], $alter_system_name);
  392. // Invoke hook_less_functions_SYSTEM_NAME_alter().
  393. drupal_alter('less_functions_' . $system_name, $data['functions']);
  394. /*
  395. * Grab the LESS include paths.
  396. *
  397. */
  398. if ($valid_module && module_hook($system_name, 'less_paths')) {
  399. $data['paths'] = array_unique(array_merge($data['paths'], (array) module_invoke($system_name, 'less_paths')));
  400. }
  401. // Prevent $system_name from being altered.
  402. $alter_system_name = $system_name;
  403. // Invoke hook_less_paths_alter().
  404. drupal_alter('less_paths', $data['paths'], $alter_system_name);
  405. // Invoke hook_less_paths_SYSTEM_NAME_alter().
  406. drupal_alter('less_paths_' . $system_name, $data['paths']);
  407. $data['paths'] = array_unique($data['paths']);
  408. $less_settings_static[$system_name] = $data;
  409. }
  410. // Don't need to test isset(), there will always be data at $system_name.
  411. return $less_settings_static[$system_name];
  412. }
  413. /**
  414. * Handler for LESS function token().
  415. *
  416. * @param string[] $arg
  417. *
  418. * @return array
  419. */
  420. function _less_token_replace($arg) {
  421. list($type, $delimiter, $value) = $arg;
  422. return array($type, $delimiter, array(token_replace($value[0])));
  423. }
  424. /**
  425. * Helper function that attempts to create a folder if it doesn't exist.
  426. *
  427. * Locks are used to help avoid concurrency collisions.
  428. *
  429. * @param string $directory_path
  430. * Directory of which to create/confirm existence.
  431. *
  432. * @return bool
  433. * Value indicating existence of directory.
  434. */
  435. function _less_ensure_directory($directory_path) {
  436. $is_dir = is_dir($directory_path);
  437. if (!$is_dir) {
  438. $lock_id = 'less_directory_' . md5($directory_path);
  439. // Attempt to create directory only 3 times, else delay is too long.
  440. for ($i = 0; $i < 3; $i++) {
  441. if (lock_acquire($lock_id) && $is_dir = file_prepare_directory($directory_path, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
  442. // Creation was successful, cancel the 'for' loop;
  443. break;
  444. }
  445. lock_wait($lock_id, 1);
  446. }
  447. lock_release($lock_id);
  448. if (!$is_dir) {
  449. // There is a problem with the directory.
  450. $message_vars = array(
  451. '%dir' => $directory_path,
  452. );
  453. watchdog('LESS', 'LESS could not create a directory in %dir', $message_vars, WATCHDOG_ERROR);
  454. if (user_access(LESS_PERMISSION)) {
  455. drupal_set_message(t('LESS could not create a directory in %dir', $message_vars), 'error', FALSE);
  456. }
  457. }
  458. }
  459. return $is_dir;
  460. }
  461. /**
  462. * Return keys from array that match '.less' file extension.
  463. *
  464. * @param array $items
  465. * An array where keys are expected to be filepaths.
  466. *
  467. * @return array
  468. * Array of matching filepaths.
  469. */
  470. function _less_children($items) {
  471. return array_filter(array_keys($items), '_less_is_less_filename');
  472. }
  473. /**
  474. * Check if filename has '.less' extension.
  475. *
  476. * @param string $filename
  477. * File name/path to search for '.less' extension.
  478. *
  479. * @return bool
  480. * TRUE if $filename does end with '.less'.
  481. */
  482. function _less_is_less_filename($filename) {
  483. return drupal_substr($filename, -5) === '.less';
  484. }
  485. /**
  486. * Implements hook_less_engines().
  487. *
  488. * @return string[]
  489. */
  490. function less_less_engines() {
  491. return array(
  492. 'less.php' => 'LessEngineLess_php',
  493. 'lessphp' => 'LessEngineLessphp',
  494. 'less.js' => 'LessEngineLess_js',
  495. );
  496. }
  497. /**
  498. * @return \LessEngineInterface[]
  499. */
  500. function _less_get_engines() {
  501. $registered_engines = module_invoke_all('less_engines');
  502. drupal_alter('less_engines', $registered_engines);
  503. return $registered_engines;
  504. }
  505. /**
  506. * @param $input_file_path
  507. *
  508. * @return \LessEngine
  509. *
  510. * @throws Exception
  511. */
  512. function less_get_engine($input_file_path) {
  513. $engines = _less_get_engines();
  514. $selected_engine = _less_inc();
  515. if (!empty($engines[$selected_engine])) {
  516. $class_name = $engines[$selected_engine];
  517. return new $class_name($input_file_path);
  518. }
  519. else {
  520. throw new Exception('Unable to load LessEngine.');
  521. }
  522. }