xenogenesi::blog
memento
3d adt android apache2 app apt aria2 build bullet cflags chromium codeigniter debian demoscene dependencies dpkg driver emulator freeglut gcc gfx git glut htaccess javascript json kernel linux make metalink minimal mysql opengl php python raspbian realtime rpi specs template toolchain update-alternatives video wifi wordpress

debian/stretch, apache2, mod_rewrite and .htaccess

by default debian/stretch apache2 installation have mod_rewrite disabled (at least the one used with debootstrap and lxc containers) so few steps are needed to enable it and .htaccess files

enable mod_rewrite (apache2 must be restarted, see below)

a2endmod rewrite

in the virtual host configuration enable .htaccess (apache2 must be restarted, see below)

<Directory "/var/www/htdocs">
     AllowOverride All
</Directory>

optionally enable mod_rewrite log (in the virtual host configuration) output goes into error.log (don’t leave it enabled in production) note: rewrite engine may need to be enabled before (apache2 must be restarted, see below)

RewriteEngine On
LogLevel alert rewrite:trace6

restart apache

systemctl restart apache2

SSL Let’s encrypt on Debian stretch with dehydrated

Assuming you’ve apache2 already installed and a reachable internet server running

apt-get install dehydrated

Add/edit /etc/apache2/conf-available/letscrypt.conf (notice the difference between the alias and the real directory which is plural acme-challenges):

Alias /.well-known/acme-challenge/ "/var/lib/dehydrated/acme-challenges/"
<Directory "/var/lib/dehydrated/acme-challenges/">
        Options None
        AllowOverride None
        # Apache 2.x
        <IfModule !mod_authz_core.c>
                Order allow,deny
                Allow from all
        </IfModule>
        # Apache 2.4
        <IfModule mod_authz_core.c>
                Require all granted
        </IfModule>
</Directory>

Add/edit /etc/dehydrated/conf.d/99_email.sh:

CONTACT_EMAIL="anymail@yourdomain"

Edit /etc/dehydrated/domains.txt, set the domains for which generate certificates.

Restart apache2 and run dehydrated -c, it should create the domain certs.

Edit your apache’s host file (/etc/apache2/sites-available/default-ssl.conf), replace DOMAIN with your domains:

SSLCertificateFile /var/lib/dehydrated/certs/DOMAIN/fullchain.pem
SSLCertificateKeyFile /var/lib/dehydrated/certs/DOMAIN/privkey.pem

Add/edit /etc/cron.daily/dehydrated:

#!/bin/sh

exec /usr/bin/dehydrated -c >/var/log/dehydrated-cron.log 2>&1

Run chmod 0755 /etc/cron.daily/dehydrated

Add/Edit /etc/logrotate.d/dehydrated:

/var/log/dehydrated-cron.log
{
        rotate 12
        monthly
        missingok
        notifempty
        delaycompress
        compress
}

Yii2: more about assets

Yii2’s guide about assets is good and explain how to compress, convert and combine bundles but lack some information, not every asset can be combined (for instance, javascripts with some custom dynamic module/plugins loading may cause some trouble).

The defaul hash() function:

$path = (is_file($path) ? dirname($path) : $path) . filemtime($path);
return sprintf('%x', crc32($path . Yii::getVersion() . '|' . $this->linkAssets));

it evaluates the directory full path and the file/directory mtime, Yii’s version and the option linkAssets, this mean if your development and production server have different paths the asset will need to be published again (as mentioned in the guide the option hashCallback could be used to modify this behavior).

You may want (as I do) to process your development environment to generate a production directory and publish all assets, even the one not combined, in the current Yii2 implementation there’s nothing ready to do so, you need to add a console command, something like that:

namespace app\commands;

use Yii;
use yii\console\Controller;

