public function index($file, $parameters = array()) { $file = Path::assemble(BASE_PATH, $file); if (File::exists($file)) { $fileSize = File::getSize(BASE_PATH . $file); switch ($parameters) { case "file_ext": return File::getExtension($file); break; case "file_size": return File::getSize(BASE_PATH . $file); break; case "file_size_kilobytes": return number_format($fileSize / 1024); break; case "file_size_human": return self::format_bytes_human($fileSize); break; default: return File::getExtension($file); } } else { Log::error("File does not exist or is not readable", "fileinfo_modifier", $file); } }
private function makeFileSelect($selected_file = null) { $html = "<span class='btn btn-file-browse'><span class='ss-icon'>openfolder</span></span>"; $html .= "<p><select name='{$this->fieldname}' style='display:none'>"; $html .= "<option value=''>Select a file...</option>"; $path = Path::assemble(BASE_PATH, array_get($this->field_config, 'destination')); $finder = new Finder(); // Set folder location $finder->in($path); // Limit by depth $finder->depth = array_get($this->field_config, 'depth', '<1'); // Limit by file extension foreach (array_get($this->field_config, array('allowed', 'types'), array()) as $ext) { $finder->name("*.{$ext}"); } // Fetch matches $matches = $finder->files()->followLinks(); // Build HTML options foreach ($matches as $file) { $filename = Path::toAsset($file->getPathname(), false); $display_name = ltrim(str_replace($path, '', $file->getPathname()), '/'); $selected = $selected_file === $filename ? 'selected' : ''; $html .= "<option value='{$filename}' {$selected}>" . $display_name . "</option>"; } $html .= '</select></p>'; return $html; }
/** * render * Finds and chooses the correct template, then renders the page * * @param string $template Template (or array of templates, in order of preference) to render the page with * @return string */ public function render($template) { $html = '<p style="text-align:center; font-size:28px; font-style:italic; padding-top:50px;">No template found.</p>'; $list = $template ? $list = array($template) : self::$_templates; $template_type = 'html'; // Allow setting where to get the template from if (!self::$_template_location) { self::$_template_location = Path::assemble(BASE_PATH, Config::getTemplatesPath(), 'templates'); } foreach ($list as $template) { $template_path = Path::assemble(self::$_template_location, $template); $override_path = Path::assemble(BASE_PATH, Config::getThemesPath(), Config::getTheme(), 'admin', $template); if (File::exists($template_path . '.html') || file_exists($template_path . '.php')) { // set debug information Debug::setValue('template', $template); Debug::setvalue('layout', str_replace('layouts/', '', self::$_layout)); Debug::setValue('statamic_version', STATAMIC_VERSION); Debug::setValue('php_version', phpversion()); Debug::setValue('theme', array_get($this->data, '_theme', null)); Debug::setValue('environment', array_get($this->data, 'environment', '(none)')); $this->data['_debug'] = array('template' => Debug::getValue('template'), 'layout' => Debug::getValue('layout'), 'version' => Debug::getValue('statamic_version'), 'statamic_version' => Debug::getValue('statamic_version'), 'php_version' => Debug::getValue('php_version'), 'theme' => Debug::getValue('theme'), 'environment' => Debug::getValue('environment')); # standard lex-parsed template if (File::exists($template_path . '.html')) { $template_type = 'html'; $this->appendNewData($this->data); // Fetch template and parse any front matter $template = Parse::frontMatter(File::get($template_path . '.html')); self::$_extra_data = $template['data'] + self::$_extra_data; $this->prependNewData(self::$_extra_data); $html = Parse::template($template['content'], Statamic_View::$_dataStore, array($this, 'callback')); break; # lets forge into raw data } elseif (File::exists($override_path . '.php') || File::exists($template_path . '.php')) { $template_type = 'php'; extract($this->data); ob_start(); if (File::exists($override_path . '.php')) { $template_path = $override_path; } require $template_path . ".php"; $html = ob_get_clean(); break; } else { Log::error("Template does not exist: '{$template_path}'", 'core'); } } } // mark milestone for debug panel Debug::markMilestone('template rendered'); // get rendered HTML $rendered = $this->_render_layout($html, $template_type); // mark milestone for debug panel Debug::markMilestone('layout rendered'); // store it into the HTML cache if needed if (Addon::getAPI('html_caching')->isEnabled()) { Addon::getAPI('html_caching')->putCachedPage($rendered); } // return rendered HTML return $rendered; }
private function getServerFiles($config, $destination) { $path = Path::assemble(BASE_PATH, $destination); $finder = new Finder(); // Set folder location $finder->in($path); // Limit by depth $finder->depth('<' . array_get($config, 'depth', '1')); // Limit by file extension foreach (array_get($config, array('allowed', 'types'), array()) as $ext) { $finder->name("/\.{$ext}/i"); } // Fetch matches $matches = $finder->files()->followLinks(); // Build array $files = array(); foreach ($matches as $file) { $filename = Path::trimSubdirectory(Path::toAsset($file->getPathname(), false)); $display_name = ltrim(str_replace($path, '', $file->getPathname()), '/'); $value = (Config::get('prepend_site_root_to_uploads', false)) ? '{{ _site_root }}' . ltrim($filename, '/') : $filename; $files[] = compact('value', 'display_name'); } return $files; }
public function __call($method, $arguments) { $extensions = array(".html", ".md", ".markdown", ".textile"); $html = null; foreach ($extensions as $extension) { $full_src = Path::assemble(BASE_PATH, Config::getCurrentThemePath(), 'partials', ltrim($method . $extension, '/')); if (File::exists($full_src)) { // Merge additional variables passed as parameters Statamic_View::$_dataStore = $arguments + Statamic_View::$_dataStore; if ($this->fetchParam('use_context', false, false, true, false)) { $html = Parse::contextualTemplate(File::get($full_src), Statamic_View::$_dataStore, $this->context, 'Statamic_View::callback'); } else { $html = Parse::template(File::get($full_src), Statamic_View::$_dataStore, 'Statamic_View::callback'); } // parse contents if needed if ($extension == ".md" || $extension == ".markdown") { $html = Parse::markdown($html); } elseif ($extension == ".textile") { $html = Parse::textile($html); } } } if (Config::get('enable_smartypants', TRUE)) { $html = Parse::smartypants($html); } return $html; }
public function index($value, $parameters = array()) { $pi = pathinfo($value); if (Pattern::matches('resized$', $pi['dirname'])) { $dir = preg_replace('/resized$/', '', $pi['dirname']); $value = Path::assemble($dir, $pi['basename']); } return $value; }
/** * Returns a list of templates for this theme * * @param string $theme Optional theme to list from, otherwise, current theme * @return array */ public static function getTemplates($theme = NULL) { $templates = array(); $finder = new Finder(); $files = $finder->files()->in(Path::assemble(BASE_PATH, Config::getThemesPath(), Config::getTheme(), 'templates'))->name('*.html')->followLinks(); if (iterator_count($files) > 0) { foreach ($files as $file) { $templates[] = str_replace('.' . $file->getExtension(), '', $file->getRelativePathname()); } } return $templates; }
public function redactor__fetch_files() { $this->authCheck(); $dir = Path::tidy(ltrim(Request::get('path'), '/') . '/'); $file_list = glob($dir . "*.*", GLOB_BRACE); $files = array(); if (count($file_list) > 0) { foreach ($file_list as $file) { $pi = pathinfo($file); $files[] = array('link' => Path::toAsset($file), 'title' => $pi['filename'], 'name' => $pi['basename'], 'size' => File::getHumanSize(File::getSize(Path::assemble(BASE_PATH, $file)))); } } echo json_encode($files); }
public function file__render_thumbnail() { if (!($path = Request::get('path'))) { exit('No path specified'); } $url = Path::toAsset($this->getTransformedImage($path)); $url = Config::getSiteRoot() !== '/' ? str_replace(Config::getSiteRoot(), '', $url) : $url; $file = Path::assemble(BASE_PATH, $url); header('Content-type: image/jpeg'); header('Content-length: ' . filesize($file)); if ($file = fopen($file, 'rb')) { fpassthru($file); } exit; }
public function partial() { $start = time(); $src = $this->fetchParam('src', null, null, false, false); $extensions = array(".html", ".md", ".markdown", ".textile"); $html = null; // measurement $hash = Debug::markStart('partials', $src, $start); Debug::increment('partials', $src); if ($src) { foreach ($extensions as $extension) { $full_src = Path::assemble(BASE_PATH, $this->theme_root, 'partials', ltrim($src . $extension, '/')); if (File::exists($full_src)) { Statamic_View::$_dataStore = $this->attributes + Statamic_View::$_dataStore; if ($this->fetchParam('use_context', false, false, true, false)) { // to use context, we only want to pass the attributes as // the current data, as those will override into the context // set of data; if we were to include all of ::$_dataStore, // we run into the issue where all of the global-level variables // are overriding variables in context, when the variables in // context are more accurate scope-wise at this point in the parse $html = Parse::contextualTemplate(file_get_contents($full_src), $this->attributes, $this->context, array('statamic_view', 'callback'), true); } else { $html = Parse::template(file_get_contents($full_src), Statamic_View::$_dataStore); } // parse contents if needed if ($extension == ".md" || $extension == ".markdown") { $html = Parse::markdown($html); } elseif ($extension == ".textile") { $html = Parse::textile($html); } } } if (Config::get('enable_smartypants', TRUE)) { $html = Parse::smartypants($html); } } Debug::markEnd($hash); return $html; }
public function deleteFile() { if (!Config::get('allow_file_field_deletions')) { return $this->abortDeletion('file_deleting_not_permitted'); } if (!($path = Request::get('path'))) { return $this->abortDeletion('file_no_path'); } if (!($destination = Request::get('config'))) { return $this->abortDeletion('file_no_config'); } $destination = Path::addStartingSlash(Helper::decrypt(urldecode($destination))); if (!Pattern::startsWith($path, $destination) || strpos($path, '../')) { return $this->abortDeletion('error'); } $full_path = Path::assemble(BASE_PATH, $path); if (!File::exists($full_path)) { return $this->abortDeletion('file_doesnt_exist'); } File::delete($full_path); return array('success' => true, 'message' => Localization::fetch('file_deleted')); }
/** * Finds a given path on the server, adding in any ordering elements missing * * @param string $path Path to resolve * @return string */ public static function resolve($path) { $content_root = Config::getContentRoot(); $content_type = Config::getContentType(); if (strpos($path, "/") === 0) { $parts = explode("/", substr($path, 1)); } else { $parts = explode("/", $path); } $fixedpath = "/"; foreach ($parts as $part) { if (!File::exists(Path::assemble($content_root, $path . '.' . $content_type)) && !is_dir(Path::assemble($content_root, $part))) { // check folders $list = Statamic::get_content_tree($fixedpath, 1, 1, FALSE, TRUE, FALSE); foreach ($list as $item) { $t = basename($item['slug']); if (Slug::isNumeric($t)) { $nl = strlen(Slug::getOrderNumber($t)) + 1; if (strlen($part) >= strlen($item['slug']) - $nl && Pattern::endsWith($item['slug'], $part)) { $part = $item['slug']; break; } } else { if (Pattern::endsWith($item['slug'], $part)) { if (strlen($part) >= strlen($t)) { $part = $item['slug']; break; } } } } // check files $list = Statamic::get_file_list($fixedpath); foreach ($list as $key => $item) { if (Pattern::endsWith($key, $part)) { $t = basename($item); $offset = 0; if (Pattern::startsWith($key, '__')) { $offset = 2; } elseif (Pattern::startsWith($key, '_')) { $offset = 1; } if (Config::getEntryTimestamps() && Slug::isDateTime($t)) { if (strlen($part) >= strlen($key) - 16 - $offset) { $part = $key; break; } } elseif (Slug::isDate($t)) { if (strlen($part) >= strlen($key) - 12 - $offset) { $part = $key; break; } } elseif (Slug::isNumeric($t)) { $nl = strlen(Slug::getOrderNumber($key)) + 1; if (strlen($part) >= strlen($key) - $nl - $offset) { $part = $key; break; } } else { $t = basename($item); if (strlen($part) >= strlen($t) - $offset) { $part = $key; break; } } } } } if ($fixedpath != '/') { $fixedpath .= '/'; } $fixedpath .= $part; } return $fixedpath; }
/** * Load the config (yaml) files in a specified order: * * 1. Loose per-site configs * 2. Routes * 3. Settings * 4. Theme overrides */ public static function loadAllConfigs($admin = false) { $hash = Debug::markStart('config', 'finding'); /* |-------------------------------------------------------------------------- | YAML Mode |-------------------------------------------------------------------------- | | We need to know the YAML mode first (loose, strict, transitional), | so we parse the settings file once to check before doing anything else. | */ $preload_config = YAML::parse(Config::getConfigPath() . '/settings.yaml'); $yaml_mode = array_get($preload_config, '_yaml_mode', 'loose'); /* |-------------------------------------------------------------------------- | Default Settings |-------------------------------------------------------------------------- | | We keep a set of default options that the user config overrides, allowing | us to always have clean defaults. | */ $settings_to_parse = File::get(Config::getAppConfigPath() . '/default.settings.yaml'); /* |-------------------------------------------------------------------------- | User Site Settings |-------------------------------------------------------------------------- | | Next we parse and override the user's settings. | */ $settings_to_parse .= "\n\n" . File::get(Config::getConfigPath() . '/settings.yaml'); /* |-------------------------------------------------------------------------- | Routes and vanity URLs |-------------------------------------------------------------------------- | | Any URL can be manipulated by routes or vanity urls. We need this info | early on, before content parsing begins. | */ $settings_to_parse .= "\n\n_routes:\n " . trim(preg_replace("/\n/", "\n ", File::get(Config::getConfigPath() . '/routes.yaml'))); $settings_to_parse .= "\n\n_vanity_urls:\n " . trim(preg_replace("/\n/", "\n ", File::get(Config::getConfigPath() . '/vanity.yaml'))); /* |-------------------------------------------------------------------------- | Global Variables |-------------------------------------------------------------------------- | | We parse all the yaml files in the root (except settings and routes) of | the config folder and make them available as global template variables. | */ if (Folder::exists($config_files_location = Config::getConfigPath())) { $files = glob($config_files_location . '/*.yaml'); if ($files) { foreach ($files as $file) { if (strpos($file, 'routes.yaml') !== false || strpos($file, 'vanity.yaml') !== false || strpos($file, 'settings.yaml')) { continue; } $settings_to_parse .= "\n\n" . File::get($file); } } } /* |-------------------------------------------------------------------------- | Parse settings up until now |-------------------------------------------------------------------------- | | Parses the concatenated settings string we've made so far. | */ $config = YAML::parse($settings_to_parse, $yaml_mode); /* |-------------------------------------------------------------------------- | Theme Variables |-------------------------------------------------------------------------- | | Theme variables need to specifically parsed later so they can override | any site/global defaults. | */ $themes_path = array_get($config, '_themes_path', '_themes'); $theme_name = array_get($config, '_theme', 'acadia'); // reset $settings_to_parse = ''; if (Folder::exists($theme_files_location = Path::assemble(BASE_PATH, $themes_path, $theme_name))) { $theme_files = glob(Path::tidy($theme_files_location . '/*.yaml')); if ($theme_files) { foreach ($theme_files as $file) { $settings_to_parse .= "\n\n" . File::get($file); } } } Debug::markEnd($hash); // parse theme settings if any if ($settings_to_parse) { $config = YAML::parse($settings_to_parse, $yaml_mode) + $config; } /* |-------------------------------------------------------------------------- | Load Environment Configs and Variables |-------------------------------------------------------------------------- | | Environments settings explicitly overwrite any existing settings, and | therefore must be loaded late. We also set a few helper variables | to make working with environments even easier. | */ _Environment::establish($config); /* |-------------------------------------------------------------------------- | MIME Types |-------------------------------------------------------------------------- */ $config = array('_mimes' => require Config::getAppConfigPath() . '/mimes.php') + $config; /* |-------------------------------------------------------------------------- | Localization |-------------------------------------------------------------------------- | | We load up English by default. We're American after all. Doesn't the | world revolve around us? Hello? Bueller? More hamburgers please. | */ $config['_translations'] = array(); $config['_translations']['en'] = YAML::parse(Config::getAppConfigPath() . '/default.en.yaml'); if ($lang = array_get($config, '_language', false)) { if (File::exists(Config::getTranslation($lang))) { $translation = YAML::parse(Config::getTranslation($lang)); $config['_translations'][$lang] = Helper::arrayCombineRecursive($config['_translations']['en'], $translation); } } $finder = new Finder(); // clear previous Finder interator results try { $translation_files = $finder->files()->in(BASE_PATH . Config::getAddonsPath() . '/*/translations')->name($lang . '.*.yaml')->depth(0)->followLinks(); foreach ($translation_files as $file) { $translation = YAML::parse($file->getRealPath()); $config['_translations'][$lang] = Helper::arrayCombineRecursive($translation, $config['_translations'][$lang]); } } catch (Exception $e) { // meh. not important. } /* |-------------------------------------------------------------------------- | Set Slim Config |-------------------------------------------------------------------------- | | Slim needs to be initialized with a set of config options, so these | need to be set earlier than the set_default_tags() method. | */ // $config['view'] = new Statamic_View(); $config['cookies.lifetime'] = $config['_cookies.lifetime']; if ($admin) { $admin_theme = array_get($config, '_admin_theme', 'ascent'); if (!Folder::exists(BASE_PATH . Path::tidy('/' . $config['_admin_path'] . '/' . 'themes/' . $admin_theme))) { $admin_theme = 'ascent'; } $theme_path = Path::tidy('/' . $config['_admin_path'] . '/' . 'themes/' . $admin_theme . '/'); $config['theme_path'] = $theme_path; $config['templates.path'] = '.' . $theme_path; } else { $public_path = isset($config['_public_path']) ? $config['_public_path'] : ''; $config['theme_path'] = $themes_path . '/' . $config['_theme'] . '/'; $config['templates.path'] = Path::tidy($public_path . $themes_path . '/' . $config['_theme'] . '/'); } if (!array_get($config, '_display_debug_panel', false)) { Debug::disable(); } return $config; }
Hook::run('control_panel', 'delete', null, $file); File::delete($file); } if ($count > 1) { $admin_app->flash('success', Localization::fetch('entries_deleted')); } else { $admin_app->flash('success', Localization::fetch('entry_deleted')); } $url = $admin_app->request()->getReferrer(); $admin_app->redirect($url); })->name('delete_entry')->via('GET', 'POST'); // GET: DELETE PAGE $admin_app->get('/delete/page', function () use($admin_app) { authenticateForRole('admin'); doStatamicVersionCheck($admin_app); $path = Path::assemble(BASE_PATH, Config::getContentRoot(), $admin_app->request()->get('path')); $type = $admin_app->request()->get('type'); if ($type == "folder" && Folder::exists($path)) { Folder::delete($path); $admin_app->flash('success', Localization::fetch('page_deleted')); } else { if (!Pattern::endsWith($path, Config::getContentType())) { $path .= Config::getContentType(); } if (File::exists($path)) { /* |-------------------------------------------------------------------------- | Delete Hook |-------------------------------------------------------------------------- | | Runs the delete hook, passing the file path
/** * _render_layout * Renders the page * * @param string $_html HTML of the template to use * @param string $template_type Content type of the template * @return string */ public function _render_layout($_html, $template_type = 'html') { if (self::$_layout != '') { $this->data['layout_content'] = $_html; $layout_path = Path::assemble(BASE_PATH, Config::getTemplatesPath(), self::$_layout); if ($template_type != 'html' or self::$_control_panel) { extract($this->data); ob_start(); require $layout_path . ".php"; $html = ob_get_clean(); } else { if (!File::exists($layout_path . ".html")) { Log::fatal("Can't find the specified theme.", 'core', 'template'); return '<p style="text-align:center; font-size:28px; font-style:italic; padding-top:50px;">We can\'t find your theme files. Please check your settings.'; } $this->mergeNewData($this->data); $html = Parse::template(File::get($layout_path . ".html"), Statamic_View::$_dataStore, array($this, 'callback')); $html = Lex\Parser::injectNoparse($html); } } else { $html = $_html; } // post-render hook $html = \Hook::run('_render', 'after', 'replace', $html, $html); return $html; }
public function getThemeSettingsPath() { return Path::assemble(BASE_PATH, Config::getThemesPath(), Config::getTheme(), '/theme.yaml'); }
/** * Upload file(s) * * @param string $destination Where the file is going * @param string $id The field took look at in the files array * @return array */ public static function uploadBatch($destination = null, $id = null) { $destination = $destination ?: Request::get('destination'); $id = $id ?: Request::get('id'); $files = self::standardizeFileUploads($_FILES); $results = array(); // Resizing configuration if ($resize = Request::get('resize')) { $width = Request::get('width', null); $height = Request::get('height', null); $ratio = Request::get('ratio', true); $upsize = Request::get('upsize', false); $quality = Request::get('quality', '75'); } // If $files[$id][0] exists, it means there's an array of images. // If there's not, there's just one. We want to change this to an array. if ( ! isset($files[$id][0])) { $tmp = $files[$id]; unset($files[$id]); $files[$id][] = $tmp; } // Process each image foreach ($files[$id] as $file) { // Image data $path = File::upload($file, $destination); $name = basename($path); // Resize if ($resize) { $image = \Intervention\Image\Image::make(Path::assemble(BASE_PATH, $path)); $resize_folder = Path::assemble($image->dirname, 'resized'); if ( ! Folder::exists($resize_folder)) { Folder::make($resize_folder); } $resize_path = Path::assemble($resize_folder, $image->basename); $path = Path::toAsset($resize_path); $name = basename($path); $image->resize($width, $height, $ratio, $upsize)->save($resize_path, $quality); } $results[] = compact('path', 'name'); } return $results; }
public function folderExists() { return Folder::exists(Path::assemble(BASE_PATH, $this->config['destination'])); }
/** * Returns the path for a given $addon relative to the BASE_PATH * * @param string $addon Add-on to use * @return string */ public static function getAddOnPath($addon) { return Path::assemble(self::getAddOnsPath(), $addon); }
public function markAsSpam($file) { $info = new SplFileInfo($file); $filename = $info->getFilename(); $directory = str_replace($filename, '', $file) . 'spam/'; Folder::make($directory); File::move($file, Path::assemble($directory, $filename)); }
/** * Store the first revision for a given $file * * @param string $file The file needing a first revision */ public function saveFirstRevision($file) { // if this has revisions, abort if ($this->hasRevisions($file)) { return; } // get file contents $full_path = Path::assemble(BASE_PATH, Config::getContentRoot(), $file); $existing_content = File::get($full_path); // save revision $this->saveRevision($file, $existing_content, __('first_save'), File::getLastModified($full_path)); }
/** * Upload a file. * * @param string $file Name of file * @param string $target target of file * @param string $filename Name of new file * @return bool **/ public static function upload($file, $destination, $add_root_variable = false, $renamed_file = false) { Folder::make($destination); $info = pathinfo($file['name']); $extension = $info['extension']; $filename = $renamed_file ?: $info['filename']; // build filename $new_filename = Path::assemble(BASE_PATH, $destination, $filename . '.' . $extension); // check for dupes if (File::exists($new_filename)) { $new_filename = Path::assemble(BASE_PATH, $destination, $filename . '-' . date('YmdHis') . '.' . $extension); } // Check if destination is writable if (!Folder::isWritable($destination)) { Log::error('Upload failed. Directory "' . $destination . '" is not writable.', 'core'); return null; } // write file move_uploaded_file($file['tmp_name'], $new_filename); return Path::toAsset($new_filename, $add_root_variable); }
/** * Creates and downloads a zip file of the static pages * * @return void */ public function download() { $path = Path::assemble(BASE_PATH, $this->config['destination']); $zip_name = 'site-' . time() . '.zip'; $zip_filename = Path::assemble(BASE_PATH, '_cache/_add-ons/', $this->addon_name, $zip_name); $zip = new ZipArchive(); $zip->open($zip_filename, ZipArchive::CREATE); $ignore = array('.', '..', '.DS_Store'); foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $file) { // Ignore ignored files if (in_array(substr($file, strrpos($file, '/') + 1), $ignore)) { continue; } $filename = trim(Path::trimFilesystem($file), '_'); $zip->addFile($file->getPathname(), $filename); } $zip->close(); header('Content-Type: application/zip'); header('Content-disposition: attachment; filename=' . $zip_name); header('Content-Length: ' . filesize($zip_filename)); readfile($zip_filename); }