boost.module

  1. nittany7 modules/contrib/boost/boost.module
  2. cis7 modules/contrib/boost/boost.module

Caches generated output as a static file to be served directly from the webserver.

Functions

Namesort descending Description
boost_block_info Implements hook_block_info().
boost_block_view Implements hook_block_view().
boost_boost_is_cacheable Implements hook_boost_is_cacheable().
boost_boost_menu_router Implements hook_boost_menu_router().
boost_boost_storage_types Implements hook_boost_storage_types().
boost_cookie_handler Logic for the setting and removal of the boost cookie.
boost_cron Implements hook_cron(). Performs periodic actions.
boost_deliver_html_page Capture error conditions.
boost_drupal_goto_alter Implements hook_drupal_goto_alter().
boost_exit Implements hook_exit().
boost_expire_cache Implements hook_expire_cache (from the 'expire' module)
boost_file_get_age Returns the age of a cached file, measured in seconds since it was last updated.
boost_flush_caches Implements hook_flush_caches(). Deletes all static files.
boost_form_submit_handler Always run these functions after a form submit from boost.
boost_get_header_info Gets and parses the header info.
boost_get_normal_cache_dir Returns the relative normal cache dir. cache/normal.
boost_get_storage_types Get the storage types for the boost cache.
boost_htaccess_cache_dir_generate Generate htaccess rules for the cache directory.
boost_htaccess_cache_dir_put Overwrite old htaccess rules with new ones.
boost_init Implements hook_init().
boost_in_cache_dir Verify that the operation is going to operate in the cache dir.
boost_is_cacheable Determines whether a given url can be cached or not by boost.
boost_log Simple function to output log and debug messages
boost_match_header_attributes Given header info, match it to a file extension
boost_menu Implements hook_menu().
boost_mkdir Create a directory.
boost_module_implements Alters module_implements to set a hook to fire at the end.
boost_page_delivery_callback_alter Implements hook_page_delivery_callback_alter().
boost_parse_url parse_url that takes into account the base_path
boost_permission Implements hook_permissions().
boost_print_r Returns a nice html formatted version of print_r
boost_set_cookie Sets a special cookie preventing authenticated users getting served pages from the static page cache.
boost_transform_url Given a URL give back eveything we know
boost_write_file Write to a file. Ensures write is atomic via rename operation.
_boost_get_menu_router Gets menu router contex.
_boost_rmdir Recursive version of rmdir(); use with extreme caution.

Constants

