8
0
daux.io/libs/DauxHelper.php

379 Zeilen
12 KiB
PHP

<?php namespace Todaymade\Daux;
use Todaymade\Daux\Exception\LinkNotFoundException;
use Todaymade\Daux\Tree\Builder;
use Todaymade\Daux\Tree\Directory;
use Todaymade\Daux\Tree\Entry;
2015-04-23 00:32:30 +02:00
class DauxHelper
{
2015-07-20 15:59:52 +02:00
/**
* Set a new base_url for the configuration
*
* @param Config $config
* @param string $base_url
*/
2015-07-19 14:05:12 +02:00
public static function rebaseConfiguration(Config $config, $base_url)
{
// Avoid changing the url if it is already correct
if ($config->getBaseUrl() == $base_url && !empty($config->getTheme())) {
2015-07-19 14:05:12 +02:00
return;
}
// Change base url for all links on the pages
$config['base_url'] = $base_url;
2015-07-19 14:05:12 +02:00
$config['theme'] = static::getTheme($config, $base_url);
$config['image'] = str_replace('<base_url>', $base_url, $config->getImage());
}
2015-07-17 23:38:06 +02:00
/**
* @param Config $config
2015-07-17 23:38:06 +02:00
* @param string $current_url
* @return array
*/
protected static function getTheme(Config $config, $current_url)
2015-04-23 00:32:30 +02:00
{
$htmlTheme = $config->getHTML()->getTheme();
$theme_folder = $config->getThemesPath() . DIRECTORY_SEPARATOR . $htmlTheme;
$theme_url = $config->getBaseUrl() . 'themes/' . $htmlTheme . '/';
2016-07-27 21:32:51 +02:00
$theme = [];
if (is_file($theme_folder . DIRECTORY_SEPARATOR . 'config.json')) {
$theme = json_decode(file_get_contents($theme_folder . DIRECTORY_SEPARATOR . 'config.json'), true);
2015-04-23 00:32:30 +02:00
if (!$theme) {
2016-07-27 21:32:51 +02:00
$theme = [];
}
2015-04-23 00:32:30 +02:00
}
2015-04-23 00:32:30 +02:00
//Default parameters for theme
$theme += [
'name' => $htmlTheme,
2015-04-23 00:32:30 +02:00
'css' => [],
'js' => [],
'fonts' => [],
'favicon' => '<base_url>themes/daux/img/favicon.png',
2015-07-20 15:59:52 +02:00
'templates' => $theme_folder . DIRECTORY_SEPARATOR . 'templates',
'variants' => [],
2015-04-23 00:32:30 +02:00
];
if ($config->getHTML()->hasThemeVariant()) {
$variant = $config->getHTML()->getThemeVariant();
if (!array_key_exists($variant, $theme['variants'])) {
throw new Exception("Variant '$variant' not found for theme '$theme[name]'");
}
// These will be replaced
foreach (['templates', 'favicon'] as $element) {
if (array_key_exists($element, $theme['variants'][$variant])) {
$theme[$element] = $theme['variants'][$variant][$element];
}
}
// These will be merged
foreach (['css', 'js', 'fonts'] as $element) {
if (array_key_exists($element, $theme['variants'][$variant])) {
$theme[$element] = array_merge($theme[$element], $theme['variants'][$variant][$element]);
}
}
}
$substitutions = [
'<local_base>' => $config->getLocalBase(),
'<base_url>' => $current_url,
2016-07-27 21:32:51 +02:00
'<theme_url>' => $theme_url,
];
2015-04-23 00:32:30 +02:00
// Substitute some placeholders
2015-04-23 10:24:50 +02:00
$theme['templates'] = strtr($theme['templates'], $substitutions);
2015-04-23 00:32:30 +02:00
$theme['favicon'] = utf8_encode(strtr($theme['favicon'], $substitutions));
2015-07-17 23:38:06 +02:00
foreach (['css', 'js', 'fonts'] as $element) {
foreach ($theme[$element] as $key => $value) {
$theme[$element][$key] = utf8_encode(strtr($value, $substitutions));
}
}
2015-04-23 00:32:30 +02:00
return $theme;
}
2015-07-17 23:38:06 +02:00
/**
2016-07-29 23:46:57 +02:00
* Remove all '/./' and '/../' in a path, without actually checking the path
*
2015-07-17 23:38:06 +02:00
* @param string $path
* @return string
*/
public static function getCleanPath($path)
{
2016-07-27 21:32:51 +02:00
$path = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path);
$parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
2016-07-27 21:32:51 +02:00
$absolutes = [];
foreach ($parts as $part) {
if ('.' == $part) {
continue;
}
if ('..' == $part) {
array_pop($absolutes);
} else {
$absolutes[] = $part;
}
}
2016-07-27 21:32:51 +02:00
return implode(DIRECTORY_SEPARATOR, $absolutes);
}
2016-07-29 23:46:57 +02:00
/**
* Get the possible output file names for a source file.
*
* @param Config $config
* @param string $part
* @return string[]
*/
public static function getFilenames(Config $config, $part)
{
$extensions = implode('|', array_map('preg_quote', $config->getValidContentExtensions())) . '|html';
2016-07-27 21:32:51 +02:00
$raw = preg_replace('/(.*)?\\.(' . $extensions . ')$/', '$1', $part);
$raw = Builder::removeSortingInformations($raw);
return ["$raw.html", $raw];
}
2015-07-17 23:38:06 +02:00
/**
* Locate a file in the tree. Returns the file if found or false
*
* @param Directory $tree
* @param string $request
2015-07-18 21:45:38 +02:00
* @return Tree\Content|Tree\Raw|false
2015-07-17 23:38:06 +02:00
*/
public static function getFile($tree, $request)
{
$request = explode('/', $request);
foreach ($request as $node) {
// If the element we're in currently is not a
// directory, we failed to find the requested file
if (!$tree instanceof Directory) {
return false;
}
// Some relative paths may start with ./
if ($node == '.') {
continue;
}
if ($node == '..') {
$tree = $tree->getParent();
continue;
}
// if the node exists in the current request tree,
// change the $tree variable to reference the new
// node and proceed to the next url part
if (isset($tree->getEntries()[$node])) {
$tree = $tree->getEntries()[$node];
continue;
}
2019-11-26 22:08:18 +01:00
// We try a second time by decoding the url
$node = DauxHelper::slug(urldecode($node));
if (isset($tree->getEntries()[$node])) {
$tree = $tree->getEntries()[$node];
continue;
}
// if the node doesn't exist, we can try
// two variants of the requested file:
// with and w/o the .html extension
foreach (static::getFilenames($tree->getConfig(), $node) as $filename) {
if (isset($tree->getEntries()[$filename])) {
$tree = $tree->getEntries()[$filename];
continue 2;
}
}
// At this stage, we're in a directory, but no
// sub-item matches, so the current node must
// be an index page or we failed
if ($node !== 'index' && $node !== 'index.html') {
return false;
}
return $tree->getIndexPage();
}
// If the entry we found is not a directory, we're done
if (!$tree instanceof Directory) {
return $tree;
}
if ($index = $tree->getIndexPage()) {
return $index;
}
return false;
}
2015-07-17 18:30:10 +02:00
/**
* Generate a URL friendly "slug" from a given string.
*
* Taken from Stringy
*
* @param string $title
2015-07-17 18:30:10 +02:00
* @return string
*/
public static function slug($title)
{
// Convert to ASCII
if (function_exists("transliterator_transliterate")) {
$title = transliterator_transliterate("Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC;", $title);
}
2019-12-29 20:41:13 +01:00
$title = iconv("utf-8", "ASCII//TRANSLIT//IGNORE", $title);
// Remove unsupported characters
2015-07-17 18:30:10 +02:00
$title = preg_replace('/[^\x20-\x7E]/u', '', $title);
$separator = '_';
// Convert all dashes into underscores
2016-07-27 21:32:51 +02:00
$title = preg_replace('![' . preg_quote('-') . ']+!u', $separator, $title);
2015-07-17 23:38:06 +02:00
// Remove all characters that are not valid in a URL:
// $-_.+!*'(), separator, letters, numbers, or whitespace.
$title = preg_replace('![^-' . preg_quote($separator) . '\!\'\(\),\.\+\*\$\pL\pN\s]+!u', '', $title);
2015-07-17 23:38:06 +02:00
2015-07-17 18:30:10 +02:00
// Replace all separator characters and whitespace by a single separator
2015-07-17 23:38:06 +02:00
$title = preg_replace('![' . preg_quote($separator) . '\s]+!u', $separator, $title);
2015-07-17 18:30:10 +02:00
return trim($title, $separator);
}
2016-07-29 23:46:57 +02:00
/**
* @param string $from
* @param string $to
* @return string
*/
public static function getRelativePath($from, $to)
{
// some compatibility fixes for Windows paths
$from = is_dir($from) ? rtrim($from, '\/') . '/' : $from;
$to = is_dir($to) ? rtrim($to, '\/') . '/' : $to;
$from = str_replace('\\', '/', $from);
$to = str_replace('\\', '/', $to);
$from = explode('/', $from);
$to = explode('/', $to);
$relPath = $to;
foreach ($from as $depth => $dir) {
// find first non-matching dir
if ($dir === $to[$depth]) {
// ignore this directory
array_shift($relPath);
} else {
// get number of remaining dirs to $from
$remaining = count($from) - $depth;
if ($remaining > 1) {
// add traversals up to first matching dir
$padLength = (count($relPath) + $remaining - 1) * -1;
$relPath = array_pad($relPath, $padLength, '..');
break;
} else {
//$relPath[0] = './' . $relPath[0];
}
}
}
2016-07-27 21:32:51 +02:00
return implode('/', $relPath);
}
2016-09-21 23:10:10 +02:00
public static function isAbsolutePath($path)
{
if (!is_string($path)) {
$mess = sprintf('String expected but was given %s', gettype($path));
throw new \InvalidArgumentException($mess);
}
if (!ctype_print($path)) {
$mess = 'Path can NOT have non-printable characters or be empty';
throw new \DomainException($mess);
}
// Optional wrapper(s).
$regExp = '%^(?<wrappers>(?:[[:print:]]{2,}://)*)';
// Optional root prefix.
$regExp .= '(?<root>(?:[[:alpha:]]:/|/)?)';
// Actual path.
$regExp .= '(?<path>(?:[[:print:]]*))$%';
$parts = [];
if (!preg_match($regExp, $path, $parts)) {
$mess = sprintf('Path is NOT valid, was given %s', $path);
throw new \DomainException($mess);
}
return '' !== $parts['root'];
}
2017-11-07 22:44:27 +01:00
public static function getAbsolutePath($path) {
if (DauxHelper::isAbsolutePath($path)) {
return $path;
}
return getcwd() . '/' . $path;
}
2017-11-07 22:44:27 +01:00
public static function is($path, $type) {
return ($type == 'dir') ? is_dir($path) : file_exists($path);
}
/**
* @param Config $config
* @param string $url
* @return Entry
* @throws LinkNotFoundException
*/
public static function resolveInternalFile($config, $url)
{
$triedAbsolute = false;
// Legacy absolute paths could start with
// "!" In this case we will try to find
// the file starting at the root
if ($url[0] == '!' || $url[0] == '/') {
$url = ltrim($url, '!/');
if ($file = DauxHelper::getFile($config->getTree(), $url)) {
return $file;
}
$triedAbsolute = true;
}
// Seems it's not an absolute path or not found,
// so we'll continue with the current folder
if ($file = DauxHelper::getFile($config->getCurrentPage()->getParent(), $url)) {
return $file;
}
// If we didn't already try it, we'll
// do a pass starting at the root
if (!$triedAbsolute && $file = DauxHelper::getFile($config->getTree(), $url)) {
return $file;
}
throw new LinkNotFoundException("Could not locate file '$url'");
}
public static function isValidUrl($url)
{
return !empty($url) && $url[0] != '#';
}
public static function isExternalUrl($url)
{
return preg_match('#^(?:[a-z]+:)?//|^mailto:#', $url);
}
2015-04-23 00:32:30 +02:00
}