class PublishController extends Controller
{
    public function actionIndex($assetName = null) {

        Yii::setAlias('@webroot', __DIR__ . '/../web' );
        Yii::setAlias('@web', '/');

        if ($assetName != null) {
            echo "* publishing:  '$assetName'\n";
            $asset = new $assetName();
            $asset->publish(Yii::$app->assetManager);
            echo "  - sourcePath: $asset->sourcePath\n";
            echo "  - baseUrl: $asset->basePath\n";
        }
    }

then call it from the shell or a shell script (using the same namespace and class name used by Yii2’s loader to find the asset):

php yii publish noam148\\imagemanager\\assets\\ImageManagerAsset

Phing’s AdhocTaskdefTask adjusting relative paths

I’m using phing to automate a deploy of a php web application to production, phing is a really powerful tool (and easy to use), AdhocTaskdefTask allow to implement custom tags with input and output parameters, for example, I needed to adjust some relative path in production, there’s a simple adhoc task to get the new paths:

<!--
    Usage:
    <relative-path from="${from}" to="${to}"
        output="project_property" />
-->
<adhoc-task name="relative-path"><![CDATA[
    class RelativePath extends Task {
        private $from;
        private $to;
        private $output;

        function setFrom($from) {
            $this->from = $from;
        }

        function setTo($to) {
            $this->to = $to;
        }

        function setOutput($output=null) {
            $this->output = $output;
        }

        function main() {
            $relpath = $this->find_relative_path($this->from, $this->to);
            $this->log("relpath = " . $relpath);
            if ($this->output != null) {
                $this->project->setProperty($this->output, $relpath);
            }
        }

        /**
         * credits: https://gist.github.com/ohaal/2936041
         * Find the relative file system path between two file system paths
         *
         * @param  string  $frompath  Path to start from
         * @param  string  $topath    Path we want to end up in
         *
         * @return string             Path leading from $frompath to $topath
         */
        function find_relative_path ( $frompath, $topath ) {
            $from = explode( DIRECTORY_SEPARATOR, $frompath ); // Folders/File
            $to = explode( DIRECTORY_SEPARATOR, $topath ); // Folders/File
            $relpath = '';

            $i = 0;
            // Find how far the path is the same
            while ( isset($from[$i]) && isset($to[$i]) ) {
                if ( $from[$i] != $to[$i] ) break;
                $i++;
            }
            $j = count( $from ) - 1;
            // Add '..' until the path is the same
            while ( $i <= $j ) {
                if ( !empty($from[$j]) ) $relpath .= '..'.DIRECTORY_SEPARATOR;
                $j--;
            }
            // Go to folder from where it starts differing
            while ( isset($to[$i]) ) {
                if ( !empty($to[$i]) ) $relpath .= $to[$i].DIRECTORY_SEPARATOR;
                $i++;
            }

            // Strip last separator
            return substr($relpath, 0, -1);
        }
    }
]]></adhoc-task>

phpunit with phpstorm < 9.5

PhpStorm versions older than 9.5 may have some trouble running phpunit tests:

PHP Fatal error:  Call to undefined method PHP_CodeCoverage_Filter::addFileToBlacklist()

so:

composer require --dev "phpunit/phpunit=4.*" # to install phpunit as dev dependency then...
# not working with phpunit 5
composer require --dev phpunit/php-code-coverage dev-master#b8436b000263f6d72fbad1d36890e247ce84857e

reference

apache2/php/mysql (logs) timezone

Setting timezone for apache/php/mysql (logs timestamp also)

# apache2 on debian (it get system tz)
dpkg-reconfigure tzdata

# this doesn't work (maybe useful for .htaccess/vhosts?)
echo "SetEnv TZ Europe/Rome" > /etc/apache2/conf-available/tz-rome.conf
service apache2 reload

# php
echo 'date.timezone = "Europe/Rome"' > /etc/php5/apache2/conf.d/30-tz-rome.ini

# mysql (untested)
default-time-zone = "Europe/Rome"

preparing thumbnails and html for gallery (ImageMagick)

1) cd into the directory where images are, create thumbs/ directory

mogrify  -format gif -path thumbs -thumbnail "75x75^" -gravity center -extent 75x75 *.jpg

this will create a gif for each jpg 75×75 square size

2) create the html (I’m using blueimp Gallery) lightbox

for IMG in *.jpg; do
   THUMB="${IMG%.*}.gif"
   printf -- "<a href=\"assets/images/gallery/$IMG\" title=\"...\">"
   printf -- "<img src=\"assets/images/gallery/thumbs/$THUMB\" alt=\"...\">"
   printf -- "</a>"`
done

notice: img tags have display: inline-block property by default, mean there will be some margin see fighting-the-space-between-inline-block-elements for details

python/jinja2 for metaprogramming

A simple example using python and jinja2 template engine, I’m evaluating it for doing some metaprogramming (generating php/html and javascript from a json).
I evaluated also fmpp/freemarker but jinja2 is just so simple and its syntax doesn’t conflict with php/html/javascript/css.

test.py:

from jinja2 import Template
import json

rootJson = json.load(open('test.json', 'r'))

tpl = Template(open('test.jinja', 'r').read().decode('utf-8'))
print tpl.render(root=rootJson).encode('utf-8')

test.json:

{
    "test": "valueèè&&"
}

test.jinja:

Hello {{ root.test|e }}

debugging a responsive web page

Using bootstrap (3) will show the visible class for the current window width:

<div class="row">
    <div class="col-xs-12 text-center">
        <div class="visible-lg text-success">Large Device (&gt;= 1200px)</div>
        <div class="visible-md text-warning">Medium Device (&gt;= 992px)</div>
        <div class="visible-sm text-warning">Small Device (&gt;= 768px)</div>
        <div class="visible-xs text-danger">Extra Small Device (&gt;= 480px)</div>
    </div>
</div>

The javascript below will show the current window width:

<p class="text-center">Current width: <span id="screen-width"></span></p>
<script>
updateScreenWidth();
window.addEventListener('resize', updateScreenWidth);
function updateScreenWidth(){
    document.getElementById('screen-width').innerText = document.documentElement.clientWidth;
}
</script>

I also found this responsive tool handy (on github)
(Had the weird idea to make a desktop app like this with python/gtk/webkit (a webkit view is really easy to embed with python) but … just an idea till now)

Also useful to begin the bootstrap grid this simple tool is awesome http://shoelace.io/

wordpress: add upload file types

wp-content/themes/your-theme/functions.php:

add_filter('upload_mimes', 'custom_upload_mimes');
function custom_upload_mimes ( $existing_mimes=array() ) {
    $existing_mimes['tgz'] = 'application/x-compressed-tar';
    return $existing_mimes; 
}