Browse Source

support image resize and header override

master
Tsia 3 years ago
parent
commit
36c05274c2
  1. 26
      README.md
  2. 145
      index.php

26
README.md

@ -10,7 +10,7 @@ This is an attempt to generate Static HTML from Twig Templates.
# Config
Edit `settings.php` and change `BASE_PATH` accordingly.
Depending on your webserver, you can change `$redirectMethod` to one of the following:
Depending on your webserver, you can change `REDIRECT_METHOD` to one of the following:
* `REDIRECT_METHOD_NONE`
* `REDIRECT_METHOD_HTACCESS`
* `REDIRECT_METHOD_PHP`
@ -21,13 +21,19 @@ This will change the way, the user is redirected from `altSlugs` (see section "A
`REDIRECT_METHOD_HTACCESS` obviously will only work with Apache. `REDIRECT_METHOD_PHP` obviously will only work with a PHP-capable webserver.
`REDIRECT_METHOD_HTML` will generate HTML files that redirect the user via `<meta>` tags and JS. `REDIRECT_METHOD_SYMLINK` will just symlink the file so basically no redirect will happen.
Depending on your webserver, you can change `$contenttypeOverrideMethod` to one of the following:
* `CONTENTTYPE_OVERRIDE_METHOD_NONE`
* `CONTENTTYPE_OVERRIDE_METHOD_HTACCESS`
* `CONTENTTYPE_OVERRIDE_METHOD_PHP`
Depending on your webserver, you can change `CONTENTTYPE_OVERRIDE_METHOD` to one of the following:
* `HEADER_OVERRIDE_METHOD_NONE`
* `HEADER_OVERRIDE_METHOD_HTACCESS`
* `HEADER_OVERRIDE_METHOD_PHP`
This will change the way, the content-type of pages is overridden. This is only required for example for RSS Feeds etc. where you want a different content-type than the one guessed by the webserver.
again: `CONTENTTYPE_OVERRIDE_METHOD_HTACCESS` obviously will only work with Apache. `CONTENTTYPE_OVERRIDE_METHOD_PHP` obviously will only work with a PHP-capable webserver.
This will change the way, the HTTP headers of pages are overridden. This is only required for example for RSS Feeds etc. where you want a different HTTP Header than the ones guessed by the webserver.
again: `HEADER_OVERRIDE_METHOD_HTACCESS` obviously will only work with Apache. `HEADER_OVERRIDE_METHOD_PHP` obviously will only work with a PHP-capable webserver.
Set `IMAGE_RESIZE_METHOD_*` to define the scaling method for resizing images:
* `IMAGE_RESIZE_METHOD_NONE` disables image resizing. useful if you don't want to change all templates
* `IMAGE_RESIZE_METHOD_WIDTH` resizes the image to the specified width and keeps the aspect ratio
* `IMAGE_RESIZE_METHOD_HEIGHT` resizes the image to the specified height and keeps the aspect ratio
* `IMAGE_RESIZE_METHOD_BEST` resizes the image to best fit inside the given dimensions. (format: "$width,$height" or [$width, $height] in PHP7)
there are some more constants that can be set but usually this is not required.
@ -74,6 +80,9 @@ if a ini-file with the same name as the template exists, it is read. example fil
slug = "faq"
enabled = 1
[headers]
0 = "Content-Type: text/plain"
[altSlugs]
0 = "help"
@ -97,6 +106,9 @@ use `$sort` to sort the pages by a specific item in their ini files.
use `$limit` to limit the amount of pages to fetch.
use `$desc = false` to sort them ascending instead of decending.
use the special twig function `imageresize($image, $size)` to get resized images.
define the constants `IMAGE_RESIZE_METHOD_$size` and `IMAGE_SIZE_$size` accordingly
# advanced settings
`define('DIR_MODE', 0755)` permissions of newly created folders.
`define('OUTPUT_DIR', __DIR__ . '/versions')` the folder where to put the rendered pages. no trailing slash.

145
index.php

@ -32,12 +32,15 @@ define('REDIRECT_METHOD_PHP', 2);
define('REDIRECT_METHOD_HTML', 3);
define('REDIRECT_METHOD_SYMLINK', 4);
define('CONTENTTYPE_OVERRIDE_METHOD_NONE', 0);
define('CONTENTTYPE_OVERRIDE_METHOD_HTACCESS', 1);
define('CONTENTTYPE_OVERRIDE_METHOD_PHP', 2);
define('HEADER_OVERRIDE_METHOD_NONE', 0);
define('HEADER_OVERRIDE_METHOD_HTACCESS', 1);
define('HEADER_OVERRIDE_METHOD_PHP', 2);
define('IMAGE_RESIZE_METHOD_NONE', 0);
define('IMAGE_RESIZE_METHOD_WIDTH', 1);
define('IMAGE_RESIZE_METHOD_HEIGHT', 2);
define('IMAGE_RESIZE_METHOD_BEST', 3);
$redirectMethod = REDIRECT_METHOD_PHP;
$contenttypeOverrideMethod = CONTENTTYPE_OVERRIDE_METHOD_PHP;
require __DIR__ . '/settings.php';
if(! defined('DIR_MODE')){
@ -57,6 +60,15 @@ if(! defined('THEME')){
if(! defined('STATIC_FOLDER')){
define('STATIC_FOLDER', 'static');
}
if(! defined('REDIRECT_METHOD')){
define('REDIRECT_METHOD', REDIRECT_METHOD_PHP);
}
if(! defined('HEADER_OVERRIDE_METHOD')){
define('HEADER_OVERRIDE_METHOD', HEADER_OVERRIDE_METHOD_PHP);
}
if(! defined('IMAGE_RESIZE_METHOD')){
define('IMAGE_RESIZE_METHOD', IMAGE_RESIZE_METHOD_BEST);
}
if(!file_exists(__DIR__ . '/templates/' . THEME)){
throw new Exception('Templates folder not found.');
@ -178,7 +190,8 @@ $loader = new Twig_Loader_Filesystem(__DIR__ . '/templates/' . THEME);
$twig = new Twig_Environment($loader, ['debug' => true]);
$markdownengine = new MarkdownEngine\MichelfMarkdownEngine();
$twig->addExtension(new MarkdownExtension($markdownengine));
$function = new Twig_Function('getPageMeta', function ($path = '/', $sort = null, $limit = 0, $desc = true) use ($defaultParams) {
$twig->addFunction(new Twig_Function('getPageMeta', function ($path = '/', $sort = null, $limit = 0, $offset = 0, $desc = true) use ($defaultParams) {
$tplpath = __DIR__ . '/templates/' . THEME . '/pages' . $path;
if(!file_exists($tplpath)){ throw new Exception('Page ' . $path . ' not found.'); }
$dir_iterator = new RecursiveDirectoryIterator($tplpath);
@ -219,24 +232,23 @@ $function = new Twig_Function('getPageMeta', function ($path = '/', $sort = null
$result = [];
$counter = 0;
$limit += $offset;
foreach($sortedresult as $item){
if($limit == 0 || $counter < $limit){
if(($limit == 0 || $counter < $limit) && ($counter >= $offset || $offset === 0)){
$result[$counter] = $item;
}
$counter++;
}
return $result;
});
$twig->addFunction($function);
}));
$function = new Twig_Function('dump', function ($input) {
$twig->addFunction(new Twig_Function('dump', function ($input) {
Kint::$enabled_mode = Kint::MODE_RICH;
return d($input);
});
$twig->addFunction($function);
}));
$function = new Twig_Function('getPageContent', function ($slug, $block = 'entry') use ($twig, $defaultParams) {
$twig->addFunction(new Twig_Function('getPageContent', function ($slug, $block = 'entry') use ($twig, $defaultParams) {
$dir_iterator = new RecursiveDirectoryIterator(__DIR__ . '/templates/' . THEME . '/pages/');
$iterator = new RecursiveIteratorIterator($dir_iterator);
foreach($iterator as $templatefile){
@ -257,10 +269,9 @@ $function = new Twig_Function('getPageContent', function ($slug, $block = 'entry
return $twig->createTemplate($template)->renderBlock($block, $params);
}
throw new Exception('Page ' . $slug . ' not found.');
});
$twig->addFunction($function);
}));
$function = new Twig_Function('integrityHash', function ($file) {
$twig->addFunction(new Twig_Function('integrityHash', function ($file) {
$urlinfo = parse_url($file);
if(!array_key_exists('scheme', $urlinfo) && substr($file, 0, 2) !== '//'){
$file = __DIR__ . '/static/' . THEME . '/' . $file;
@ -271,8 +282,50 @@ $function = new Twig_Function('integrityHash', function ($file) {
$fileContent = file_get_contents($file);
$hash = hash('sha256', $fileContent, true);
return 'sha256-' . base64_encode($hash);
});
$twig->addFunction($function);
}));
$twig->addFunction(new Twig_Function('imageresize', function ($image, $size) {
$urlinfo = parse_url($image);
$relativefile = 'imagecache/' . $size . '/' . basename($urlinfo['path']);
$outputfile = __DIR__ . '/static/' . THEME . '/' . $relativefile;
if(file_exists($outputfile)){
return 'static/' . $relativefile;
}
if(!array_key_exists('scheme', $urlinfo) && substr($image, 0, 2) !== '//'){
$image = new \Gumlet\ImageResize(__DIR__ . '/static/' . THEME . '/' . $image);
}else{
if(substr($file, 0, 2) === '//') {
$file = 'https:' . $file;
}
$image = \Gumlet\ImageResize::createFromString(file_get_contents($file));
}
if(!is_array(constant('IMAGE_SIZE_' . $size))){
$imagesize = explode(',', constant('IMAGE_SIZE_' . $size));
}
switch(constant('IMAGE_RESIZE_METHOD_' . $size)){
case IMAGE_RESIZE_METHOD_NONE:
return $image;
break;
case IMAGE_RESIZE_METHOD_WIDTH:
$image->resizeToWidth($imagesize[0]);
break;
case IMAGE_RESIZE_METHOD_HEIGHT:
$image->resizeToHeight($imagesize[0]);
break;
case IMAGE_RESIZE_METHOD_BEST:
if(count($imagesize) == 1){
$imagesize[1] = $imagesize[0];
}
$image->resizeToBestFit($imagesize[0], $imagesize[1]);
break;
}
mkdirIfNotExists(dirname($outputfile));
$image->save($outputfile);
return 'static/' . $relativefile;
}));
echo 'creating version folder ' . VERSION_DIR . PHP_EOL;
mkdirIfNotExists(VERSION_DIR);
@ -292,7 +345,7 @@ foreach ($iterator as $templatefile) {
$defaultslug = getDefaultSlug($templatefile);
$slug = empty($params['settings']['slug']) ? $defaultslug : $params['settings']['slug'];
handleAltSlugs($params['altSlugs'], $slug, $redirectMethod);
handleAltSlugs($params['altSlugs'], $slug, REDIRECT_METHOD);
$params['settings']['slug'] = $slug;
$params['basepath'] = BASE_PATH;
@ -306,7 +359,15 @@ foreach ($iterator as $templatefile) {
}
mkdirIfNotExists($outputpath);
if(array_key_exists('contenttype', $params['settings'])){
handleContentTypeOverride($slug, $params['settings']['contenttype'], $contenttypeOverrideMethod);
if(array_key_exists('headers', $params)){
$params['headers'][] = 'Content-Type: ' . $params['settings']['contenttype'];
}else{
$params['headers'] = ['Content-Type: ' . $params['settings']['contenttype']];
}
}
if(array_key_exists('headers', $params)){
handleHeaderOverride($slug, $params['headers'], HEADER_OVERRIDE_METHOD);
}
file_put_contents($outputpath . '/index.html', $output);
}
@ -365,21 +426,25 @@ function getDefaultSlug($templatefile){
function handleAltSlugs($slugs, $target, $method) {
foreach($slugs as $slug) {
echo " " . $slug . PHP_EOL;
$output = VERSION_DIR . '/' . $slug;
if($target !== '/' && $target !== ''){
$redirectTarget = BASE_PATH . $target;
}else{
$redirectTarget = BASE_PATH;
}
switch($method){
case REDIRECT_METHOD_HTACCESS:
file_put_contents(VERSION_DIR . '/.htaccess', 'Redirect 301 ' . BASE_PATH . $slug . ' ' . BASE_PATH . $target . PHP_EOL, FILE_APPEND);
file_put_contents(VERSION_DIR . '/.htaccess', 'Redirect 301 ' . BASE_PATH . $slug . ' ' . $redirectTarget . PHP_EOL, FILE_APPEND);
break;
case REDIRECT_METHOD_PHP:
mkdirIfNotExists($output);
file_put_contents($output . '/index.php', '<?php header("HTTP/1.1 301 Moved Permanently"); header("Location: ' . BASE_PATH . $target . '"); ?>');
file_put_contents($output . '/index.php', '<?php header("HTTP/1.1 301 Moved Permanently"); header("Location: ' . $redirectTarget . '"); ?>');
break;
case REDIRECT_METHOD_HTML:
mkdirIfNotExists($output);
file_put_contents($output . '/index.html', '<html><head><meta http-equiv="refresh" content="0; url=' . BASE_PATH . $target . '">
<script>window.location.href="' . BASE_PATH . $target . '"</script></head>
<body>Redirecting to <a href="' . BASE_PATH . $target . '">' . htmlentities(BASE_PATH . $target) . '</a>...</body></html>');
file_put_contents($output . '/index.html', '<html><head><meta http-equiv="refresh" content="0; url=' . $redirectTarget . '">
<script>window.location.href="' . $redirectTarget . '"</script></head>
<body>Redirecting to <a href="' . $redirectTarget . '">' . htmlentities($redirectTarget) . '</a>...</body></html>');
break;
case REDIRECT_METHOD_SYMLINK:
mkdirIfNotExists(dirname($output));
@ -390,15 +455,27 @@ function handleAltSlugs($slugs, $target, $method) {
}
function handleContentTypeOverride($slug, $contenttype, $method) {
$output = VERSION_DIR . '/' . $slug;
handleHeaderOverride($slug, ['Content-Type: ' . $contenttype], $method);
}
function handleHeaderOverride($slug, $header, $method) {
$outputfile = VERSION_DIR . '/' . $slug;
switch($method){
case CONTENTTYPE_OVERRIDE_METHOD_HTACCESS:
$output .= '/.htaccess';
file_put_contents($output, 'AddType text/xml .html' . PHP_EOL);
case HEADER_OVERRIDE_METHOD_HTACCESS:
$outputfile .= '/.htaccess';
$output = '';
foreach($header as $value){
$output .= $value . PHP_EOL;
}
file_put_contents($outputfile, $output . PHP_EOL);
break;
case CONTENTTYPE_OVERRIDE_METHOD_PHP:
$output .= '/index.php';
file_put_contents($output, '<?php header("Content-Type: ' . $contenttype . '"); readfile("index.html"); ?>');
case HEADER_OVERRIDE_METHOD_PHP:
$outputfile .= '/index.php';
$output = '';
foreach($header as $value){
$output .= 'header("' . $value . '", false);';
}
file_put_contents($outputfile, '<?php ' . $output . ' readfile("index.html"); ?>');
break;
}
}
@ -432,4 +509,4 @@ function unlinkr($dir) {
}
}
return rmdir($dir);
}
}
Loading…
Cancel
Save