#!/usr/bin/php-cgi -dcgi.force_redirect=0
<?php
# encoding: utf-8
# api: cgi
# type: config
# category: wiki
# title: WikiTag
# description: tag wiki pages
# version: 0.2
# state: beta
# config: -
# access: ailsv
#
# Simplifies adding tags to wiki pages.
# Basically a wrapper around `fossil tag add` which looks up the first artifact id.
# (On the assumption that the very first page artifict should declare any tags.)
#
#


#-- init
include("./fossil_common.php");   # db() etc.
#if (!is_admin()) {
#    die("Admin-only");   // doing has_cap() before save() anyway
#}
error_reporting(E_ALL);

#-- fossil HTML output
function page_md($text) {
    header("Content-Type: text/html; charset=utf-8");
    print <<<EOF
<div class='fossil-doc' data-title='Tag wiki pages'>
<style>
 .save-button {
    padding: 2pt 30pt;
 }
</style>
$text
EOF;
}


#-- query page names and tags
function wiki_pages($TYPEFILTER = "AND tagtype != 0") {
    $r = db("
        SELECT
           SUBSTR(tagname,6) AS pagename,
           MIN(tagxref.rid) AS rid,
           (SELECT GROUP_CONCAT(tagname, ', ')
              FROM (SELECT tagname
                      FROM tagxref tx2
                      JOIN tag tg2 ON tx2.tagid=tg2.tagid
                     WHERE tx2.rid=tagxref.rid
                       AND tx2.tagid != tagxref.tagid
                       $TYPEFILTER
                    )
            ) AS pagetag
        FROM
           tagxref
        LEFT JOIN
           tag ON tagxref.tagid=tag.tagid
        WHERE
           tagname LIKE 'wiki-%' AND
           NOT tagxref.tagid IN (SELECT tagid FROM (SELECT tagid,value,MAX(rid) FROM tagxref GROUP BY tagid) WHERE NOT value)
        GROUP BY
           tagxref.tagid
        ORDER BY
           LOWER(pagename)
    ");
    return array_column($r, $val="pagetag", $key="pagename");
}
function first_uuid($page) {
    return db("
        SELECT uuid, MIN(blob.rid)
          FROM blob
          LEFT JOIN tagxref ON blob.rid=tagxref.rid
          LEFT JOIN tag ON tagxref.tagid=tag.tagid
         WHERE tagname=?
         GROUP BY tagxref.tagid
    ", ["wiki-$page"])[0]["uuid"];
}


#-- saving
function save($pt, $q="escapeshellarg") {
    $orig = wiki_pages();
    foreach ($pt as $page=>$tags) {
        if ($tags == $orig[$page]) {
            continue;
        }
        $uuid = first_uuid($page);
        $new = array_filter(str_getcsv($tags));
        $old = array_filter(str_getcsv($orig[$page]));
        #-- add
        foreach (array_diff($new, $old) as $add) {
            $propagate = empty($_POST["propagate"]) ? "" : "--propagate";
            fossil_exec(["tag", "add", $propagate, $add, $uuid]);
        }
        #-- rm
        foreach (array_diff($old, $new) as $rm) {
            fossil_exec(["tag", "cancel", $rm, $uuid]);
        }
    }
}
if (!empty($_POST["tags"])) {
    if (has_cap("ailsv")) {  #admin,checkin,modwiki,superuser,developer
        save($_POST["tags"]);
    }
}

#-- get page→tags list
$pages = wiki_pages();

#-- print hook row
function pt_row($page, $tags, $h="h") {
    print <<<END
    <tr>
        <td>{$h($page)}</td>
        <td><input name="tags[{$h($page)}]" value="{$h($tags)}"></td>
    </tr>
END;
}


#-- build form table
page_md("
  <div class=config-list>
  <form method=POST enctype='multipart/form-data'>
  <table>
  <tr> <th>Page</th> <th>Tags</th> </tr>
");

# fields
foreach ($pages as $page=>$tags) {
    pt_row($page, $tags);
}

?>
<tr><td colspan=2 align=center><input type=submit value="Add / Save" class=save-button></td></tr>
<tr><td colspan=2 align=center><label><input type=checkbox name=propagate value=1 checked> <b>--propagate</b> added tags</label></td></tr>
</table>
</form>
<?php
 has_cap("ailsv") or print("<div class=warning>You don't have permission to change tags.</div>");
?>
