You are here

function live_css_save in Live CSS 7.2

Same name and namespace in other branches
  1. 6.2 live_css.module \live_css_save()
  2. 6 live_css.module \live_css_save()
  3. 7 live_css.module \live_css_save()

Callback to save a file edited live.

1 string reference to 'live_css_save'
live_css_menu in ./live_css.module
Implements hook_menu().

File

./live_css.module, line 280
Allows editing and a live view of all changes in real-time in the browser.

Code

function live_css_save() {
  $href = $_POST['href'];
  $css = $_POST['css'];
  $resetcache = (bool) variable_get('live_css_flush', 1);

  // The URL may contain cache data. In that case, we need to strip them
  // i.e. http://.../css/my_file.css?m1unhm
  $sanitized_url = _live_css_sanitize_css_url($href);

  // File path relative to Drupal installation folder.
  global $base_url;
  $stripped_url = drupal_substr($sanitized_url, drupal_strlen($base_url), drupal_strlen($sanitized_url));
  $relative_file_path = _live_css_document_root() . $stripped_url;
  if (substr($relative_file_path, -4) != '.css' && substr($relative_file_path, -5) != '.less') {
    echo drupal_json_encode(array(
      'result' => 'failure',
      'filename' => $href,
      'msg' => 'Can\'t save to files without a \'less\' or \'css\' extension!',
    ));
    return;
  }
  $filename = array_pop(explode('/', 'asdf/asdf.g'));
  if (file_munge_filename($filename, 'css less') != $filename) {
    echo drupal_json_encode(array(
      'result' => 'failure',
      'filename' => $href,
      'msg' => 'The url used contains a sub-filextension which poses a security threat. Saving not allowed.',
    ));
    return;
  }

  // Save file back.
  $msg = '';
  $fh = fopen($relative_file_path, 'w');
  if ($fh !== FALSE) {
    fwrite($fh, $css);
    fclose($fh);
    $result = 'success';
    if ($resetcache) {
      drupal_clear_css_cache();
      drupal_clear_js_cache();
      _drupal_flush_css_js();
    }
  }
  else {
    $result = 'failure';
    $msg = 'Can\'t open file ' . $relative_file_path . ' from ' . $href . '. Ensure that you have full write access and that the path is correct.';
  }
  echo drupal_json_encode(array(
    'result' => $result,
    'filename' => $href,
    'msg' => $msg,
  ));
}