#!/usr/bin/php-cgi -dcgi.force_redirect=0
<?php
# encoding: utf-8
# api: cgi
# type: store
# category: template
# title: meta tags (twitter)
# description: populate fx_meta with wiki page summaries
# version: 0.1
# state: alpha
# config: -
#
# Crafts a `fx_meta` database table to prepare twitter previews
# and image links, or other <meta> and <link> fields.
# Which can then be embedded into the header via:
#
#   <th1>  try { query {SELECT meta FROM fx_meta WHERE name=$current_page} { print $meta } }  </th1>
#
# Should be useable as extroot/ hook or ordinary cron script (with
# repo file as parameter).
#


#-- cli or admin usage
if (!empty($_SERVER["argv"][1])) {
    $_SERVER["FOSSIL_REPOSITORY"] = $_SERVER["argv"][1];
}
elseif (!strstr($_SERVER["FOSSIL_CAPABILITIES"], "s")) {
    die("Run as cron, or as admin");
}



#-- database (== fossil repo)
function db($sql="", $params=[]) {
    static $db;
    if (empty($db)) {
        $db = new PDO("sqlite:$_SERVER[FOSSIL_REPOSITORY]");
    }
    if ($params) {
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    else {
        return $db->query($sql)->fetchAll();
    }
}
function h($s) {
    return htmlspecialchars($h, "utf-8", ENT_QUOTES);
}

#-- init
db("CREATE TABLE IF NOT EXISTS fx_meta (name TEXT, meta TEXT)");
db("DELETE FROM fx_meta");
wiki_pages();

#-- loop through pages
function wiki_pages() {
    foreach (db("SELECT substr(tagname,6) AS name FROM tag WHERE tagname LIKE 'wiki-%';") as $page) {
        $page = $page["name"];
        $q = "escapeshellarg";
        $html = `fossil wiki export --html {$q($page)} -R {$q($_SERVER['FOSSIL_REPOSITORY'])}`;
        db(
            "INSERT INTO fx_meta (name, meta) VALUES (?,?)",
            ["wiki?name=$page", meta_wiki($name, $html)]
        );
    }
}


# <meta> and <link>s for a wiki page
#  · wiki?name=PageName
function meta_wiki($name, $html) {
    $html = preg_replace("~<table.+</table>~s", "", $html);
    $text = preg_replace("~\s+~", " ", strip_tags($html));
    $desc = substr($text, 0, 250);
    $h = "h";
    if (preg_match("~(raw/\w+)\?m=image/~", $html, $uu) || preg_match("~(?:!\[.+]\(|<img.+?src=\S*)(raw/\w+)~", $html, $uu)) {
        $img = $uu[1];
        $meta = <<<EOF
    <meta name="twitter:card" content="summary">
    <meta name="twitter:site" content="@sqlite">
    <meta name="twitter:creator" content="@fossilscm">
    <meta name="twitter:title" content="{$h($page)}">
    <meta name="twitter:description" content="{$h($page)}">
    <meta name="twitter:image" content="{$h($img)}">
    <meta name="twitter:image:src" content="{$h($img)}">
EOF;
    }
    else {
        $meta = "    <meta name=description content=\"{$h($desc)\">\n";
    }
    return $meta;
}

# <link> for files
#  · finfo?name=feeds/aggregator.css
#  · file?name=feeds/aggregator.css&ci=4cebd63e48afb573
#  · info/224e3f34a9f1fe11a22e7edd77120a87ff746b7f2afd7f7398ce212a471877ee
function meta_file($name, $content) {
    $meta = "<link rel='vcs alternate raw' href='raw/...' type='text/plain' content-disposition='inline; filename=$name'>";
    $meta = "<meta name='vcs alternate filename' href='file.cpp'>";
}