Namesort descending Description
BOOST_ADD_DEFAULT_CHARSET Default setting for forcing all content to be the charset defined below.
BOOST_APACHE_ETAG Default etag settings.
BOOST_APACHE_XHEADER Default header setttings.
BOOST_CACHEABILITY_PAGES Default cacheablily setting.
BOOST_CHAR Default value for the character replacement of ? in the URL.
BOOST_CHARSET_TYPE Default for content charset.
BOOST_COOKIE Default cookie name.
BOOST_EXPIRE_CRON Default value for ignoring cron cache flush requests.
BOOST_IGNORE_FLUSH Default value for ignoring cron cache flush requests.
BOOST_MESSAGE_DEBUG Default value for sending out debugging info via a message.
BOOST_NORMAL_DIR Default value for the normal cache dir.
BOOST_ROOT_CACHE_DIR Default value for the root cache dir.
BOOST_VISIBILITY_LISTED Shows this block on only the listed pages.
BOOST_VISIBILITY_NOTLISTED Shows this block on every page except the listed pages. (do not depend on block.module, see #1612448)
BOOST_VISIBILITY_PHP Shows this block if the associated PHP code returns TRUE.

File

modules/contrib/boost/boost.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Caches generated output as a static file to be served directly from the
  5. * webserver.
  6. */
  7. /**
  8. * Default cacheablily setting.
  9. */
  10. define('BOOST_CACHEABILITY_PAGES', '');
  11. /**
  12. * Default cookie name.
  13. */
  14. define('BOOST_COOKIE', 'DRUPAL_UID');
  15. /**
  16. * Default value for sending out debugging info via a message.
  17. */
  18. define('BOOST_MESSAGE_DEBUG', FALSE);
  19. /**
  20. * Default value for the root cache dir.
  21. */
  22. define('BOOST_ROOT_CACHE_DIR', 'cache');
  23. /**
  24. * Default value for the normal cache dir.
  25. */
  26. define('BOOST_NORMAL_DIR', 'normal');
  27. /**
  28. * Default value for the character replacement of ? in the URL.
  29. */
  30. define('BOOST_CHAR', '_');
  31. /**
  32. * Default value for ignoring cron cache flush requests.
  33. */
  34. define('BOOST_IGNORE_FLUSH', TRUE);
  35. /**
  36. * Default value for ignoring cron cache flush requests.
  37. */
  38. define('BOOST_EXPIRE_CRON', TRUE);
  39. /**
  40. * Default etag settings.
  41. */
  42. define('BOOST_APACHE_ETAG', 3);
  43. /**
  44. * Default header setttings.
  45. */
  46. define('BOOST_APACHE_XHEADER', 1);
  47. /**
  48. * Default setting for forcing all content to be the charset defined below.
  49. */
  50. define('BOOST_ADD_DEFAULT_CHARSET', TRUE);
  51. /**
  52. * Default for content charset.
  53. */
  54. define('BOOST_CHARSET_TYPE', 'utf-8');
  55. /**
  56. * Shows this block on every page except the listed pages.
  57. * (do not depend on block.module, see #1612448)
  58. */
  59. define('BOOST_VISIBILITY_NOTLISTED', 0);
  60. /**
  61. * Shows this block on only the listed pages.
  62. */
  63. define('BOOST_VISIBILITY_LISTED', 1);
  64. /**
  65. * Shows this block if the associated PHP code returns TRUE.
  66. */
  67. define('BOOST_VISIBILITY_PHP', 2);
  68. /**
  69. * Implements hook_menu().
  70. */
  71. function boost_menu() {
  72. $items = array();
  73. $path = drupal_get_path('module', 'boost');
  74. $items['admin/config/system/boost'] = array(
  75. 'title' => 'Boost',
  76. 'description' => 'Configuration for Boost.',
  77. 'page callback' => 'drupal_get_form',
  78. 'page arguments' => array('boost_admin_settings'),
  79. 'access arguments' => array('administer site configuration'),
  80. 'type' => MENU_NORMAL_ITEM,
  81. 'file' => 'boost.admin.inc',
  82. 'file path' => $path,
  83. );
  84. $items['admin/config/system/boost/default'] = array(
  85. 'title' => 'Boost Settings',
  86. 'type' => MENU_DEFAULT_LOCAL_TASK,
  87. );
  88. $items['admin/config/system/boost/debug'] = array(
  89. 'title' => 'Debug',
  90. 'description' => 'Debug configuration for Boost.',
  91. 'page callback' => 'drupal_get_form',
  92. 'page arguments' => array('boost_admin_debug_settings'),
  93. 'access arguments' => array('administer site configuration'),
  94. 'type' => MENU_LOCAL_TASK,
  95. 'file' => 'boost.admin.debug.inc',
  96. 'file path' => $path,
  97. );
  98. $items['admin/config/system/boost/filesystem'] = array(
  99. 'title' => 'File System',
  100. 'description' => 'File system configuration for Boost.',
  101. 'page callback' => 'drupal_get_form',
  102. 'page arguments' => array('boost_admin_filesystem_settings'),
  103. 'access arguments' => array('administer site configuration'),
  104. 'type' => MENU_LOCAL_TASK,
  105. 'file' => 'boost.admin.filesystem.inc',
  106. 'file path' => $path,
  107. );
  108. $items['admin/config/system/boost/htaccess'] = array(
  109. 'title' => '.htaccess',
  110. 'description' => '.htaccess configuration for Boost.',
  111. 'page callback' => 'drupal_get_form',
  112. 'page arguments' => array('boost_admin_htaccess_settings'),
  113. 'access arguments' => array('administer site configuration'),
  114. 'type' => MENU_LOCAL_TASK,
  115. 'file' => 'boost.admin.htaccess.inc',
  116. 'file path' => $path,
  117. );
  118. $items['admin/config/system/boost/htaccess/default'] = array(
  119. 'title' => '.htaccess Settings',
  120. 'type' => MENU_DEFAULT_LOCAL_TASK,
  121. );
  122. $items['admin/config/system/boost/htaccess/generator'] = array(
  123. 'title' => '.htaccess Generation',
  124. 'description' => '.htaccess generation for Boost.',
  125. 'page callback' => 'drupal_get_form',
  126. 'page arguments' => array('boost_admin_htaccess_generation'),
  127. 'access arguments' => array('administer site configuration'),
  128. 'type' => MENU_LOCAL_TASK,
  129. 'file' => 'boost.admin.htaccess.inc',
  130. 'file path' => $path,
  131. );
  132. $items['admin/config/system/boost/expiration'] = array(
  133. 'title' => 'Cache Expiration',
  134. 'description' => 'Cache expiration configuration for Boost.',
  135. 'page callback' => 'drupal_get_form',
  136. 'page arguments' => array('boost_admin_expiration_settings'),
  137. 'access arguments' => array('administer site configuration'),
  138. 'type' => MENU_LOCAL_TASK,
  139. 'file' => 'boost.admin.expiration.inc',
  140. 'file path' => $path,
  141. );
  142. return $items;
  143. }
  144. /**
  145. * Implements hook_permissions().
  146. */
  147. function boost_permission() {
  148. return array(
  149. 'boost flush pages' => array(
  150. 'title' => t('Flush pages from Boost cache'),
  151. 'description' => t('Allow users to flush individual pages from the Boost cache using the Boost status block.'),
  152. ),
  153. );
  154. }
  155. /**
  156. * Implements hook_block_info().
  157. */
  158. function boost_block_info() {
  159. $blocks['status'] = array(
  160. 'info' => t('Boost: Pages cache status'),
  161. 'cache' => DRUPAL_NO_CACHE,
  162. );
  163. return $blocks;
  164. }
  165. /**
  166. * Implements hook_block_view().
  167. */
  168. function boost_block_view($delta = '') {
  169. $block = array();
  170. switch ($delta) {
  171. case 'status':
  172. module_load_include('inc', 'boost', 'boost.blocks');
  173. return boost_block_view_status();
  174. }
  175. return $block;
  176. }
  177. /**
  178. * Implements hook_init().
  179. *
  180. * Performs page setup tasks.
  181. */
  182. function boost_init() {
  183. global $_boost;
  184. $_boost = array();
  185. // Make sure the page is/should be cached according to our current configuration.
  186. // Start with the quick checks
  187. if ( strpos($_SERVER['SCRIPT_FILENAME'], 'index.php') === FALSE
  188. || $_SERVER['SERVER_SOFTWARE'] === 'PHP CLI'
  189. || ($_SERVER['REQUEST_METHOD'] != 'GET' && $_SERVER['REQUEST_METHOD'] != 'HEAD')
  190. || isset($_GET['nocache'])
  191. || variable_get('maintenance_mode', 0)
  192. || defined('MAINTENANCE_MODE')
  193. || !empty($_SESSION['messages']) // do not cache pages with messages
  194. ) {
  195. $_boost['cache_this'] = FALSE;
  196. }
  197. else {
  198. // More advanced checks
  199. $_boost = boost_transform_url();
  200. if (empty($_boost['menu_item']['status']) || $_boost['menu_item']['status'] != 200) {
  201. $_boost['cache_this'] = FALSE;
  202. }
  203. }
  204. // Give modules a chance to alter the cookie handler callback used.
  205. // hook_boost_cookie_handler_callback_alter
  206. $cookie_handler_callback = 'boost_cookie_handler';
  207. drupal_alter('boost_cookie_handler_callback', $cookie_handler_callback);
  208. if (function_exists($cookie_handler_callback)) {
  209. $cookie_handler_callback();
  210. }
  211. }
  212. /**
  213. * Implements hook_drupal_goto_alter().
  214. */
  215. function boost_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  216. global $_boost;
  217. // Bypass caching on redirects (issue #1176534).
  218. $_boost['is_cacheable'] = FALSE;
  219. }
  220. /**
  221. * Implements hook_exit().
  222. */
  223. function boost_exit($destination = NULL) {
  224. global $_boost;
  225. // Bail out of caching.
  226. if (!isset($_boost['cache_this'])) {
  227. if (!isset($_boost['is_cacheable'])) {
  228. return;
  229. }
  230. elseif (!$_boost['is_cacheable']) {
  231. return;
  232. }
  233. }
  234. if (isset($_boost['cache_this']) && $_boost['cache_this'] == FALSE) {
  235. return;
  236. }
  237. elseif (!isset($_boost['is_cacheable']) || !$_boost['is_cacheable']) {
  238. return;
  239. }
  240. elseif ($_boost['menu_item']['status'] != 200) {
  241. return;
  242. }
  243. elseif (!drupal_page_is_cacheable()) {
  244. $_boost['is_cacheable'] = FALSE;
  245. return;
  246. }
  247. // Get the data to cache.
  248. $data = ob_get_contents();
  249. // Get header info.
  250. $_boost['header_info'] = boost_get_header_info();
  251. $_boost['matched_header_info'] = boost_match_header_attributes($_boost['header_info']);
  252. if ($_boost['matched_header_info']['enabled'] === FALSE) {
  253. return;
  254. }
  255. // Add note to bottom of content if possible.
  256. if ($_boost['matched_header_info']['comment_start'] && $_boost['matched_header_info']['comment_end']) {
  257. $expire = $_boost['matched_header_info']['lifetime_max'];
  258. $cached_at = date('Y-m-d H:i:s', REQUEST_TIME);
  259. $expires_at = date('Y-m-d H:i:s', REQUEST_TIME + $expire);
  260. $note = "\n" . $_boost['matched_header_info']['comment_start'] . 'Page cached by Boost @ ' . $cached_at . ', expires @ ' . $expires_at . ', lifetime ' . format_interval($expire) . $_boost['matched_header_info']['comment_end'];
  261. $data .= $note;
  262. }
  263. // Write data to a file.
  264. if ($_boost['filename']) {
  265. // Attach extension to filename.
  266. $_boost['filename'] .= '.' . $_boost['matched_header_info']['extension'];
  267. // Write to file.
  268. boost_write_file($_boost['filename'], $data);
  269. }
  270. }
  271. /**
  272. * Implements hook_cron(). Performs periodic actions.
  273. */
  274. function boost_cron() {
  275. // Remove expired files from the cache.
  276. global $_boost;
  277. // This was not invoked in hook_init because of the quick check to
  278. // avoid caching requests from the CLI
  279. $_boost = boost_transform_url();
  280. if (isset($_boost['base_dir']) && variable_get('boost_expire_cron', BOOST_EXPIRE_CRON)) {
  281. $count = _boost_rmdir($_boost['base_dir'], FALSE);
  282. watchdog('boost', 'Expired %count stale files from static page cache.', array('%count' => $count), WATCHDOG_NOTICE);
  283. }
  284. }
  285. /**
  286. * Implements hook_flush_caches(). Deletes all static files.
  287. */
  288. function boost_flush_caches() {
  289. // Remove all files from the cache
  290. global $_boost;
  291. // This may not have been invoked in hook_init because of the quick
  292. // check to avoid caching requests from the CLI
  293. $_boost = boost_transform_url();
  294. // The lock_may_be_available() checks to see if the flush was requested by
  295. // the core cron, since we may want to ignore it (boost_ignore_flush)
  296. if (isset($_boost['base_dir']) && (lock_may_be_available('cron') || variable_get('boost_ignore_flush', BOOST_IGNORE_FLUSH) == FALSE)) {
  297. $count = _boost_rmdir($_boost['base_dir'], TRUE);
  298. watchdog('boost', 'Flushed all files (%count) from static page cache.', array('%count' => $count), WATCHDOG_NOTICE);
  299. }
  300. return;
  301. }
  302. /**
  303. * Implements hook_expire_cache (from the 'expire' module)
  304. */
  305. function boost_expire_cache($urls) {
  306. global $base_root;
  307. foreach ($urls as $url) {
  308. // Check if the URL to be flushed matches our base URL
  309. if (strpos($base_root, $url) == 0) {
  310. $boost = boost_transform_url($url);
  311. // We need the extention for the filename
  312. $boost['header_info'] = boost_get_header_info();
  313. $boost['matched_header_info'] = boost_match_header_attributes($boost['header_info']);
  314. $filename = (isset($boost['filename']) ? $boost['filename'] . '.' . $boost['matched_header_info']['extension'] : NULL);
  315. if ($filename && file_exists($filename)) {
  316. if (unlink($filename)) {
  317. boost_log('Removed !file from the boost cache.', array('!file' => $filename), WATCHDOG_DEBUG);
  318. }
  319. else {
  320. boost_log('Could not delete !file from the boost cache. Check file permissions.', array('!file' => $filename), WATCHDOG_WARNING);
  321. }
  322. }
  323. else {
  324. boost_log('Could not delete the cache for !url, file !file does not exist.', array('!url' => $url, '!file' => $filename), WATCHDOG_DEBUG);
  325. }
  326. }
  327. }
  328. }
  329. /**
  330. * Implements hook_page_delivery_callback_alter().
  331. */
  332. function boost_page_delivery_callback_alter(&$callback, $set = FALSE) {
  333. if ($callback == 'drupal_deliver_html_page') {
  334. $callback = 'boost_deliver_html_page';
  335. }
  336. }
  337. /**
  338. * Given a URL give back eveything we know
  339. *
  340. * @param $url
  341. * Full URL
  342. * @param $b_path
  343. * Base Path
  344. */
  345. function boost_transform_url($url = NULL, $b_path = NULL) {
  346. global $base_root, $base_path;
  347. $items = &drupal_static(__FUNCTION__);
  348. // Set defaults if none passed in.
  349. if ($url === NULL) {
  350. $url = $base_root . request_uri();
  351. }
  352. if ($b_path == NULL) {
  353. $b_path = $base_path;
  354. }
  355. $hash = $url . ' ' . $b_path;
  356. if (!isset($items[$hash])) {
  357. $parts = boost_parse_url($url, $b_path);
  358. if (!$parts) {
  359. $items[$hash] = array('cache_this' => FALSE);
  360. return $items[$hash];
  361. }
  362. $parts['base_dir'] = boost_get_normal_cache_dir() . '/' . $parts['host'] . $b_path;
  363. $parts['filename'] = $parts['base_dir'] . $parts['full_path'] . variable_get('boost_char', BOOST_CHAR) . $parts['query'];
  364. $parts['directory'] = dirname($parts['filename']);
  365. // Get the internal path (node/8).
  366. if (drupal_is_front_page()) {
  367. $parts['normal_path'] = variable_get('site_frontpage', 'node');
  368. }
  369. else {
  370. $parts['normal_path'] = drupal_get_normal_path($parts['path']);
  371. }
  372. // Get the alias (content/about-us).
  373. $parts['path_alias'] = drupal_get_path_alias($parts['normal_path']);
  374. // Get all args.
  375. $args = arg(NULL, $parts['normal_path']);
  376. // Prevent array warnings.
  377. $args[0] = empty($args[0]) ? '' : $args[0];
  378. $args[1] = empty($args[1]) ? '' : $args[1];
  379. $args[2] = empty($args[2]) ? '' : $args[2];
  380. $parts['args'] = $args;
  381. // Get content type.
  382. if (!empty($parts['normal_path'])) {
  383. $parts = _boost_get_menu_router($parts);
  384. }
  385. // See if url is cacheable.
  386. $parts = boost_is_cacheable($parts);
  387. $items[$hash] = $parts;
  388. }
  389. return $items[$hash];
  390. }
  391. /**
  392. * Returns the relative normal cache dir. cache/normal.
  393. */
  394. function boost_get_normal_cache_dir() {
  395. return variable_get('boost_root_cache_dir', BOOST_ROOT_CACHE_DIR) . '/' . variable_get('boost_normal_dir', BOOST_NORMAL_DIR);
  396. }
  397. /**
  398. * parse_url that takes into account the base_path
  399. *
  400. * @param $url
  401. * Full URL
  402. * @param $b_path
  403. * Base Path
  404. */
  405. function boost_parse_url($url = NULL, $b_path = NULL) {
  406. global $base_root, $base_path;
  407. // Set defaults.
  408. if ($url === NULL) {
  409. $url = $base_root . request_uri();
  410. }
  411. if ($b_path == NULL) {
  412. $b_path = $base_path;
  413. }
  414. // Parse url.
  415. $parts = parse_url($url);
  416. if (empty($parts['host']) || empty($parts['path'])) {
  417. return FALSE;
  418. }
  419. if (!isset($parts['query'])) {
  420. $parts['query'] = '';
  421. }
  422. $parts['path'] = $parts['full_path'] = urldecode(preg_replace('/^' . preg_quote($b_path, '/') .'/i', '', $parts['path']));
  423. $parts['base_path'] = $b_path;
  424. $parts['query_array'] = array();
  425. parse_str($parts['query'], $parts['query_array']);
  426. // Check if language prefix for urls is enabled.
  427. if (drupal_multilingual() && variable_get('locale_language_negotiation_url_part') == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) {
  428. // Get languages grouped by status and select only the enabled ones.
  429. $languages = language_list('enabled');
  430. $languages = $languages[1];
  431. list($language, $parts['path']) = language_url_split_prefix($parts['path'], $languages);
  432. }
  433. // Get page number and info from the query string.
  434. if (!empty($parts['query_array'])) {
  435. $query = array();
  436. foreach ($parts['query_array'] as $key => $val) {
  437. if ($key != 'q' && $key != 'destination' && $key != 'page' && !empty($val)) {
  438. $query[$key] = $val;
  439. }
  440. if ($key == 'page' && is_numeric($val)) {
  441. $parts['page_number'] = $val;
  442. }
  443. }
  444. ksort($query);
  445. $parts['query_extra'] = str_replace('&amp;', '&', urldecode(http_build_query($query)));
  446. }
  447. // Get fully decoded URL.
  448. $decoded1 = urldecode($parts['base_path'] . $parts['path'] . variable_get('boost_char', BOOST_CHAR) . $parts['query']);
  449. $decoded2 = urldecode($decoded1);
  450. while ($decoded1 != $decoded2) {
  451. $decoded1 = urldecode($decoded2);
  452. $decoded2 = urldecode($decoded1);
  453. }
  454. $decoded = $decoded2;
  455. unset($decoded2);
  456. unset($decoded1);
  457. $parts['url_full'] = $parts['host'] . $parts['base_path'] . $parts['path'] . variable_get('boost_char', BOOST_CHAR) . $parts['query'];
  458. $parts['url'] = $url;
  459. $parts['url_decoded'] = $decoded;
  460. return $parts;
  461. }
  462. /**
  463. * Determines whether a given url can be cached or not by boost.
  464. *
  465. * TODO: Add in support for the menu_item
  466. *
  467. * @param $parts
  468. * $parts
  469. * @param $request_type
  470. * May be 'status' to skip some checks in order to show the status
  471. * block on the admin interface (otherwise we will always mention
  472. * that the page is non-cacheable, since user is logged in).
  473. * Please don't rely on this parameter if you are extending boost,
  474. * this is likely to change in the future. Contact us if you use it.
  475. *
  476. * @return $parts
  477. */
  478. function boost_is_cacheable($parts, $request_type = 'normal') {
  479. // Set local variables.
  480. $path = $parts['path'];
  481. $query = $parts['query'];
  482. $full = $parts['url_full'];
  483. $normal_path = $parts['normal_path'];
  484. $alias = $parts['path_alias'];
  485. $decoded = $parts['url_decoded'];
  486. // Never cache
  487. // the user autocomplete/login/registration/password/reset/logout pages
  488. // any admin pages
  489. // comment reply pages
  490. // node add page
  491. // openid login page
  492. // URL variables that contain / or \
  493. // if incoming URL contains '..' or null bytes
  494. // if decoded URL contains :// outside of the host portion of the url
  495. // Limit the maximum directory nesting depth of the path
  496. // Do not cache if destination is set.
  497. if ( $normal_path == 'user'
  498. || preg_match('!^user/(autocomplete|login|register|password|reset|logout)!', $normal_path)
  499. || preg_match('!^admin!', $normal_path)
  500. || preg_match('!^comment/reply!', $normal_path)
  501. || preg_match('!^node/add!', $normal_path)
  502. || preg_match('!^openid/authenticate!', $normal_path)
  503. || strpos($query, '/') !== FALSE
  504. || strpos($query, "\\") !== FALSE
  505. || strpos($full, '..') !== FALSE
  506. || strpos($full, "\0") !== FALSE
  507. || count(explode('/', $path)) > 10
  508. || strpos($decoded, "://") !== FALSE
  509. || !empty($query_array['destination'])
  510. ) {
  511. $parts['is_cacheable'] = FALSE;
  512. $parts['is_cacheable_reason'] = 'Core Drupal dynamic pages';
  513. return $parts;
  514. }
  515. // Check for reserved characters if on windows.
  516. // http://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
  517. // " * : < > |
  518. $chars = '"*:<>|';
  519. if (stristr(PHP_OS, 'WIN') && preg_match("/[" . $chars . "]/", $full)) {
  520. $parts['is_cacheable'] = FALSE;
  521. $parts['is_cacheable_reason'] = 'Reserved characters on MS Windows';
  522. return $parts;
  523. }
  524. // Match the user's cacheability settings against the path.
  525. // See http://api.drupal.org/api/function/block_block_list_alter/7
  526. $visibility = variable_get('boost_cacheability_option', BOOST_VISIBILITY_NOTLISTED);
  527. $pages_setting = variable_get('boost_cacheability_pages', BOOST_CACHEABILITY_PAGES);
  528. if ($pages_setting) {
  529. // Convert path string to lowercase. This allows comparison of the same path
  530. // with different case. Ex: /Page, /page, /PAGE.
  531. $pages = drupal_strtolower($pages_setting);
  532. if ($visibility < BOOST_VISIBILITY_PHP) {
  533. // Convert the alias to lowercase.
  534. $path = drupal_strtolower($alias);
  535. // Compare the lowercase internal and lowercase path alias (if any).
  536. $page_match = drupal_match_path($path, $pages);
  537. if ($path != $normal_path) {
  538. $page_match = $page_match || drupal_match_path($normal_path, $pages);
  539. }
  540. // When 'boost_cacheability_option' has a value of 0 (BOOST_VISIBILITY_NOTLISTED),
  541. // Boost will cache all pages except those listed in 'boost_cacheability_pages'.
  542. // When set to 1 (BOOST_VISIBILITY_LISTED), Boost will only cache those
  543. // pages listed in 'boost_cacheability_pages'.
  544. $page_match = !($visibility xor $page_match);
  545. }
  546. elseif (module_exists('php')) {
  547. $page_match = php_eval($pages_setting);
  548. }
  549. else {
  550. $page_match = FALSE;
  551. }
  552. }
  553. else {
  554. $page_match = TRUE;
  555. }
  556. $parts['is_cacheable'] = $page_match;
  557. if (! $page_match) {
  558. $parts['is_cacheable_reason'] = 'Page excluded from cache by the include/exclude paths defined by site admin.';
  559. }
  560. if (!$parts['is_cacheable']) {
  561. return $parts;
  562. }
  563. // Invoke hook_boost_is_cacheable($path).
  564. $modules = boost_module_implements('boost_is_cacheable', 'boost');
  565. foreach ($modules as $module) {
  566. $result = module_invoke($module, 'boost_is_cacheable', $parts, $request_type);
  567. if ($result['is_cacheable'] === FALSE) {
  568. if (! isset($result['is_cacheable'])) {
  569. $result['is_cacheable_reason'] = 'Page excluded from cache by a third-party module.';
  570. }
  571. return $result;
  572. }
  573. }
  574. return $result;
  575. }
  576. /**
  577. * Implements hook_boost_is_cacheable().
  578. *
  579. * TODO support for node types, etc.
  580. *
  581. * @param $parts
  582. * info about this request
  583. * @param $request_type
  584. * if the request_type is "status", we assume that this is being
  585. * called from the admin status block. Since the user must be
  586. * logged in to view this block, we do not return false.
  587. *
  588. * @return $parts
  589. */
  590. function boost_boost_is_cacheable($parts, $request_type = 'normal') {
  591. global $user;
  592. if ($user->uid != 0 && $request_type != 'status') {
  593. $parts['is_cacheable'] = FALSE;
  594. $parts['is_cacheable_reason'] = 'Boost only works for anonymous users.';
  595. }
  596. else {
  597. $parts['is_cacheable'] = TRUE;
  598. }
  599. return $parts;
  600. }
  601. /**
  602. * Sets a special cookie preventing authenticated users getting served pages
  603. * from the static page cache.
  604. *
  605. * @param $uid
  606. * User ID Number
  607. * @param $expires
  608. * Expiration time
  609. */
  610. function boost_set_cookie($uid, $expires = NULL) {
  611. if (!$expires) {
  612. $expires = ini_get('session.cookie_lifetime');
  613. $expires = (!empty($expires) && is_numeric($expires)) ? REQUEST_TIME + (int)$expires : 0;
  614. setcookie(BOOST_COOKIE, strval($uid), $expires, ini_get('session.cookie_path'), ini_get('session.cookie_domain'), ini_get('session.cookie_secure') == '1');
  615. }
  616. else {
  617. setcookie(BOOST_COOKIE, '0', $expires, ini_get('session.cookie_path'), ini_get('session.cookie_domain'), ini_get('session.cookie_secure') == '1');
  618. }
  619. }
  620. /**
  621. * Logic for the setting and removal of the boost cookie.
  622. */
  623. function boost_cookie_handler() {
  624. global $user;
  625. // Check if Drupal is started from index.php - could cause problems with other
  626. // contrib modules like ad module.
  627. if (strpos($_SERVER['SCRIPT_FILENAME'], 'index.php') === FALSE) {
  628. return;
  629. }
  630. $uid = isset($user->uid) ? $user->uid : 0;
  631. // Remove Boost cookie at logout if it still exists.
  632. if (isset($_COOKIE[BOOST_COOKIE]) && $uid == 0) {
  633. boost_set_cookie($uid, REQUEST_TIME - 86400);
  634. }
  635. // Set Boost cookie if it doesn't exists (or is -1 likely because of a login POST) and user is logged in.
  636. // c.f. Issue #1616356 comment #7
  637. elseif ((!isset($_COOKIE[BOOST_COOKIE]) || $_COOKIE[BOOST_COOKIE] == '-1') && $uid != 0) {
  638. boost_set_cookie($uid);
  639. }
  640. // Remove Boost cookie if set to -1 & Request Method is a GET/HEAD.
  641. elseif (isset($_COOKIE[BOOST_COOKIE]) && $_COOKIE[BOOST_COOKIE] == '-1' && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD')) {
  642. boost_set_cookie($uid, REQUEST_TIME - 86400);
  643. }
  644. // Issue #1242416: Set a nocache cookie on a POST, remove it immediately after
  645. // (on GET) Only necessary for anon users, since we already do not cache for
  646. // logged in users. Also note that if we are processing a GET, it means that
  647. // we have already been through the htaccess rules, so the cookie has done
  648. // its job and can be removed.
  649. if ($uid == 0 && $_SERVER['REQUEST_METHOD'] != 'GET' && $_SERVER['REQUEST_METHOD'] != 'HEAD') {
  650. boost_set_cookie(-1);
  651. }
  652. }
  653. /**
  654. * Gets menu router contex.
  655. *
  656. * Allows for any content type to have it's own cache expiration among
  657. * other things.
  658. *
  659. * @param $parts
  660. *
  661. * @return $parts
  662. *
  663. */
  664. function _boost_get_menu_router($parts) {
  665. // Declare array keys.
  666. $router_item = array();
  667. $router_item['page_type'] = '';
  668. $router_item['page_id'] = '';
  669. // Load the menu item.
  670. $item = menu_get_item($parts['normal_path']);
  671. if (is_array($item)) {
  672. $router_item += $item;
  673. if ($router_item['access']) {
  674. $router_item['status'] = 200;
  675. }
  676. else {
  677. $router_item['status'] = 403;
  678. }
  679. }
  680. else {
  681. $router_item['status'] = 404;
  682. }
  683. // Get any extra arguments.
  684. if (!empty($router_item['path'])) {
  685. $menu_args = arg(NULL, $router_item['path']);
  686. $diff = array();
  687. foreach ($parts['args'] as $key => $value) {
  688. if (!empty($value)) {
  689. if (isset($menu_args[$key])) {
  690. if ($value !== $menu_args[$key] && $menu_args[$key] !== '%') {
  691. $diff[] = $value;
  692. }
  693. }
  694. else {
  695. $diff[] = $value;
  696. }
  697. }
  698. }
  699. }
  700. if (!empty($diff)) {
  701. $router_item['extra_arguments'] = implode('/', $diff);
  702. }
  703. else {
  704. $router_item['extra_arguments'] = '';
  705. }
  706. // Make sure function for menu callback is loaded.
  707. // See menu_execute_active_handler()
  708. if (!empty($router_item['include_file'])) {
  709. require_once DRUPAL_ROOT . '/' . $router_item['include_file'];
  710. }
  711. $parts['menu_item'] = $router_item;
  712. // Invoke hook_boost_menu_router($router_item).
  713. $modules = boost_module_implements('boost_menu_router', 'boost');
  714. foreach ($modules as $module) {
  715. if (($result = module_invoke($module, 'boost_menu_router', $parts)) !== NULL) {
  716. break;
  717. }
  718. }
  719. // Remove extra data from the load function
  720. unset($result['menu_item']['map']);
  721. unset($result['menu_item']['page_arguments']);
  722. return $result;
  723. }
  724. /**
  725. * Implements hook_boost_menu_router().
  726. *
  727. * TODO Better support for arguments.
  728. *
  729. * @param $parts
  730. * info about this request
  731. *
  732. * @return $parts
  733. */
  734. function boost_boost_menu_router($parts) {
  735. // Handle nodes.
  736. if ($parts['args'][0] == 'node' && is_numeric($parts['args'][1])) {
  737. $node = node_load($parts['args'][1]);
  738. $parts['menu_item']['page_callback'] = 'node';
  739. $parts['menu_item']['page_id'] = $parts['args'][1];
  740. if ($node) {
  741. $parts['menu_item']['page_type'] = $node->type;
  742. }
  743. return $parts;
  744. }
  745. // Handle taxonomy.
  746. if ($parts['args'][0] == 'taxonomy' && is_numeric($parts['args'][2])) {
  747. $term = taxonomy_term_load($parts['args'][2]);
  748. $parts['menu_item']['page_callback'] = 'taxonomy';
  749. $parts['menu_item']['page_id'] = $parts['args'][2];
  750. if ($term) {
  751. $vocab = taxonomy_vocabulary_load($term->vid);
  752. $parts['menu_item']['page_type'] = $vocab->name;
  753. }
  754. return $parts;
  755. }
  756. // Handle users.
  757. if ($parts['args'][0] == 'user' && is_numeric($parts['args'][1])) {
  758. $user = user_load($parts['args'][1]);
  759. $parts['menu_item']['page_callback'] = 'user';
  760. $parts['menu_item']['page_id'] = $parts['args'][1];
  761. if ($user !== FALSE) {
  762. $parts['menu_item']['page_type'] = implode(', ', $user->roles);
  763. }
  764. return $parts;
  765. }
  766. // Handle views.
  767. if (isset($parts['menu_item']['page_callback']) && $parts['menu_item']['page_callback'] == 'views_page') {
  768. $page_arguments = $parts['menu_item']['page_arguments'];
  769. // Issue #1364090 : views with access control have serialized page arguments
  770. if (! is_array($page_arguments)) {
  771. $page_arguments = unserialize($page_arguments);
  772. }
  773. $parts['menu_item']['page_callback'] = 'view';
  774. $parts['menu_item']['page_type'] = array_shift($page_arguments);
  775. $parts['menu_item']['page_id'] = array_shift($page_arguments);
  776. // See http://drupal.org/node/651798 for the reason why this if is needed
  777. if (is_array($parts['menu_item']['page_id'])) {
  778. $parts['menu_item']['page_id'] = array_shift($parts['menu_item']['page_id']);
  779. }
  780. return $parts;
  781. }
  782. // Handle panels.
  783. if (isset($parts['menu_item']['page_callback']) && $parts['menu_item']['page_callback'] == 'page_manager_page_execute') {
  784. $page_arguments = $parts['menu_item']['page_arguments'];
  785. // Issue #1653206 : panels with access control have serialized page arguments
  786. if (! is_array($page_arguments)) {
  787. $page_arguments = unserialize($page_arguments);
  788. }
  789. $subtask_id = array_shift($page_arguments);
  790. $page = page_manager_page_load($subtask_id);
  791. $task = page_manager_get_task($page->task);
  792. if ($function = ctools_plugin_get_function($task, 'page callback')) {
  793. $parts['menu_item']['page_callback'] = $function;
  794. }
  795. $parts['menu_item']['page_type'] = $page->task;
  796. $parts['menu_item']['page_id'] = $page->name;
  797. return $parts;
  798. }
  799. // Try to handle everything else.
  800. elseif (isset($parts['menu_item']['page_arguments']) && is_array($parts['menu_item']['page_arguments'])) {
  801. foreach ($parts['menu_item']['page_arguments'] as $string) {
  802. if (is_string($string) && empty($parts['menu_item']['page_type'])) {
  803. $parts['menu_item']['page_type'] = $string;
  804. }
  805. elseif (is_string($string)) {
  806. $parts['menu_item']['page_id'] .= $string;
  807. }
  808. }
  809. }
  810. // If router doesn't hold the the arguments, get them from the URL.
  811. if (empty($parts['menu_item']['page_type'])) {
  812. $parts['menu_item']['page_type'] = $parts['menu_item']['extra_arguments'];
  813. }
  814. elseif (empty($parts['menu_item']['page_id'])) {
  815. $parts['menu_item']['page_id'] = $parts['menu_item']['extra_arguments'];
  816. }
  817. // Try populating with the query string.
  818. if (empty($parts['menu_item']['page_type']) && !empty($parts['query_extra'])) {
  819. $parts['menu_item']['page_type'] = $parts['query_extra'];
  820. }
  821. elseif (empty($parts['menu_item']['page_id']) && !empty($parts['query_extra'])) {
  822. $parts['menu_item']['page_id'] = $parts['query_extra'];
  823. }
  824. return $parts;
  825. }
  826. /**
  827. * Alters module_implements to set a hook to fire at the end.
  828. *
  829. * @param $hook
  830. * Name of hook.
  831. * @param $name
  832. * Module name to shift to the end of the array.
  833. *
  834. * @return array
  835. */
  836. function boost_module_implements($hook, $name) {
  837. $modules = module_implements($hook);
  838. // Make $names built in hook the last one.
  839. $pos = array_search($name, $modules);
  840. if ($pos !== FALSE) {
  841. $temp = $modules[$pos];
  842. unset($modules[$pos]);
  843. $modules[] = $temp;
  844. }
  845. return $modules;
  846. }
  847. /**
  848. * Gets and parses the header info.
  849. *
  850. * @see drupal_send_headers()
  851. *
  852. * @return array
  853. * Contains info about the page that is about to be sent.
  854. */
  855. function boost_get_header_info() {
  856. $headers = drupal_get_http_header();
  857. $status = '200 OK';
  858. $status_number = '200';
  859. $content_type = 'text/html; charset=utf-8';
  860. $content_type_basic = 'text/html';
  861. $charset = 'utf-8';
  862. foreach ($headers as $name_lower => $value) {
  863. if ($name_lower == 'status') {
  864. $status = $value;
  865. }
  866. elseif ($name_lower == 'content-type') {
  867. $content_type = $value;
  868. }
  869. }
  870. preg_match('!^(\d+)!', $status, $matches);
  871. if (isset($matches[1])) {
  872. $status_number = (int) $matches[1];
  873. }
  874. $content_type_info = explode('; charset=', $content_type);
  875. $content_type_basic = array_shift($content_type_info);
  876. if (!empty($content_type_info)) {
  877. $charset = array_shift($content_type_info);
  878. }
  879. return array(
  880. 'status' => $status,
  881. 'status-number' => $status_number,
  882. 'content-type' => $content_type,
  883. 'content-type-basic' => $content_type_basic,
  884. 'charset' => $charset,
  885. 'headers_sent' => headers_sent(),
  886. );
  887. }
  888. /**
  889. * Given header info, match it to a file extension
  890. *
  891. * @param $header_info
  892. * array contains header info
  893. *
  894. * @return array
  895. */
  896. function boost_match_header_attributes($header_info) {
  897. $type = $header_info['content-type-basic'];
  898. $enabled = variable_get('boost_enabled_' . $type, -1);
  899. if ($enabled === -1) {
  900. boost_get_storage_types();
  901. $enabled = variable_get('boost_enabled_' . $type, -1);
  902. if ($enabled === -1) {
  903. variable_set('boost_enabled_' . $type, FALSE);
  904. $enabled = FALSE;
  905. }
  906. }
  907. if (!$enabled) {
  908. return array('enabled' => FALSE);
  909. }
  910. $keys = array(
  911. 'enabled',
  912. 'extension',
  913. 'lifetime_max',
  914. 'lifetime_min',
  915. 'comment_start',
  916. 'comment_end',
  917. );
  918. $info = array();
  919. foreach ($keys as $key) {
  920. $info[$key] = variable_get('boost_' . $key . '_' . $type, -1);
  921. if ($info[$key] === -1) {
  922. return array('enabled' => FALSE);
  923. }
  924. }
  925. return $info;
  926. }
  927. /**
  928. * Get the storage types for the boost cache.
  929. *
  930. * @return $types
  931. * array('title' => array('content-type' => $values));
  932. */
  933. function boost_get_storage_types() {
  934. $primary_types = array();
  935. $secondary_types = array();
  936. // Force boost to be last in the array
  937. $modules = boost_module_implements('boost_storage_types', 'boost');
  938. // Module with the lightest weight runs last. They will then be able to change
  939. // the defaults and modules that are heavier
  940. $modules = array_reverse($modules);
  941. foreach ($modules as $module) {
  942. // Invoke hook_boost_storage_types()
  943. if (($result = module_invoke($module, 'boost_storage_types')) !== NULL) {
  944. foreach ($result as $key => $values) {
  945. if (!empty($values['variants'])) {
  946. foreach ($values['variants'] as $type) {
  947. $secondary_types[$type] = $values;
  948. unset($secondary_types[$type]['variants']);
  949. }
  950. }
  951. unset($values['variants']);
  952. $primary_types[$key] = $values;
  953. }
  954. }
  955. }
  956. // Merge it all back together
  957. $merged = array_merge($primary_types, $secondary_types);
  958. $types = array();
  959. foreach ($merged as $type => $values) {
  960. if ($values['title']) {
  961. $title = $values['title'];
  962. unset($values['title']);
  963. $types[$title][$type] = $values;
  964. }
  965. }
  966. // Apply what's saved in the database
  967. $keys = array(
  968. 'enabled',
  969. 'extension',
  970. 'gzip',
  971. 'lifetime_max',
  972. 'lifetime_min',
  973. 'comment_start',
  974. 'comment_end',
  975. );
  976. foreach ($types as $title => $content_types) {
  977. foreach ($content_types as $type => $values) {
  978. foreach ($keys as $key) {
  979. $types[$title][$type][$key] = variable_get('boost_' . $key . '_' . $type, $values[$key]);
  980. // Set variable in DB if it has never been set before
  981. if (variable_get('boost_' . $key . '_' . $type, -1) === -1) {
  982. variable_set('boost_' . $key . '_' . $type, $values[$key]);
  983. }
  984. }
  985. }
  986. }
  987. return $types;
  988. }
  989. /**
  990. * Implements hook_boost_storage_types().
  991. *
  992. * @return $types
  993. */
  994. function boost_boost_storage_types() {
  995. $types = array();
  996. $types['text/html'] = array(
  997. 'title' => t('HTML'),
  998. 'description' => t('HTML output, usually a webpage'),
  999. 'extension' => 'html',
  1000. 'enabled' => TRUE,
  1001. 'gzip' => TRUE,
  1002. 'lifetime_max' => 3600,
  1003. 'lifetime_min' => 0,
  1004. 'comment_start' => '<!-- ',
  1005. 'comment_end' => ' -->',
  1006. 'variants' => array(),
  1007. );
  1008. $types['text/xml'] = array(
  1009. 'title' => t('XML'),
  1010. 'description' => t('XML output, usually a feed'),
  1011. 'extension' => 'xml',
  1012. 'enabled' => FALSE,
  1013. 'gzip' => TRUE,
  1014. 'lifetime_max' => 3600,
  1015. 'lifetime_min' => 0,
  1016. 'comment_start' => '<!-- ',
  1017. 'comment_end' => ' -->',
  1018. 'variants' => array(
  1019. 'application/xml',
  1020. 'application/rss',
  1021. 'application/rss+xml',
  1022. ),
  1023. );
  1024. $types['text/javascript'] = array(
  1025. 'title' => t('AJAX/JSON'),
  1026. 'description' => t('JSON output, usually a response to a AJAX request'),
  1027. 'extension' => 'json',
  1028. 'enabled' => FALSE,
  1029. 'gzip' => TRUE,
  1030. 'lifetime_max' => 3600,
  1031. 'lifetime_min' => 0,
  1032. 'comment_start' => '/* ',
  1033. 'comment_end' => ' */',
  1034. 'variants' => array(),
  1035. );
  1036. return $types;
  1037. }
  1038. /**
  1039. * Recursive version of rmdir(); use with extreme caution.
  1040. *
  1041. * Function also checks file age and only removes expired files.
  1042. *
  1043. * @param $dir
  1044. * The top-level directory that will be recursively removed.
  1045. * @param $flush
  1046. * Instead of removing expired cached files, remove all files.
  1047. */
  1048. function _boost_rmdir($dir, $flush = TRUE) {
  1049. static $lifetimes = array();
  1050. static $counter = 0;
  1051. if (is_dir($dir) == FALSE) {
  1052. return FALSE;
  1053. }
  1054. if (!boost_in_cache_dir($dir)) {
  1055. return FALSE;
  1056. }
  1057. // Map extensions to cache lifetimes
  1058. if (empty($lifetimes)) {
  1059. $types = boost_get_storage_types();
  1060. foreach ($types as $title => $content_types) {
  1061. foreach ($content_types as $type => $values) {
  1062. $lifetimes[$values['extension']] = $values['lifetime_max'];
  1063. }
  1064. }
  1065. // Be sure to recreate the htaccess file just in case.
  1066. boost_form_submit_handler();
  1067. }
  1068. $objects = scandir($dir);
  1069. $empty_dir = TRUE;
  1070. foreach ($objects as $object) {
  1071. if ($object == "." || $object == "..") {
  1072. continue;
  1073. }
  1074. if ($object == ".htaccess") {
  1075. $empty_dir = FALSE;
  1076. continue;
  1077. }
  1078. $file = $dir . "/" . $object;
  1079. if (is_dir($file)) {
  1080. _boost_rmdir($file, $flush);
  1081. }
  1082. elseif ($flush) {
  1083. unlink($file);
  1084. $counter++;
  1085. }
  1086. else {
  1087. // Need to handle gzipped files.
  1088. // Nice if it supported multi level cache expiration per content type.
  1089. $ext = substr(strrchr($file, '.'), 1);
  1090. $age = boost_file_get_age($file);
  1091. if (isset($lifetimes[$ext]) && $age > $lifetimes[$ext]) {
  1092. unlink($file);
  1093. $counter++;
  1094. }
  1095. else {
  1096. $empty_dir = FALSE;
  1097. }
  1098. }
  1099. }
  1100. if ($empty_dir && is_dir($dir)) {
  1101. // #1138630 @ error suppression used due to rmdir being a race condition.
  1102. @rmdir($dir);
  1103. }
  1104. return $counter;
  1105. }
  1106. /**
  1107. * Returns the age of a cached file, measured in seconds since it was last
  1108. * updated.
  1109. *
  1110. * @param $filename
  1111. * Name of cached file
  1112. * @return int
  1113. */
  1114. function boost_file_get_age($filename) {
  1115. return REQUEST_TIME - filemtime($filename);
  1116. }
  1117. /**
  1118. * Returns a nice html formatted version of print_r
  1119. *
  1120. * @param $data
  1121. *
  1122. * @return string
  1123. */
  1124. function boost_print_r($data) {
  1125. return str_replace(' ', '&nbsp;&nbsp;&nbsp;&nbsp;', nl2br(htmlentities(print_r($data, TRUE))));
  1126. }
  1127. /**
  1128. * Write to a file. Ensures write is atomic via rename operation.
  1129. *
  1130. * @param $filename
  1131. * relative filename.
  1132. * @param $data
  1133. * data to write to the file.
  1134. */
  1135. function boost_write_file($filename, $data) {
  1136. // Create directory if it doesn't exist.
  1137. $directory = dirname($filename);
  1138. if (!boost_mkdir($directory)) {
  1139. return FALSE;
  1140. }
  1141. // Save data to a temp file.
  1142. // file_unmanaged_save_data does not use rename.
  1143. $tempname = drupal_tempnam($directory, 'boost');
  1144. if (file_put_contents($tempname, $data) === FALSE) {
  1145. watchdog('boost', 'Could not create the file %file on your system', array('%file' => $tempname), WATCHDOG_ERROR);
  1146. @unlink($tempname);
  1147. return FALSE;
  1148. }
  1149. // Move temp file to real filename; windows can not do a rename replace.
  1150. if (@rename($tempname, $filename) === FALSE) {
  1151. $oldname = $tempname. 'old';
  1152. if (@rename($filename, $oldname) !== FALSE) {
  1153. if (@rename($tempname, $filename) === FALSE) {
  1154. watchdog('boost', 'Could not rename the file %file on your system', array('%file' => $filename), WATCHDOG_ERROR);
  1155. @unlink($tempname);
  1156. @rename($oldname, $filename);
  1157. return FALSE;
  1158. }
  1159. else {
  1160. @unlink($oldname);
  1161. }
  1162. }
  1163. }
  1164. // chmod file so webserver can send it out.
  1165. drupal_chmod($filename);
  1166. return TRUE;
  1167. }
  1168. /**
  1169. * Create a directory.
  1170. *
  1171. * @param $directory
  1172. * relative directory.
  1173. */
  1174. function boost_mkdir($directory) {
  1175. global $_boost;
  1176. // Only do something if it's not a dir.
  1177. if (!is_dir($directory)) {
  1178. if (!boost_in_cache_dir($directory)) {
  1179. return FALSE;
  1180. }
  1181. // Try to create the directory.
  1182. $mode = variable_get('file_chmod_directory', 0775);
  1183. if (!mkdir($directory, $mode, TRUE)) {
  1184. watchdog('boost', 'Could not create the directory %dir on your system', array('%dir' => $directory), WATCHDOG_ERROR);
  1185. return FALSE;
  1186. }
  1187. drupal_chmod($directory);
  1188. }
  1189. return TRUE;
  1190. }
  1191. /**
  1192. * Verify that the operation is going to operate in the cache dir.
  1193. *
  1194. * @param $file
  1195. * relative directory or file.
  1196. */
  1197. function boost_in_cache_dir($file) {
  1198. global $_boost;
  1199. $good = TRUE;
  1200. $real_file = realpath($file);
  1201. $cache_dir = variable_get('boost_root_cache_dir', BOOST_ROOT_CACHE_DIR);
  1202. $real_cache_dir = realpath($cache_dir);
  1203. // Only operate in the cache dir.
  1204. // Check the real path.
  1205. if ( strpos($file, $cache_dir) !== 0
  1206. || ($real_file && $real_cache_dir && strpos($real_file, $real_cache_dir) !== 0)
  1207. ) {
  1208. $good = FALSE;
  1209. }
  1210. // Send error to watchdog.
  1211. if (!$good) {
  1212. watchdog('boost', 'An operation outside of the cache directory was attempted on your system. %file or %real_file is outside the cache directory %cache or %real_cache. Debug info below <br> !debug', array(
  1213. '%file' => $file,
  1214. '%real_file' => $real_file,
  1215. '%cache' => $cache_dir,
  1216. '%real_cache' => $real_cache_dir,
  1217. '!debug' => boost_print_r($_boost),
  1218. ),
  1219. WATCHDOG_CRITICAL);
  1220. }
  1221. return $good;
  1222. }
  1223. /**
  1224. * Capture error conditions.
  1225. *
  1226. * @param $page_callback_result
  1227. * The result of a page callback. Can be one of:
  1228. * - NULL: to indicate no content.
  1229. * - An integer menu status constant: to indicate an error condition.
  1230. * - A string of HTML content.
  1231. * - A renderable array of content.
  1232. *
  1233. * @see drupal_deliver_html_page()
  1234. */
  1235. function boost_deliver_html_page($page_callback_result) {
  1236. global $_boost;
  1237. // Menu status constants are integers; page content is a string or array.
  1238. if (is_int($page_callback_result)) {
  1239. // @todo: Break these up into separate functions?
  1240. switch ($page_callback_result) {
  1241. case MENU_NOT_FOUND:
  1242. // 404 page.
  1243. $_boost['menu_item']['status'] = 404;
  1244. break;
  1245. case MENU_ACCESS_DENIED:
  1246. // 403 page.
  1247. $_boost['menu_item']['status'] = 403;
  1248. break;
  1249. case MENU_SITE_OFFLINE:
  1250. // 503 page.
  1251. $_boost['menu_item']['status'] = 503;
  1252. break;
  1253. }
  1254. }
  1255. // Call original function
  1256. drupal_deliver_html_page($page_callback_result);
  1257. // Last possible place to send a watchdog message without a shutdown function.
  1258. if (variable_get('boost_message_debug', BOOST_MESSAGE_DEBUG) && $_boost['args'][0] != 'admin') {
  1259. watchdog('boost', boost_print_r($_boost), array(), WATCHDOG_DEBUG);
  1260. }
  1261. }
  1262. /**
  1263. * Always run these functions after a form submit from boost.
  1264. */
  1265. function boost_form_submit_handler() {
  1266. register_shutdown_function('boost_htaccess_cache_dir_put');
  1267. }
  1268. /**
  1269. * Overwrite old htaccess rules with new ones.
  1270. */
  1271. function boost_htaccess_cache_dir_put() {
  1272. global $_boost, $base_path, $base_root;
  1273. if (empty($_boost['base_dir'])) {
  1274. $url = $base_root . request_uri();
  1275. $parts = parse_url($url);
  1276. $_boost['base_dir'] = boost_get_normal_cache_dir() . '/' . $parts['host'] . $base_path;
  1277. }
  1278. boost_write_file($_boost['base_dir'] . '.htaccess', boost_htaccess_cache_dir_generate());
  1279. }
  1280. /**
  1281. * Generate htaccess rules for the cache directory.
  1282. */
  1283. function boost_htaccess_cache_dir_generate() {
  1284. $char_type = variable_get('boost_charset_type', BOOST_CHARSET_TYPE);
  1285. $etag = variable_get('boost_apache_etag', BOOST_APACHE_ETAG);
  1286. // Go through every storage type getting data needed to build htaccess file.
  1287. $gzip = FALSE;
  1288. $data = array();
  1289. $files = array();
  1290. $types = boost_get_storage_types();
  1291. foreach ($types as $title => $content_types) {
  1292. foreach ($content_types as $type => $values) {
  1293. if ($values['enabled']) {
  1294. $forcetype = '\.' . $values['extension'];
  1295. if ($values['gzip']) {
  1296. $forcetype .= '(\.gz)?$';
  1297. $gzip = TRUE;
  1298. }
  1299. else {
  1300. $forcetype .= '$';
  1301. }
  1302. $files[$values['extension']] = $values['extension'];
  1303. $data[$values['extension']] = array(
  1304. 'type' => $type,
  1305. 'forcetype' => $forcetype,
  1306. );
  1307. }
  1308. }
  1309. }
  1310. if (empty($data) || empty($files)) {
  1311. return FALSE;
  1312. }
  1313. // Add in default charset
  1314. $string = '';
  1315. if (variable_get('boost_add_default_charset', BOOST_ADD_DEFAULT_CHARSET)) {
  1316. $string .= "AddDefaultCharset " . $char_type . "\n";
  1317. }
  1318. // Set FileETag
  1319. if ($etag == 1) {
  1320. $string .= "FileETag None\n";
  1321. }
  1322. elseif ($etag == 2) {
  1323. $string .= "FileETag All\n";
  1324. }
  1325. elseif ($etag == 3) {
  1326. $string .= "FileETag MTime Size\n";
  1327. }
  1328. // Set html expiration time to the past and put in boost header if desired.
  1329. $files = '(' . implode('|' , $files) . ')';
  1330. if ($gzip) {
  1331. $files .= '(\.gz)?';
  1332. }
  1333. $string .= "<FilesMatch \"\.$files$\">\n";
  1334. $string .= " <IfModule mod_expires.c>\n";
  1335. $string .= " ExpiresDefault A5\n";
  1336. $string .= " </IfModule>\n";
  1337. $string .= " <IfModule mod_headers.c>\n";
  1338. $string .= " Header set Expires \"Sun, 19 Nov 1978 05:00:00 GMT\"\n";
  1339. $string .= " Header unset Last-Modified\n";
  1340. $string .= " Header append Vary Accept-Encoding\n";
  1341. $string .= " Header set Cache-Control \"no-store, no-cache, must-revalidate, post-check=0, pre-check=0\"\n";
  1342. if (variable_get('boost_apache_xheader', BOOST_APACHE_XHEADER) > 0) {
  1343. $string .= " Header set X-Cached-By \"Boost\"\n";
  1344. }
  1345. $string .= " </IfModule>\n";
  1346. $string .= "</FilesMatch>\n";
  1347. // Set charset and content encoding.
  1348. $string .= "<IfModule mod_mime.c>\n";
  1349. foreach ($data as $extension => $values) {
  1350. $string .= " AddCharset " . $char_type . " ." . $extension . "\n";
  1351. }
  1352. $string .= $gzip ? " AddEncoding gzip .gz\n" : '';
  1353. $string .= "</IfModule>\n";
  1354. // Fix for versions of apache that do not respect the T='' RewriteRule
  1355. foreach ($data as $extension => $values) {
  1356. $forcetype = $values['forcetype'];
  1357. $type = $values['type'];
  1358. $string .= "<FilesMatch \"$forcetype\">\n";
  1359. $string .= " ForceType " . $type . "\n";
  1360. $string .= "</FilesMatch>\n";
  1361. }
  1362. // Make sure files can not execute in the cache dir.
  1363. $string .= "\n";
  1364. $string .= "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\n";
  1365. $string .= "Options None\n";
  1366. $string .= "Options +FollowSymLinks\n";
  1367. $string .= "\n";
  1368. return $string;
  1369. }
  1370. /**
  1371. * Simple function to output log and debug messages
  1372. */
  1373. function boost_log($message, $variables, $severity = WATCHDOG_NOTICE) {
  1374. // Log debug info only if boost debugging is enabled
  1375. if ($severity == WATCHDOG_DEBUG && ! variable_get('boost_message_debug', BOOST_MESSAGE_DEBUG)) {
  1376. return;
  1377. }
  1378. watchdog('boost', $message, $variables, $severity);
  1379. }