cgi-bin/tek/class/loona.lua
author Timm S. Mueller <tmueller@neoscientists.org>
Mon, 06 Oct 2008 21:36:21 +0200
changeset 247 71a5ca44a68e
parent 246 9378039084bd
child 248 d00981e0d1de
permissions -rw-r--r--
Initialization problem fixed in Post; Re-publishing the published profile did
not work, corrected; updated the debug class
     1 
     2 --
     3 --	loona - tiny CMS
     4 --	Written by Timm S. Mueller <tmueller at neoscientists.org>
     5 --	See copyright notice in COPYRIGHT
     6 --
     7 
     8 local Class = require "tek.class"
     9 local lib = require "tek.lib"
    10 local luahtml = require "tek.lib.luahtml"
    11 local posix = require "tek.os.posix"
    12 local cgi = require "tek.class.cgi"
    13 local Request = require "tek.class.cgi.request"
    14 local util = require "tek.class.loona.util"
    15 local Markup = require "tek.class.markup"
    16 
    17 local boxed_G = {
    18 	string = string, table = table,
    19 	assert = assert, collectgarbage = collectgarbage, dofile = dofile,
    20 	error = error, getfenv = getfenv, getmetatable = getmetatable,
    21 	ipairs = ipairs, load = load, loadfile = loadfile, loadstring = loadstring,
    22 	next = next, pairs = pairs, pcall = pcall, print = print,
    23 	rawequal = rawequal, rawget = rawget, rawset = rawset, require = require,
    24 	select = select, setfenv = setfenv, setmetatable = setmetatable,
    25 	tonumber = tonumber, tostring = tostring, type = type, unpack = unpack,
    26 	xpcall = xpcall
    27 }
    28 
    29 local table, string, assert, unpack, ipairs, pairs, type, require, setfenv =
    30 	table, string, assert, unpack, ipairs, pairs, type, require, setfenv
    31 local open, remove, rename, getenv, time, date =
    32 	io.open, os.remove, os.rename, os.getenv, os.time, os.date
    33 local setmetatable = setmetatable
    34 
    35 -------------------------------------------------------------------------------
    36 --	Module setup:
    37 -------------------------------------------------------------------------------
    38 
    39 module("tek.class.loona", tek.class)
    40 _VERSION = "LOona Class 5.5"
    41 
    42 -------------------------------------------------------------------------------
    43 --	Markup:
    44 -------------------------------------------------------------------------------
    45 
    46 Markup = Markup:newClass()
    47 
    48 function Markup:init()
    49 	self.depth = 1
    50 	return ''
    51 end
    52 
    53 function Markup:exit()
    54 	return ''
    55 end
    56 
    57 function Markup:argument(name, text)
    58 	return ', function()%>', '<%end'
    59 end
    60 
    61 function Markup:func(is_dynamic, args)
    62 	if is_dynamic then
    63 		self.is_dynamic_content = true
    64 	end
    65 	local t = { '<%loona:include("', args[1], '"' }
    66 	table.remove(args, 1)
    67 	for _, v in ipairs(args) do
    68 		table.insert(t, ',' .. v)
    69 	end
    70 	return table.concat(t), ')%>'
    71 end
    72 
    73 function Markup:link(link)
    74 	local func = link:match("^(.*)%(%)$")
    75 	if func then
    76 		return '<%=loona:link("' .. '#' .. self:encodeurl(func, true) .. '", [[', ']])%>'
    77 	elseif link:match("^%a*://.*$") then
    78 		return '<%=loona:elink("' .. self:encodeurl(link, true) .. '", [[', ']])%>'
    79 	else
    80 		return '<%=loona:link("' .. link .. '", [[', ']])%>'
    81 	end
    82 end
    83 
    84 function Markup:indent()
    85 	return '<div class="indent">', '</div>'
    86 end
    87 
    88 -------------------------------------------------------------------------------
    89 --	class Session:
    90 -------------------------------------------------------------------------------
    91 
    92 local Session = Class:newClass { _NAME = "_session" }
    93 
    94 function Session.new(class, self)
    95 	self = self or { }
    96 
    97 	assert(self.id, "No session Id")
    98  	assert(self.sessiondir, "No session directory")
    99 
   100 	self.name = self.id:gsub("(.)", function(a)
   101 		return ("%02x"):format(a:byte())
   102 	end)
   103 
   104 	self.filename = self.sessiondir .. "/" .. self.name
   105 	-- remove non-dotted files (expired sessions) from sessions dir:
   106 
   107 	util.expire(self.sessiondir, "[^.]%S+", self.maxage or 600)
   108 	-- load session state:
   109 	self.data = lib.source(self.filename) or { }
   110 
   111 	return Class.new(class, self)
   112 end
   113 
   114 function Session:save()
   115 	local f = open(self.filename, "wb")
   116 	assert(f, "Failed to open session file for writing")
   117 	lib.dump(self.data, function(...)
   118 		f:write(...)
   119 	end)
   120 	f:close()
   121 end
   122 
   123 function Session:delete()
   124 	remove(self.filename)
   125 end
   126 
   127 -------------------------------------------------------------------------------
   128 --	class Loona
   129 -------------------------------------------------------------------------------
   130 
   131 local Loona = _M
   132 
   133 
   134 function Loona:dbmsg(msg, detail)
   135  	return (msg and detail and self.authuser) and
   136  		("%s : %s"):format(msg, detail) or msg
   137 end
   138 
   139 
   140 function Loona:checkprofilename(n)
   141 	assert(n:match("^%w+$") and n ~= "current",
   142 		self:dbmsg("Invalid profile name", n))
   143 	return n
   144 end
   145 
   146 
   147 function Loona:checklanguage(n)
   148 	assert(n:match("^%l%l$"), self:dbmsg("Invalid language code", n))
   149 	return n
   150 end
   151 
   152 
   153 function Loona:checkbodyname(s)
   154 	s = s or "main"
   155 	assert(s:match("^[%w_]*%w+[%w_]*$"), self:dbmsg("Invalid body name", s))
   156 	return s
   157 end
   158 
   159 
   160 function Loona:deleteprofile(p, lang)
   161 	p = self.config.contentdir .. "/" .. p .. "_" .. (lang or self.lang)
   162 	for e in util.readdir(p) do
   163  		local success, msg = remove(p .. "/" .. e)
   164 		assert(success, self:dbmsg("Error removing entry in profile", msg))
   165 	end
   166 	return remove(p)
   167 end
   168 
   169 
   170 function Loona:copyprofile(dstprof, srcprof, dstlang, srclang)
   171 	local contentdir = self.config.contentdir
   172 	local src = ("%s/%s_%s"):format(contentdir,
   173 		srcprof or self.profile, srclang or self.lang)
   174 	local dst = ("%s/%s_%s"):format(contentdir,
   175 		dstprof or self.profile, dstlang or self.lang)
   176 	assert(src ~= dst, self:dbmsg("Attempt to copy profile over itself"))
   177 	assert(posix.stat(src, "mode") == "directory",
   178 		self:dbmsg("Source profile not a directory", src))
   179 	local success, msg = posix.mkdir(dst)
   180 	assert(success, self:dbmsg("Error creating profile directory " .. dst, msg))
   181 	for e in util.readdir(src) do
   182 		local ext = e:match("^[^.].*%.([^.]*)$")
   183 		if ext ~= "LOCK" then
   184 			local f = src .. "/" .. e
   185 			if posix.stat(f, "mode") == "file" then
   186 				success, msg = lib.copyfile(f, dst .. "/" .. e)
   187 				assert(success, self:dbmsg("Error copying file", msg))
   188 			end
   189 		end
   190 	end
   191 	-- create "current" symlink if none exists for new profile/language
   192 	if not posix.readlink(contentdir .. "/current_" .. dstlang) then
   193 		self:makecurrent(dstprof, dstlang)
   194 	end
   195 end
   196 
   197 
   198 function Loona:makecurrent(prof, lang)
   199 	prof = prof or self.profile
   200 	lang = lang or self.lang
   201 	local contentdir = self.config.contentdir
   202 	local newpath = ("%s/current_%s"):format(contentdir, lang)
   203 	local tmppath = newpath .. "." .. self.session.name
   204 	local success, msg = posix.symlink(prof .. "_" .. lang, tmppath)
   205 	assert(success, self:dbmsg("Cannot create symlink", msg))
   206 	success, msg = rename(tmppath, newpath)
   207 	assert(success, self:dbmsg("Cannot put symlink in place", msg))
   208 	return true
   209 end
   210 
   211 
   212 function Loona:publishprofile(profile, lang)
   213 	lang = lang or self.lang
   214 	local contentdir = self.config.contentdir
   215 
   216 	-- Get languages for the current profile
   217 
   218 	local plangs = { }
   219 	local lmatch = "^" .. self.profile .. "_(%w+)$"
   220 	for e in util.readdir(self.config.contentdir) do
   221 		local l = e:match(lmatch)
   222 		if l then
   223 			table.insert(plangs, l)
   224 		end
   225 	end
   226 
   227 	-- For all languages, update "current" symlink
   228 
   229 	for _, lang in ipairs(plangs) do
   230 		self:makecurrent(profile, lang)
   231 	end
   232 
   233 	-- These arguments are overwritten globally and need to get restored
   234 
   235 	local save_args = { self.args.lang, self.args.profile, self.args.session }
   236 
   237 	-- For all languages, unroll site to static HTML
   238 
   239 	for _, lang in ipairs(plangs) do
   240 		local ext = (#plangs == 1 and ".html") or (".html." .. lang)
   241 		self:recursesections(self.sections, function(self, s, e, path)
   242 			path = path and path .. "/" .. e.name or e.name
   243 			if not e.notvisible then
   244 				Loona:dumphtml {
   245 					request = self.request, -- reuse request
   246 					userdata = self.userdata, -- reuse userdata
   247 					requestpath = path, requestlang = lang,
   248 					htmlext = ext, insecure = true
   249 				}
   250 			end
   251 			return path
   252 		end)
   253 	end
   254 
   255 	-- Restore arguments
   256 
   257 	self.args.lang, self.args.profile, self.args.session = unpack(save_args)
   258 
   259 	-- Update file cache
   260 
   261 	local htdocs = self.config.htdocsdir
   262 	local cache = self.config.htmlcachedir
   263 
   264 	for e in util.readdir(cache) do
   265 		local f = e:match("^.*%.html%.?(%w*)$")
   266 		if f and f ~= "tmp" then
   267 			local success, msg = remove(htdocs .. "/" .. e)
   268 			success, msg = remove(cache .. "/" .. e)
   269  			assert(success,
   270  				self:dbmsg("Could not purge cached HTML file", msg))
   271 		end
   272 	end
   273 
   274 	for e in util.readdir(cache) do
   275 		local f = e:match("^(.*%.html%.?%w*)%.tmp$")
   276 		if f then
   277 			local success, msg = rename(cache .. "/" .. e, cache .. "/" .. f)
   278 			assert(success,
   279 				self:dbmsg("Could not update cached HTML file", msg))
   280 			success, msg = rename(htdocs .. "/" .. e, htdocs .. "/" .. f)
   281 			assert(success,
   282 				self:dbmsg("Could not update cached HTML file", msg))
   283 		end
   284 	end
   285 end
   286 
   287 
   288 function Loona:recursesections(s, func, ...)
   289 	for _, e in ipairs(s) do
   290 		local udata = { func(self, s, e, unpack(arg)) }
   291 		if e.subs then
   292 			self:recursesections(e.subs, func, unpack(udata))
   293 		end
   294 	end
   295 end
   296 
   297 
   298 function Loona:indexsections()
   299 	local userperm = self.session and self.session.data.permissions
   300 	userperm = userperm and userperm ~= "" and "[" .. userperm .. "]"
   301 	self:recursesections(self.sections, function(self, s, e)
   302 		local permitted = true
   303 		local sectperm = e.permissions
   304 		if sectperm and sectperm ~= "" and not self.authuser_seeall then
   305 			permitted = false
   306 			if userperm then
   307 				local num = sectperm:len()
   308 				sectperm:gsub(userperm, function() num = num - 1 end)
   309 				permitted = num == 0
   310 			end
   311 		end
   312 		e.notvalid = not permitted or (not self.secure and e.secure) or
   313 			(not self.authuser_visible and e.secret) or nil
   314 		e.notvisible = e.notvalid or not self.authuser_visible and e.hidden or nil
   315 		s[e.name] = e
   316 	end)
   317 end
   318 
   319 
   320 --	Decompose section path into a stack of sections, returning only up to
   321 --	the last valid element in the path. additionally returns the table of
   322 --	the last section path element (or the default section)
   323 
   324 function Loona:getsection(path)
   325 	local default = not self.authuser and self.config.defname
   326 	local tab = { { entries = self.sections, name = default } }
   327 	local ss = self.sections
   328 	local sectionpath
   329 	(path or ""):gsub("(%w+)/?", function(a)
   330 		if ss then
   331 			local s = ss[a]
   332 			if s and not s.notvalid then
   333 				sectionpath = s
   334 				tab[#tab].name = a
   335 				ss = s.subs
   336 				if ss then
   337 					table.insert(tab, { entries = ss })
   338 				end
   339 			else
   340 				ss = nil -- stop.
   341 			end
   342 		end
   343 	end)
   344 	if not self.section and not sectionpath then
   345 		sectionpath = self.sections[default]
   346 		if sectionpath then
   347 			table.insert(tab, { entries = sectionpath.subs })
   348 		end
   349 	end
   350 	return tab, sectionpath or false
   351 end
   352 
   353 
   354 function Loona:getpath(delimiter, maxdepth)
   355 	local t = { }
   356 	local d = 0
   357 	maxdepth = maxdepth or #self.submenus
   358 	for _, menu in ipairs(self.submenus) do
   359 		if menu.name then
   360 			table.insert(t, menu.name)
   361 		end
   362 		d = d + 1
   363 		if d == maxdepth then
   364 			break
   365 		end
   366 	end
   367 	return table.concat(t, delimiter or "/")
   368 end
   369 
   370 
   371 function Loona:deletesection(fname, all_bodies)
   372 	local fullname = self.contentdir .. "/" .. fname
   373 	local success, msg = remove(fullname)
   374 	if all_bodies then
   375 		local pat = "^" .. -- TODO: check
   376 			fname:gsub("%^%$%(%)%%%.%[%]%*%+%-%?", "%%%1") .. "%..*$"
   377 		for e in util.readdir(self.contentdir) do
   378 			if e:match(pat) then
   379 				remove(self.contentdir .. "/" .. e)
   380 			end
   381 		end
   382 	end
   383 	return success, msg
   384 end
   385 
   386 
   387 function Loona:addpath(path, e)
   388 	local tab = self.sections
   389 	path:gsub("(%w+)/?", function(a)
   390 		if tab then
   391 			local s = tab[a]
   392 			if s then
   393 				if not s.subs then
   394 					s.subs = { }
   395 				end
   396 				tab = s.subs
   397 			else
   398 				table.insert(tab, e)
   399 				tab[a] = e
   400  				tab = nil -- stop
   401 			end
   402 		end
   403 	end)
   404 	return e
   405 end
   406 
   407 
   408 local function lookupname(tab, val)
   409 	for i, v in ipairs(tab) do
   410 		if v.name == val then
   411 			return i
   412 		end
   413 	end
   414 end
   415 
   416 
   417 function Loona:rmpath(path)
   418 	local parent
   419 	local tab = self.sections
   420 	path:gsub("(%w+)/?", function(a)
   421 		if tab then
   422 			local idx = lookupname(tab, a)
   423 			if idx then
   424 				if tab[idx].subs then
   425 					parent = tab[idx]
   426 					tab = tab[idx].subs
   427 				else
   428 					table.remove(tab, idx)
   429 					tab[a] = nil
   430 					if #tab == 0 and parent then
   431 						parent.subs = nil
   432 					end
   433 					tab = nil
   434 				end
   435 			end
   436 		end
   437 	end)
   438 end
   439 
   440 
   441 function Loona:checkpath(path)
   442 	if path ~= "index" then -- "index" is reserved
   443 		local res, idx
   444 		local tab = self.sections
   445 		path:gsub("(%w+)/?", function(a)
   446 			if tab then
   447 				local i = lookupname(tab, a)
   448 				if i then
   449 					res, idx = tab, i
   450 					tab = tab[i].subs
   451 				else
   452 					res, idx, tab = nil, nil, nil
   453 				end
   454 			end
   455 		end)
   456 		return res, idx
   457 	end
   458 end
   459 
   460 
   461 function Loona:title()
   462 	return self.section and (self.section.title or self.section.label or
   463 		self.section.name) or ""
   464 end
   465 
   466 
   467 --	Run a site function snippet, with full error recovery
   468 --	(also recovers from errors in error handling function)
   469 
   470 function Loona:dosnippet(func, errfunc)
   471 	local ret = { lib.catch(func) }
   472 	if ret[1] == 0 or (errfunc and lib.catch(errfunc) == 0) then
   473 		return unpack(ret)
   474 	end
   475 	self:out("<h2>Error</h2>")
   476 	self:out("<h3>" .. self:encodeform(ret[2] or "") .. "</h3>")
   477 	if self.authuser_debug then
   478 		if type(ret[3]) == "string" then
   479 			self:out("<p>" .. self:encodeform(ret[3]) .. "</p>")
   480 		end
   481 		if ret[4] then
   482 			self:out("<pre>" .. self:encodeform(ret[4]) .. "</pre>")
   483 		end
   484 	end
   485 end
   486 
   487 
   488 function Loona:lockfile(file)
   489 	return not self.session and true or
   490 		posix.symlink(self.session.filename, file .. ".LOCK")
   491 end
   492 
   493 
   494 function Loona:unlockfile(file)
   495 	return not self.session and true or remove(file .. ".LOCK")
   496 end
   497 
   498 
   499 function Loona:saveindex()
   500 	local tempname = self.indexfname .. "." .. self.session.name
   501 	local f, msg = open(tempname, "wb")
   502 	assert(f, self:dbmsg("Error opening section file for writing", msg))
   503 	lib.dump(self.sections, function(...)
   504 		f:write(unpack(arg))
   505 	end)
   506 	f:close()
   507 	local success, msg = rename(tempname, self.indexfname)
   508 	assert(success, self:dbmsg("Error renaming section file", msg))
   509 end
   510 
   511 
   512 function Loona:savebody(fname, content)
   513 	fname = self.contentdir .. "/" .. fname
   514 	local f, msg = open(fname, "wb")
   515 	assert(f, self:dbmsg("Could not open file for writing", msg))
   516 	f:write(content or "")
   517 	f:close()
   518 end
   519 
   520 
   521 function Loona:runboxed(func, envitems, ...)
   522 	local fenv = {
   523  		arg = arg,
   524  		loona = self
   525  	}
   526  	if envitems then
   527 	 	for k, v in pairs(envitems) do
   528  			fenv[k] = v
   529  		end
   530  	end
   531  	setmetatable(fenv, { __index = boxed_G }) -- boxed global environment
   532 	setfenv(func, fenv)
   533 	return func()
   534 end
   535 
   536 
   537 function Loona:include(fname, ...)
   538 	assert(not fname:match("%W"), self:dbmsg("Invalid include name", fname))
   539 	local fname2 = ("%s/%s.lua"):format(self.config.extdir, fname)
   540 	local f, msg = open(fname2)
   541 	assert(f, self:dbmsg("Cannot open file", msg))
   542 	local parsed, msg = self:loadhtml(f, "loona:out", fname2)
   543 	msg = msg and (type(msg) == "string" and msg or msg.txt)
   544 	assert(parsed, self:dbmsg("Syntax error", msg))
   545 	return self:runboxed(parsed, nil, unpack(arg))
   546 end
   547 
   548 
   549 --	produce link target (simple)
   550 
   551 function Loona:shref(section, arg)
   552 	local args2 = { } -- propagated or new arguments
   553 	for _, a in ipairs(arg) do
   554 		local key, val = a:match("^([%w_]+)=(.*)$")
   555 		if key and val then -- "arg=val" sets/overrides argument
   556 			table.insert(args2, { name = key, value = val })
   557 		elseif self.args[a] then -- just "arg" propagates argument
   558 			table.insert(args2, { name = a, value = self.args[a] })
   559 		end
   560 	end
   561 	local doc = self:getdocname(section, #args2 > 0)
   562 	local url, anch = doc:match("^(.+)(#.+)$")
   563 	local notfirst = doc:match("%?")
   564 	local href = { anch and url or doc }
   565 	for i, arg in ipairs(args2) do
   566 		if i > 1 or notfirst then
   567 			table.insert(href, "&amp;")
   568 		else
   569 			table.insert(href, "?")
   570 		end
   571 		table.insert(href, arg.name .. "=" .. cgi.encodeurl(arg.value))
   572 	end
   573 	if anch then
   574 		table.insert(href, anch)
   575 	end
   576 	return table.concat(href)
   577 end
   578 
   579 
   580 --	produce link target, implicit propagation of lang, profile, session
   581 
   582 function Loona:href(section, ...)
   583 	if self.session then
   584 		table.insert(arg, 1, "profile")
   585 		table.insert(arg, 1, "session")
   586 	end
   587 	if self.explicitlang then
   588 		table.insert(arg, 1, "lang")
   589 	end
   590 	return self:shref(section, arg)
   591 end
   592 
   593 
   594 function Loona:ilink(target, text, extra)
   595 	return ('<a href="%s"%s>%s</a>'):format(target, extra or "", text)
   596 end
   597 
   598 
   599 --	internal link, implicit propagation of lang, profile, session
   600 
   601 function Loona:link(section, text, ...)
   602 	return self:ilink(self:href(section, unpack(arg)), text or section,
   603 	' class="intlink"')
   604 end
   605 
   606 
   607 --	external link (opens in a new window), no argument propagation
   608 
   609 function Loona:elink(target, text)
   610 	return self:ilink(target, text or target, self.config.extlinkextra)
   611 end
   612 
   613 
   614 --	plain link, no implicit argument propagation
   615 
   616 function Loona:plink(section, text, ...)
   617 	return self:ilink(self:shref(section, arg), text or section)
   618 end
   619 
   620 
   621 --	user interface link, implicit propagation of lang, profile, session
   622 
   623 function Loona:uilink(section, text, ...)
   624 	return self:ilink(self:href(section, unpack(arg)), text or section,
   625 	' class="uilink"')
   626 end
   627 
   628 
   629 --	produce a hidden input value in forms
   630 
   631 function Loona:hidden(name, value)
   632 	return not value and "" or
   633 		('<input type="hidden" name="%s" value="%s" />'):format(name, value)
   634 end
   635 
   636 
   637 function Loona:scanprofiles(func)
   638 	local tab = { }
   639 	local dir = self.config.contentdir
   640 	for f in util.readdir(dir) do
   641 		if posix.lstat(dir .. "/" .. f, "mode") == "directory" then
   642 			f = func(f)
   643 			if f then
   644 				table.insert(tab, f)
   645 			end
   646 		end
   647 	end
   648 	table.sort(tab)
   649 	for _, v in ipairs(tab) do
   650 		tab[v] = v
   651 	end
   652 	return tab
   653 end
   654 
   655 
   656 function Loona:getprofiles(lang)
   657 	lang = lang or self.lang
   658 	return self:scanprofiles(function(f)
   659 		return f:match("^(%w+)_" .. lang .. "$")
   660 	end)
   661 end
   662 
   663 
   664 function Loona:getlanguages(prof)
   665 	prof = prof or self.profile
   666 	return self:scanprofiles(function(f)
   667 		return f:match("^" .. prof .. "_(%l%l)$")
   668 	end)
   669 end
   670 
   671 
   672 --	Functions to produce a navigation menu
   673 
   674 local newent = { name = "new", label = "[+]", action="actionnew=true" }
   675 
   676 function Loona:rmenu(level, render, path, addnew, recurse)
   677 	local sub = (addnew and level == #self.submenus + 1) and
   678 		{ name = "new", entries = { }} or self.submenus[level]
   679  	if sub and sub.entries then
   680 		local visible = { }
   681 		for _, e in ipairs(sub.entries) do
   682 			if not e.notvisible then
   683 				table.insert(visible, e)
   684 			end
   685 		end
   686 		if addnew then
   687 			table.insert(visible, newent)
   688 		end
   689 		local numvis = #visible
   690 		if numvis > 0 then
   691 			render.listbegin(self, level, numvis, path)
   692 			for idx, e in ipairs(visible) do
   693 				local label = self:encodeform(e.label or e.name)
   694 				local newpath = path and path .. "/" .. e.name or e.name
   695 				local active = (e.name == sub.name)
   696 				render.itembegin(self, level, idx, label)
   697 				render.link(self, level, newpath, label, active, e.action)
   698 				if recurse and active then
   699 					self:rmenu(level + 1, render, newpath, addnew, recurse)
   700 				end
   701 				render.itemend(self, level, idx, label)
   702 			end
   703 			render.listend(self)
   704 		end
   705 	end
   706 end
   707 
   708 
   709 function Loona:menu(level, recurse, render)
   710 	level = level or 1
   711 	render = render or { }
   712 	render.link = render.link or
   713 		function(self, level, path, label, active, ...)
   714 			self:out(('<a %shref="%s">%s</a>\n'):format(active and
   715 				'class="active" ' or "", self:href(path, unpack(arg)), label))
   716 		end
   717 	render.listbegin = render.listbegin or
   718 		function(self, level) -- , numvis, path
   719 			self:out('<ul id="menulevel' .. level .. '">\n')
   720 		end
   721 	render.listend = render.listend or
   722 		function(self)
   723 			self:out('</ul>\n')
   724 		end
   725 	render.itembegin = render.itembegin or
   726 		function(self) -- , level, idx
   727 			self:out('<li>\n')
   728 		end
   729 	render.itemend = render.itemend or
   730 		function(self)
   731 			self:out('</li>\n')
   732 		end
   733 	recurse = recurse == nil and true or recurse
   734 	local path = level > 1 and self:getpath("/", level - 1) or nil
   735 	local addnew = self.authuser_menu and
   736 		(not self.ispubprofile or self.config.editablepubprofile)
   737 	self:rmenu(level, render, path, addnew, recurse)
   738 end
   739 
   740 
   741 function Loona:loadcontent(fname)
   742 	if fname then
   743 		local f = open(self.contentdir .. "/" .. fname)
   744 		local c = f:read("*a")
   745 		f:close()
   746 		return c
   747 	end
   748 	return ""
   749 end
   750 
   751 
   752 function Loona:loadmarkup(fname)
   753 	return (fname and fname ~= "") and
   754 		self:domarkup(self:loadcontent(fname)) or ""
   755 end
   756 
   757 
   758 function Loona:editable(editkey, fname, savename)
   759 
   760 	local contentdir = self.contentdir
   761 	local edit, show, hidden, extramsg, changed
   762 
   763 	if self.authuser_edit or self.authuser_profile or self.authuser_menu then
   764 
   765 		local hiddenvars = table.concat( {
   766 			self:hidden("lang", self.args.lang),
   767 			self:hidden("profile", self.profile),
   768 			self:hidden("session", self.session.id),
   769 			self:hidden("editkey", editkey) }, " ")
   770 
   771 		local lockfname = fname and (contentdir .. "/" .. fname)
   772 
   773 		if self.useralert and editkey == self.args.editkey then
   774 
   775 			--	display user alert/request/confirmation
   776 
   777 			hidden = true
   778 			self:out([[
   779 			<form action="]] .. self.document .. [[" method="post" accept-charset="utf-8">
   780 				<fieldset>
   781 					<legend>]] .. self.useralert.text ..[[</legend>
   782 					]] .. (self.useralert.confirm or "") .. [[
   783 					]] .. (self.useralert.returnto or "") .. [[
   784 					<input type="submit" name="actioncancel" value="]] .. self.locale.CANCEL  ..[[" />
   785 					]] .. hiddenvars .. [[
   786 				</fieldset>
   787 			</form>
   788 			]])
   789 
   790 		elseif self.args.actionnew and editkey == "main" and self.authuser_menu then
   791 
   792 			--	form for creating a new section
   793 
   794 			hidden = true
   795 			if self.ispubprofile then
   796 				self:out([[<h2><span class="warn">]] .. self.locale.WARNING_YOU_ARE_IN_PUBLISHED_PROFILE ..[[</span></h2>]])
   797 			end
   798 			self:out([[
   799 			<form action="]] .. self.document .. [[" method="post" accept-charset="utf-8">
   800 				<fieldset>
   801 					<legend>
   802 						]] .. self.locale.CREATE_NEW_SECTION_UNDER .. " " .. self.sectionpath .. [[
   803 					</legend>
   804 					<table>
   805 						<tr>
   806 							<td align="right">
   807 								]] .. self.locale.PATHNAME .. [[
   808 							</td>
   809 							<td>
   810 								<input size="30" maxlength="30" name="editname" />
   811 							</td>
   812 						</tr>
   813 						<tr>
   814 							<td align="right">
   815 								]] .. self.locale.MENULABEL .. [[
   816 							</td>
   817 							<td>
   818 								<input size="30" maxlength="50" name="editlabel" />
   819 							</td>
   820 						</tr>
   821 						<tr>
   822 							<td align="right">
   823 								]] .. self.locale.WINDOWTITLE .. [[
   824 							</td>
   825 							<td>
   826 								<input size="30" maxlength="50" name="edittitle" />
   827 							</td>
   828 						</tr>
   829 						<tr>
   830 							<td align="right">
   831 								]] .. self.locale.INVISIBLE .. [[
   832 							</td>
   833 							<td>
   834 								<input type="checkbox" name="editvisibility" />
   835 							</td>
   836 						</tr>
   837 						<tr>
   838 							<td align="right">
   839 								]] .. self.locale.SECRET .. [[
   840 							</td>
   841 							<td>
   842 								<input type="checkbox" name="editsecrecy" />
   843 							</td>
   844 						</tr>
   845 						<tr>
   846 							<td align="right">
   847 								]] .. self.locale.SECURE_CONNECTION .. [[
   848 							</td>
   849 							<td>
   850 								<input type="checkbox" name="editsecure" />
   851 							</td>
   852 						</tr>
   853 						<tr>
   854 							<td align="right">
   855 								]] .. self.locale.PERMISSIONS .. [[
   856 							</td>
   857 							<td>
   858 								<input size="30" maxlength="50" name="editpermissions" />
   859 							</td>
   860 						</tr>
   861 						<tr>
   862 							<td align="right">
   863 								]] .. self.locale.REDIRECT .. [[
   864 							</td>
   865 							<td>
   866 								<input size="30" maxlength="50" name="editredirect" />
   867 							</td>
   868 						</tr>
   869 					</table>
   870 					<input type="submit" name="actioncreate" value="]] .. self.locale.CREATE .. [[" />
   871 					]] .. hiddenvars .. [[
   872 				</fieldset>
   873 			</form>
   874 			<hr />
   875 			]])
   876 
   877 		elseif self.args.actioneditprops and editkey == "main" and
   878 			self.authuser_menu then
   879 			hidden = true
   880 			if self.ispubprofile then
   881 				self:out([[<h2><span class="warn">]] .. self.locale.WARNING_YOU_ARE_IN_PUBLISHED_PROFILE ..[[</span></h2>]])
   882 			end
   883 			self:out([[
   884 			<form action="]] ..self.document .. [[" method="post" accept-charset="utf-8">
   885 				<fieldset>
   886 					<legend>
   887 						]] .. self.locale.MODIFY_PROPERTIES_OF_SECTION .. " " .. self.sectionpath .. [[
   888 					</legend>
   889 					<table>
   890 						<tr>
   891 							<td align="right">
   892 								]] .. self.locale.MENULABEL .. [[
   893 							</td>
   894 							<td>
   895 								<input size="30" maxlength="50" name="editlabel" value="]] .. (self.section.label or "") .. [[" />
   896 							</td>
   897 						</tr>
   898 						<tr>
   899 							<td align="right">
   900 								]] .. self.locale.WINDOWTITLE .. [[
   901 							</td>
   902 							<td>
   903 								<input size="30" maxlength="50" name="edittitle" value="]] .. (self.section.title or "") .. [[" />
   904 							</td>
   905 						</tr>
   906 						<tr>
   907 							<td align="right">
   908 								]] .. self.locale.INVISIBLE .. [[
   909 							</td>
   910 							<td>
   911 								<input type="checkbox" name="editvisibility" ]] .. (self.section.hidden and 'checked="checked"' or "") .. [[/>
   912 							</td>
   913 						</tr>
   914 						<tr>
   915 							<td align="right">
   916 								]] .. self.locale.SECRET .. [[
   917 							</td>
   918 							<td>
   919 								<input type="checkbox" name="editsecrecy" ]] .. (self.section.secret and 'checked="checked"' or "") .. [[/>
   920 							</td>
   921 						</tr>
   922 						<tr>
   923 							<td align="right">
   924 								]] .. self.locale.SECURE_CONNECTION .. [[
   925 							</td>
   926 							<td>
   927 								<input type="checkbox" name="editsecure" ]] .. (self.section.secure and 'checked="checked"' or "") .. [[/>
   928 							</td>
   929 						</tr>
   930 						<tr>
   931 							<td align="right">
   932 								]] .. self.locale.PERMISSIONS .. [[
   933 							</td>
   934 							<td>
   935 								<input size="30" maxlength="50" name="editpermissions" value="]] .. (self.section.permissions or "") .. [[" />
   936 							</td>
   937 						</tr>
   938 						<tr>
   939 							<td align="right">
   940 								]] .. self.locale.REDIRECT .. [[
   941 							</td>
   942 							<td>
   943 								<input size="30" maxlength="50" name="editredirect" value="]] .. (self.section.redirect or "") .. [[" />
   944 							</td>
   945 						</tr>
   946 					</table>
   947 					<input type="submit" name="actionsaveprops" value="]] .. self.locale.SAVE .. [[" />
   948 					<input type="submit" name="actioncancel" value="]] .. self.locale.CANCEL .. [[" />
   949 					]] .. hiddenvars .. [[
   950 				</fieldset>
   951 			</form>
   952 			]])
   953 
   954 		elseif (self.args.actioneditprofiles or
   955 			self.args.actioncreateprofile or
   956 			self.args.actionchangeprofile or
   957 			self.args.actionchangelanguage or
   958 			self.args.actionpublishprofile) and editkey == "main" and
   959 			self.authuser_profile then
   960 			hidden = true
   961 			self:out([[
   962 			<form action="]] .. self.document .. [[" method="post" accept-charset="utf-8">
   963 				<fieldset>
   964 					<legend>
   965 						]] .. self.locale.CHANGEPROFILE .. [[
   966 					</legend>
   967 					<select name="changeprofile" size="1">]])
   968 						for _, val in ipairs(self:getprofiles()) do
   969 							self:out('<option' .. (val == self.profile and ' selected="selected"' or '') .. '>')
   970 							self:out(val)
   971 							self:out('</option>')
   972 						end
   973 					self:out([[
   974 					</select>
   975 					<input type="submit" name="actionchangeprofile" value="]] .. self.locale.CHANGE ..[[" />
   976 					]] .. hiddenvars .. [[
   977 				</fieldset>
   978 			</form>
   979 			<form action="]] .. self.document .. [[" method="post" accept-charset="utf-8">
   980 				<fieldset>
   981 					<legend>
   982 						]] .. self.locale.CHANGELANGUAGE .. [[
   983 					</legend>
   984 					<select name="changelanguage" size="1">]])
   985 						for _, val in ipairs(self:getlanguages()) do
   986 							self:out('<option' .. (val == self.lang and ' selected="selected"' or '') .. '>')
   987 							self:out(val)
   988 							self:out('</option>')
   989 						end
   990 					self:out([[
   991 					</select>
   992 					<input type="submit" name="actionchangelanguage" value="]] .. self.locale.CHANGE ..[[" />
   993 					]] .. hiddenvars .. [[
   994 				</fieldset>
   995 			</form>
   996 			]])
   997 			if self.authuser_publish then
   998 				self:out([[
   999 				<form action="]] .. self.document ..[[" method="post" accept-charset="utf-8">
  1000 					<fieldset>
  1001 						<legend>
  1002 							]] .. self.locale.CREATEPROFILE .. [[
  1003 						</legend>
  1004 						<input size="20" maxlength="20" name="createprofile" />
  1005 						]] .. self.locale.LANGUAGE ..[[
  1006 						<input size="2" maxlength="2" name="createlanguage" value="]] .. self.lang ..[[" />
  1007 						<input type="submit" name="actioncreateprofile" value="]] .. self.locale.CREATE .. [[" />
  1008 						]] .. hiddenvars .. [[
  1009 					</fieldset>
  1010 				</form>
  1011 				]])
  1012 			end
  1013 			if (not self.ispubprofile or self.config.editablepubprofile) and
  1014 				self.authuser_publish then
  1015 				self:out([[
  1016 				<form action="]] .. self.document .. [[" method="post" accept-charset="utf-8">
  1017 					<fieldset>
  1018 						<legend>
  1019 							]] .. self.locale.PUBLISHPROFILE .. [[
  1020 						</legend>
  1021 						]] .. self:hidden("publishprofile", self.profile) .. [[
  1022 						<input type="submit" name="actionpublishprofile" value="]] .. self.locale.PUBLISH .. [[" />
  1023 						]] .. hiddenvars .. [[
  1024 					</fieldset>
  1025 				</form>
  1026 				<form action="]] .. self.document .. [[" method="post" accept-charset="utf-8">
  1027 					<fieldset>
  1028 						<legend>
  1029 							]] .. self.locale.DELETEPROFILE .. [[
  1030 						</legend>
  1031 						]] .. self:hidden("deleteprofile", self.profile) .. [[
  1032 						<input type="submit" name="actiondeleteprofile" value="]] .. self.locale.DELETE .. [[" />
  1033 						]] .. hiddenvars .. [[
  1034 					</fieldset>
  1035 				</form>
  1036 				]])
  1037 			end
  1038 
  1039 		elseif self.args.actionedit and editkey == self.args.editkey and self.authuser_edit then
  1040 			if not self.section.redirect then
  1041 				extramsg = self.ispubprofile and
  1042 					self.locale.WARNING_YOU_ARE_IN_PUBLISHED_PROFILE
  1043 				edit = self:loadcontent(fname):gsub("\194\160", "&nbsp;") -- TODO
  1044 				changed = self.section and (self.section.revisiondate or self.section.creationdate)
  1045 			end
  1046 
  1047 		elseif self.args.actionpreview and editkey == self.args.editkey and
  1048 			self.authuser_edit then
  1049 			edit = self.args.editform
  1050 			show = self:domarkup(edit:gsub("&nbsp;", "\194\160")) -- TODO
  1051 
  1052 		elseif self.args.actionsave and editkey == self.args.editkey
  1053 			and self.authuser_edit then
  1054 			local c = self.args.editform
  1055 			local dynamic
  1056 
  1057 			if lockfname then
  1058 				self:expire(contentdir, "[^.]%S+.LOCK")
  1059 				if self:lockfile(lockfname) then
  1060 					-- lock was expired, aquired a new one
  1061 					extramsg = self.locale.SECTION_COULD_HAVE_CHANGED
  1062 					edit = c
  1063 				else
  1064 					local tab = lib.source(lockfname .. ".LOCK")
  1065 					if tab and tab.id == self.session.id then
  1066 						-- lock already held and is mine - try to save:
  1067 						local savec = c:gsub("&nbsp;", "\194\160") -- TODO
  1068 						remove(contentdir .. "/" .. savename .. ".html")
  1069 						self:savebody(savename, savec)
  1070 						-- TODO: error handling
  1071 						self:unlockfile(lockfname)
  1072 						show, dynamic = self:domarkup(savec)
  1073 						changed = time()
  1074 					else
  1075 						-- lock was expired and someone else has it now
  1076 						extramsg = self.locale.SECTION_IN_USE
  1077 						edit = c
  1078 					end
  1079 				end
  1080 			else
  1081 				-- new sidefile
  1082 				local savec = c:gsub("&nbsp;", "\194\160") -- TODO
  1083 				self:savebody(savename, savec)
  1084 				-- TODO: error handling
  1085 				show, dynamic = self:domarkup(savec)
  1086 			end
  1087 
  1088 			-- mark dynamic text bodies
  1089 			if not self.section.dynamic then
  1090 				self.section.dynamic = { }
  1091 			end
  1092 			self.section.dynamic[editkey] = dynamic
  1093 			local n = 0
  1094 			for _ in pairs(self.section.dynamic) do
  1095 				n = n + 1
  1096 			end
  1097 			if n == 0 then
  1098 				self.section.dynamic = nil
  1099 			end
  1100 
  1101 			self:saveindex()
  1102 
  1103 		elseif self.args.actioncancel and editkey == self.args.editkey then
  1104 			if lockfname then
  1105 				self:unlockfile(lockfname) -- remove lock
  1106 			end
  1107 		end
  1108 
  1109 		if editkey == "main" and self.section and self.section.redirect then
  1110 			self:out('<h2>' .. self.locale.SECTION_IS_REDIRECT ..'</h2>')
  1111 			self:out(self:link(self.section.redirect))
  1112 			self:out('<hr />')
  1113 		end
  1114 
  1115 		if edit then
  1116 			self:expire(contentdir, "[^.]%S+.LOCK")
  1117 			if fname and not self:lockfile(contentdir .. "/" .. fname) then
  1118 				local tab = lib.source(contentdir .. "/" .. fname .. ".LOCK")
  1119 				if tab and tab.id ~= self.session.id then
  1120 					extramsg = self.locale.SECTION_IN_USE
  1121 				end
  1122 				-- else already owner
  1123 			end
  1124 			if extramsg then
  1125 				self:out('<h2><span class="warn">' .. extramsg .. '</span></h2>')
  1126 			end
  1127 			self:out([[
  1128 			<form action="]] .. self.document .. [[#preview" method="post" accept-charset="utf-8">
  1129 				<fieldset>
  1130 					<legend>
  1131 						]] .. self.locale.EDIT_SECTION .. [[
  1132 					</legend>
  1133 					<textarea cols="80" rows="25" name="editform">
  1134 ]] .. self:encodeform(edit) .. [[</textarea>
  1135 					<br />
  1136 					<input type="submit" name="actionsave" value="]] .. self.locale.SAVE .. [[" />
  1137 					<input type="submit" name="actionpreview" value="]] .. self.locale.PREVIEW .. [[" />
  1138 					<input type="submit" name="actioncancel" value="]] .. self.locale.CANCEL .. [[" />
  1139 					]] .. hiddenvars .. [[
  1140 				</fieldset>
  1141 			</form>
  1142 			]])
  1143 		end
  1144 	end
  1145 
  1146 	if not hidden then
  1147 		self:dosnippet(function()
  1148 			if not show then
  1149 				show = self:loadmarkup(fname)
  1150 				changed = self.section and (self.section.revisiondate or self.section.creationdate)
  1151 			end
  1152 			local parsed, msg = self:loadhtml(show, "loona:out", "<parsed html>")
  1153 			assert(parsed, msg and "Syntax error : " .. msg)
  1154 			self:runboxed(parsed)
  1155 		end)
  1156 	end
  1157 
  1158 	if self.authuser_profile or self.authuser_edit or self.authuser_menu then
  1159 		self:out([[
  1160 		<hr />
  1161 		<div class="edit">]])
  1162 			if editkey == "main" then
  1163 				self:out([[
  1164 				<a name="preview"></a>
  1165 				]] .. self.authuser .. [[ : ]])
  1166 				if self.authuser_profile then
  1167 					self:out(self:uilink(self.sectionpath, "[" .. self.locale.PROFILE .. "]", "actioneditprofiles=true", "editkey=" .. editkey) .. [[ :
  1168 						]] .. self.profile .. "_" .. self.lang)
  1169 					if self.ispubprofile then
  1170 						self:out([[
  1171 							<span class="warn">[]] .. self.locale.PUBLIC .. [[]</span>]])
  1172 					end
  1173 					self:out(" : ")
  1174 				end
  1175 				self:out(self.sectionpath .. ' ')
  1176 			end
  1177 			if self.section and (not self.ispubprofile or self.config.editablepubprofile) then
  1178 				if self.authuser_edit then
  1179 					self:out('- ' .. self:uilink(self.sectionpath, "[" .. self.locale.EDIT .. "]", "actionedit=true", "editkey=" .. editkey) .. " ")
  1180 				end
  1181 				if editkey == "main" and self.authuser_menu then
  1182 					self:out('- ' .. self:uilink(self.sectionpath, "[" .. self.locale.PROPERTIES .. "]", "actioneditprops=true", "editkey=" .. editkey) .. " ")
  1183 				end
  1184 				if (fname == savename or not self.section.subs) and (self.authuser_edit and self.authuser_menu) then
  1185 					self:out('- ' .. self:uilink(self.sectionpath, "[" .. self.locale.DELETE .. "]", "actiondelete=true", "editkey=" .. editkey) .. " ")
  1186 				end
  1187 				if editkey == "main" and self.authuser_menu then
  1188 					self:out('- ' .. self:uilink(self.sectionpath, "[" .. self.locale.MOVEUP .. "]", "actionup=true", "editkey=" .. editkey) .. " ")
  1189 					self:out('- ' .. self:uilink(self.sectionpath, "[" .. self.locale.MOVEDOWN .. "]", "actiondown=true", "editkey=" .. editkey) .. " ")
  1190 				end
  1191 				if changed and editkey == "main" then
  1192 					self:out('- ' .. self.locale.CHANGED .. ': ' .. date("%d-%b-%Y %T", changed))
  1193 				end
  1194 			end
  1195 		self:out('</div>')
  1196 	end
  1197 
  1198 end
  1199 
  1200 
  1201 --	Get pathname of an existing content file that
  1202 --	the current path is determined by (or defaults to)
  1203 
  1204 function Loona:getsectionpath(bodyname, requestpath)
  1205 	local ext = (not bodyname or bodyname == "main") and "" or "." .. bodyname
  1206 	local t, path, section = { }
  1207 	for _, menu in ipairs(self.submenus) do
  1208 		if menu.entries and menu.entries[menu.name] then
  1209 			table.insert(t, menu.name)
  1210 			local fn = table.concat(t, "_")
  1211 			if posix.stat(self.contentdir .. "/" .. fn .. ext,
  1212 				"mode") == "file" then
  1213 				path, section = fn, menu
  1214 			end
  1215 		end
  1216 	end
  1217 	return path, ext, section
  1218 end
  1219 
  1220 
  1221 function Loona:body(name)
  1222 	name = self:checkbodyname(name)
  1223 	local path, ext = self:getsectionpath(name)
  1224 	self:dosnippet(function()
  1225 		self:editable(name, path and path .. ext, self.sectionname .. ext)
  1226 	end)
  1227 end
  1228 
  1229 
  1230 function Loona:init()
  1231 
  1232 	-- get list of languages, in order of preference
  1233 	-- TODO: respect quality parameter, not just order
  1234 
  1235 	local l = self.requestlang or self.args.lang
  1236 	self.langs = { l and l:match("^%w+$") }
  1237 	local s = getenv("HTTP_ACCEPT_LANGUAGE")
  1238 	while s do
  1239 		local l, r = s:match("^([%w.=]+)[,;](.*)$")
  1240 		l = l or s
  1241 		s = r
  1242 		if l:match("^%w+$") then
  1243 			table.insert(self.langs, l)
  1244 		end
  1245 	end
  1246 	table.insert(self.langs, self.config.deflang)
  1247 
  1248 	-- get list of possible profiles
  1249 
  1250 	local profiles = { }
  1251 	for e in util.readdir(self.config.contentdir) do
  1252 		profiles[e] = e
  1253 	end
  1254 
  1255 	-- get pubprofile
  1256 
  1257 	for _, lang in ipairs(self.langs) do
  1258 		local p = posix.readlink(self.config.contentdir .. "/current_" .. lang)
  1259 		p = p and p:match("^(%w+)_" .. lang .. "$")
  1260 		if p then
  1261 			self.pubprofile = p
  1262 			break
  1263 		end
  1264 	end
  1265 
  1266 	-- get profile
  1267 
  1268 	local checkprofile = self.authuser and
  1269 		(self.authuser_profile and self.args.profile or self.session.data.profile)
  1270 		or self.config.defprofile or self.pubprofile or "work"
  1271 
  1272 	for _, lang in ipairs(self.langs) do
  1273 		if profiles[checkprofile .. "_" .. lang] then
  1274 			self.profile = checkprofile
  1275 			self.lang = lang
  1276 			break
  1277 		end
  1278 	end
  1279 
  1280 	assert(self.profile and self.lang, "Invalid profile or language")
  1281 
  1282 
  1283 	self.ispubprofile = self.profile == self.pubprofile
  1284 
  1285 	-- write back language and profile
  1286 
  1287 	self.args.lang = (self.explicitlang or self.lang ~= self.config.deflang)
  1288 		and self.lang or nil
  1289 	self.args.profile = self.profile
  1290 
  1291 	-- determine content directory pathname and section filename
  1292 
  1293 	self.contentdir =
  1294 		("%s/%s_%s"):format(self.config.contentdir, self.profile, self.lang)
  1295  	self.indexfname = self.contentdir .. "/.sections"
  1296 
  1297 	-- load sections
  1298 
  1299  	self.sections = lib.source(self.indexfname)
  1300 
  1301 	-- index sections, determine visibility in menu
  1302 
  1303 	self:indexsections()
  1304 
  1305 	-- decompose request path, produce a stack of sections
  1306 
  1307 	self.submenus, self.section = self:getsection(self.requestpath)
  1308 
  1309 	-- handle redirects if not logged on
  1310 
  1311 	if not self.authuser_edit and self.section and self.section.redirect then
  1312 		self.submenus, self.section = self:getsection(self.section.redirect)
  1313 	end
  1314 
  1315 	-- section path and document name (refined)
  1316 
  1317 	self.sectionpath = self:getpath()
  1318 	self.sectionname = self:getpath("_")
  1319 
  1320 end
  1321 
  1322 
  1323 function Loona:handlechanges()
  1324 
  1325 	local save
  1326 
  1327 	if self.args.editkey == "main" then
  1328 
  1329 		-- In main editable section:
  1330 
  1331 		if self.args.actioncreate then
  1332 
  1333 			-- Create new section
  1334 
  1335 			local editname = self.args.editname:lower()
  1336 			assert(not editname:match("%W"),
  1337 				self:dbmsg("Invalid section name", editname))
  1338 			if not (section and (section.subs or section)[editname]) then
  1339 				local newpath = (self.sectionpath and
  1340 					(self.sectionpath .. "/")) .. editname
  1341 				local s = self:addpath(newpath, { name = editname,
  1342 					label = self.args.editlabel ~= "" and
  1343 						self.args.editlabel or nil,
  1344 					title = self.args.edittitle ~= "" and
  1345 						self.args.edittitle or nil,
  1346 					redirect = self.args.editredirect ~= "" and
  1347 						self.args.editredirect or nil,
  1348 					permissions = self.args.editpermissions ~= "" and
  1349 						self.args.editpermissions or nil,
  1350 					hidden = self.args.editvisibility and true,
  1351 					secret = self.args.editsecrecy and true,
  1352 					secure = self.args.editsecure and true,
  1353 					creator = self.authuser,
  1354 					creationdate = time() })
  1355 				save = true
  1356 			end
  1357 
  1358 		elseif self.args.actionsave then
  1359 
  1360 			-- Save section
  1361 
  1362 			self.section.revisiondate = time()
  1363 			self.section.revisioner = self.authuser
  1364 			save = true
  1365 
  1366 		elseif self.args.actionsaveprops then
  1367 
  1368 			-- Save properties
  1369 
  1370 			self.section.hidden = self.args.editvisibility and true
  1371 			self.section.secret = self.args.editsecrecy and true
  1372 			self.section.secure = self.args.editsecure and true
  1373 			self.section.label = self.args.editlabel ~= "" and
  1374 				self.args.editlabel or nil
  1375 			self.section.title = self.args.edittitle ~= "" and
  1376 				self.args.edittitle or nil
  1377 			self.section.redirect =
  1378 				self.args.editredirect ~= "" and self.args.editredirect or nil
  1379 			self.section.permissions =
  1380 				self.args.editpermisisons ~= "" and self.args.editpermissions or nil
  1381 			save = true
  1382 
  1383 		elseif self.args.actionup then
  1384 
  1385 			-- Move section up
  1386 
  1387 			local t, i = self:checkpath(self.sectionpath)
  1388 			if t and i > 1 then
  1389 				if self.ispubprofile and not self.args.actionconfirm then
  1390 					self.useralert = {
  1391 						text = self.locale.ALERT_MOVE_IN_PUBLISHED_PROFILE,
  1392 						confirm =
  1393 							'<input type="submit" name="actionup" value="' ..
  1394 							self.locale.MOVE .. '" /> ' ..
  1395 							self:hidden("actionconfirm", "true")
  1396 					}
  1397 				else
  1398 					local item = table.remove(t, i)
  1399 					table.insert(t, i - 1, item)
  1400 					save = true
  1401 				end
  1402 			end
  1403 
  1404 		elseif self.args.actiondown then
  1405 
  1406 			-- Move section down
  1407 
  1408 			local t, i = self:checkpath(self.sectionpath)
  1409 			if t and i < #t then
  1410 				if self.ispubprofile and not self.args.actionconfirm then
  1411 					self.useralert = {
  1412 						text = self.locale.ALERT_MOVE_IN_PUBLISHED_PROFILE,
  1413 						confirm =
  1414 							'<input type="submit" name="actiondown" value="' ..
  1415 							self.locale.MOVE .. '" /> ' ..
  1416 							self:hidden("actionconfirm", "true")
  1417 					}
  1418 				else
  1419 					local item = table.remove(t, i)
  1420 					table.insert(t, i + 1, item)
  1421 					save = true
  1422 				end
  1423 			end
  1424 
  1425 		elseif self.args.actioncreateprofile and self.args.createprofile then
  1426 
  1427 			-- Create profile
  1428 
  1429 			local c = self.args.createprofile
  1430 			if c == "" then
  1431 				c = self.profile
  1432 			end
  1433 			c = self:checkprofilename(c:lower())
  1434 			local l = self:checklanguage((self.args.createlanguage or self.lang):lower())
  1435 			if c == self.profile and l == self.lang then
  1436 				self.useralert = {
  1437 					text = self.locale.ALERT_CANNOT_COPY_PROFILE_TO_SELF,
  1438 					returnto = self:hidden("actioneditprofiles", "true")
  1439 				}
  1440 			else
  1441 				local profiles = self:getprofiles(l)
  1442 				local text
  1443 				if c == self.pubprofile then
  1444 					text = self.locale.ALERT_OVERWRITE_PUBLISHED_PROFILE
  1445 				elseif profiles[c] and l == self.lang then
  1446 					text = self.locale.ALERT_OVERWRITE_EXISTING_PROFILE
  1447 				end
  1448 				if text and not self.args.actionconfirm then
  1449 					self.useralert = {
  1450 						text = text,
  1451 						returnto = self:hidden("actioneditprofiles", "true"),
  1452 						confirm = '<input type="submit" ' ..
  1453 							'name="actioncreateprofile" value="' ..
  1454 							self.locale.OVERWRITE .. '" /> ' ..
  1455 							self:hidden("actionconfirm", "true") ..
  1456 							self:hidden("createlanguage", l) ..
  1457 							self:hidden("createprofile", c)
  1458 					}
  1459 				else
  1460 					if profiles[c] then
  1461 						self:deleteprofile(c, l)
  1462 					end
  1463 					self:copyprofile(c, self.profile, l, self.lang)
  1464 				end
  1465 			end
  1466 
  1467 		elseif self.args.actiondeleteprofile and self.args.deleteprofile then
  1468 
  1469 			-- Delete profile
  1470 
  1471 			local c = self:checkprofilename(self.args.deleteprofile:lower())
  1472 			assert(c ~= self.pubprofile,
  1473 				self:dbmsg("Cannot delete published profile", c))
  1474 			if self.args.actionconfirm then
  1475 				self:deleteprofile(c)
  1476 				self.profile = false
  1477 				self.args.profile = nil
  1478 				self:init()
  1479 				save = true
  1480 			else
  1481 				self.useralert = {
  1482 					text = self.locale.ALERT_DELETE_PROFILE,
  1483 					returnto = self:hidden("actioneditprofiles", "true"),
  1484 					confirm = '<input type="submit" ' ..
  1485 						'name="actiondeleteprofile" value="' ..
  1486 						self.locale.DELETE .. '" /> ' ..
  1487 						self:hidden("actionconfirm", "true") ..
  1488 						self:hidden("deleteprofile", c)
  1489 				}
  1490 			end
  1491 
  1492 		elseif self.args.actionchangeprofile and self.args.changeprofile then
  1493 
  1494 			-- Change profile
  1495 
  1496 			local c = self:checkprofilename(self.args.changeprofile:lower())
  1497 			self.profile = c
  1498 			self.args.profile = c
  1499 			save = true
  1500 
  1501 		elseif self.args.actionchangelanguage and self.args.changelanguage then
  1502 
  1503 			-- Change language
  1504 
  1505 			local l = self:checklanguage(self.args.changelanguage:lower())
  1506 			self.lang = l
  1507 			self.args.lang = l
  1508  			self.explicitlang = l
  1509 			save = true
  1510 
  1511 		elseif self.args.actionpublishprofile and self.args.publishprofile then
  1512 
  1513 			-- Publish profile
  1514 
  1515 			local c = self:checkprofilename(self.args.publishprofile:lower())
  1516 			if c ~= self.pubprofile or self.config.editablepubprofile then
  1517 				if self.args.actionconfirm then
  1518 					self:publishprofile(c)
  1519 					save = true
  1520 				else
  1521 					self.useralert = {
  1522 						text = self.locale.ALERT_PUBLISH_PROFILE,
  1523 						returnto = self:hidden("actioneditprofiles", "true"),
  1524 						confirm = '<input type="submit" ' ..
  1525 							'name="actionpublishprofile" value="' ..
  1526 							self.locale.PUBLISH .. '" /> ' ..
  1527 							self:hidden("actionconfirm", "true") ..
  1528 							self:hidden("publishprofile", c)
  1529 					}
  1530 				end
  1531 			end
  1532 		end
  1533 
  1534 	end
  1535 
  1536 	if self.args.actiondelete then
  1537 
  1538 		-- Delete section
  1539 
  1540 		if not self.args.actionconfirm then
  1541 			self.useralert = {
  1542 				text = self.ispubprofile and
  1543 					self.locale.ALERT_DELETE_IN_PUBLISHED_PROFILE or
  1544 					self.locale.ALERT_DELETE_SECTION,
  1545 				confirm =
  1546 					'<input type="submit" name="actiondelete" value="' ..
  1547 					self.locale.DELETE .. '" /> ' ..
  1548 					self:hidden("actionconfirm", "true")
  1549 			}
  1550 		else
  1551 			local key = self.args.editkey
  1552 			if key == "main" and not self.section.subs then
  1553 				self:deletesection(self.sectionname, true) -- all bodies
  1554 				self:rmpath(self.sectionpath) -- and node
  1555 			else
  1556 				local ext = (key == "main" and "") or "." .. key
  1557 				self:deletesection(self.sectionname .. ext) -- only text
  1558 				if self.section.dynamic then
  1559 					self.section.dynamic[key] = nil
  1560 					local n = 0
  1561 					for _ in pairs(self.section.dynamic) do
  1562 						n = n + 1
  1563 					end
  1564 					if n == 0 then
  1565 						self.section.dynamic = nil
  1566 					end
  1567 				end
  1568 			end
  1569 			save = true
  1570 		end
  1571 	end
  1572 
  1573 	if save then
  1574 		self:saveindex()
  1575 		self:init()
  1576 	end
  1577 
  1578 end
  1579 
  1580 
  1581 function Loona:encodeform(s)
  1582 	return util.encodeform(s)
  1583 end
  1584 
  1585 
  1586 function Loona:loadhtml(src, outfunc, chunkname)
  1587  	return luahtml.load(src, outfunc, chunkname)
  1588 end
  1589 
  1590 
  1591 function Loona:domarkup(s)
  1592 	local t = { }
  1593 	local is_dynamic = Markup:new { input = s,
  1594 		features = "hespcadlintf", indentchar = " ",
  1595 		wrfunc = function(s) table.insert(t, s) end }:run()
  1596 	return table.concat(t), is_dynamic
  1597 end
  1598 
  1599 
  1600 function Loona:expire(dir, pat, maxage)
  1601 	return util.expire(dir, pat, maxage or self.config.sessionmaxage)
  1602 end
  1603 
  1604 
  1605 local function wrout(self, s)
  1606 	self.buf:out(s)
  1607 end
  1608 
  1609 
  1610 local function headout(self, s)
  1611 	self.buf:addheader(s)
  1612 end
  1613 
  1614 
  1615 function Loona.new(class, self)
  1616 
  1617 	local parsed, msg
  1618 
  1619 	self = self or { }
  1620 
  1621 	self.langs = false
  1622 	self.document = false
  1623 	self.profile = false
  1624 	self.pubprofile = false
  1625 	self.profile = false
  1626 	self.lang = false
  1627 	self.ispubprofile = false
  1628 	self.contentdir = false
  1629 	self.indexfname = false
  1630 	self.sections = false
  1631 	self.section = false
  1632 	self.submenus = false
  1633 	self.sectionpath = false
  1634 	self.sectionname = false
  1635 	self.getdocname = false
  1636 	self.useralert = false
  1637 	self.loginfailed = false
  1638 
  1639 	-- Buffer
  1640 
  1641 	self.out = self.out or wrout
  1642 	self.addheader = self.addheader or headout
  1643 
  1644 
  1645 	-- Get configuration
  1646 
  1647 	self.config = self.config or lib.source(self.conffile or "../etc/config.lua") or { }
  1648 	self.config.defname = self.config.defname or "home"
  1649 	self.config.deflang = self.config.deflang or "en"
  1650 	self.config.sessionmaxage = self.config.sessionmaxage or 6000
  1651 	self.config.secureport = self.config.secureport or 443
  1652 	self.config.passwdfile =
  1653 		posix.abspath(self.config.passwdfile or "../etc/passwd.lua")
  1654 	self.config.sessiondir =
  1655 		posix.abspath(self.config.sessiondir or "../var/sessions")
  1656 	self.config.extdir = posix.abspath(self.config.extdir or "../extensions")
  1657 	self.config.contentdir = posix.abspath(self.config.contentdir or "../content")
  1658 	self.config.localedir = posix.abspath(self.config.localedir or "../locale")
  1659 	self.config.htdocsdir = posix.abspath(self.config.htdocsdir or "../htdocs")
  1660 	self.config.htmlcachedir =
  1661 		posix.abspath(self.config.htmlcachedir or "../var/htmlcache")
  1662 	self.config.extlinkextra = self.config.extlinksamewindow and ' class="extlink"'
  1663 		or ' class="extlink" onclick="void(window.open(this.href, \'\', \'\')); return false;"'
  1664 
  1665 	-- Create proxy for on-demand loading of locales
  1666 
  1667 	self.locale = { }
  1668 	local locmt = { }
  1669 	locmt.__index = function(_, key)
  1670 		for _, l in ipairs(self.langs) do
  1671 			locmt.__locale = lib.source(self.config.localedir .. "/" .. l)
  1672 			if locmt.__locale then
  1673 				break
  1674 			end
  1675 		end
  1676 		locmt.__index = function(tab, key)
  1677 			return locmt.__locale[key] or key
  1678 		end
  1679 		return locmt.__locale[key] or key
  1680 	end
  1681 	setmetatable(self.locale, locmt)
  1682 
  1683 
  1684 	-- Get request, args, document, script name, request path
  1685 
  1686 	self.request = self.request or Request:new()
  1687 	self.args = self.request:getargs()
  1688 	self.cgi_document = self.request:getdocument()
  1689 
  1690 	self.requesthandler = self.requesthandler or self.cgi_document.Handler
  1691  	self.requestdocument = self.requestdocument or self.cgi_document.Name
  1692 	self.requestpath = self.requestpath or self.cgi_document.VirtualPath or false
  1693 	self.requestlang = self.requestlang or false
  1694 	self.explicitlang = not self.requestlang and self.args.lang or false
  1695 	self.secure = not self.insecure and (self.request.SERVER_PORT == self.config.secureport)
  1696 
  1697 	self.nologin = self.nologin or false
  1698 	self.authuser = false
  1699 
  1700 	-- Manage login and establish session
  1701 
  1702 	if not self.nologin then
  1703 		local sid = self.args.session or self.request.UNIQUE_ID
  1704 		self.session = self.session or Session:new {
  1705 			id = sid,
  1706 			sessiondir = self.config.sessiondir,
  1707 			maxage = self.config.sessionmaxage
  1708 		}
  1709 		if self.args.login then
  1710 			-- write back session ID into request args:
  1711 			self.args.session = sid -- !
  1712 			if self.args.login == "false" then
  1713 				self.session:delete()
  1714 				self.session = false
  1715 			elseif self.args.password then
  1716 				self.loginfailed = true
  1717 				local match, username, perm, profile =
  1718 					checkpw(self, self.args.login, self.args.password)
  1719 				if match then
  1720 					self.session.data.authuser = self.args.login
  1721 					self.session.data.username = username
  1722 					self.session.data.permissions = perm
  1723 					self.session.data.profile = profile
  1724 					self.session.data.id = self.session.id
  1725 					self.loginfailed = false
  1726 				end
  1727 			end
  1728 		end
  1729 		self.authuser = self.session and self.session.data.authuser
  1730 	end
  1731 
  1732 	if self.nologin or not self.authuser then
  1733 		self.authuser = false
  1734 		self.session = false
  1735 		self.args.session = false
  1736 		self.authuser_edit = false
  1737 		self.authuser_menu = false
  1738 		self.authuser_publish = false
  1739 		self.authuser_profile = false
  1740 		self.authuser_visible = false
  1741 		self.authuser_debug = false
  1742 		self.authuser_seeall = false
  1743 	else
  1744 		self.authuser_edit = self.session.data.permissions:find("e") and true
  1745 		self.authuser_menu = self.session.data.permissions:find("m") and true
  1746 		self.authuser_publish = self.session.data.permissions:find("p") and true
  1747 		self.authuser_profile = self.authuser_publish or
  1748 			self.session.data.permissions:find("c") and true
  1749 		self.authuser_visible = self.session.data.permissions:find("v") and true
  1750 		self.authuser_debug = self.session.data.permissions:find("d") and true
  1751 		self.authuser_seeall = self.session.data.permissions:find("a") and true
  1752 	end
  1753 
  1754 	self = Class.new(class, self)
  1755 
  1756 	-- Get lang, locale, profile, section
  1757 
  1758 	self:init()
  1759 
  1760 	if self.authuser then -- TODO?
  1761 		self:handlechanges()
  1762 	else
  1763 		self.args.profile = nil
  1764 	end
  1765 
  1766 	-- Current document
  1767 
  1768 	self.document = self.requestdocument .. "/" .. self.sectionpath
  1769 	assert(self.document ~= nil)
  1770 	if self.authuser then
  1771 		self.getdocname = getDocNameNoAuth
  1772 	else
  1773 		self.getdocname = getDocNameAuth
  1774 	end
  1775 
  1776 	-- Save session state
  1777 
  1778 	if self.session then
  1779 		self.session:save()
  1780 	end
  1781 
  1782 	return self
  1783 end
  1784 
  1785 
  1786 function Loona:getDocNameNoAuth(path)
  1787 	local url, anch = path:match("^([^#]*)(#?.*)$")
  1788 	path = url ~= "" and url
  1789 	anch = anch or ""
  1790 	return self.requestdocument .. "/" .. (path or self.sectionpath) .. anch
  1791 end
  1792 
  1793 
  1794 function Loona:getDocNameAuth(path, haveargs)
  1795 	local url, anch = path:match("^([^#]*)(#?.*)$")
  1796 	path = url ~= "" and url
  1797 	anch = anch or ""
  1798 	local dyn, exists
  1799 	dyn, path, exists = self:isdynamic(path or self.sectionpath)
  1800 	if dyn or haveargs or not exists then
  1801 		return self.requestdocument .. "/" .. path .. anch
  1802 	end
  1803 	path = path == self.config.defname and "index" or path
  1804 
  1805 	if path:match("%.html$") then
  1806 		return "/" .. path:gsub("/", "_") .. anch
  1807 	end
  1808 	return "/" .. path:gsub("/", "_") .. ".html" .. anch
  1809 end
  1810 
  1811 
  1812 function Loona.checkpw(self, login, passwd)
  1813 	local pwddb = lib.source(self.config.passwdfile)
  1814 	if pwddb then
  1815 		local pwdent = pwddb[login]
  1816 		if pwdent and pwdent.password == passwd then
  1817 			return true, pwdent.username or login,
  1818 				pwdent.permissions or "", pwdent.profile
  1819 		end
  1820 	end
  1821 end
  1822 
  1823 
  1824 function Loona:run(fname)
  1825 	self:indexdynamic()
  1826 	fname = fname or self.requesthandler
  1827 	local f = assert(open(fname), self:dbmsg("Handler not found", fname))
  1828 	local parsed, msg = self:loadhtml(f, "loona:out", fname)
  1829 	assert(parsed, self:dbmsg("HTML/Lua parsing failed", msg))
  1830 	self:runboxed(parsed)
  1831 	return self
  1832 end
  1833 
  1834 
  1835 function Loona:indexdynamic()
  1836 	self:recursesections(self.sections, function(self, s, e, path, dynamic)
  1837 		path = path and path .. "_" .. e.name or e.name
  1838 		dynamic = dynamic or { }
  1839 		for k in pairs(e.dynamic or { }) do
  1840 			dynamic[k] = true
  1841 		end
  1842 		for k in pairs(dynamic) do
  1843 			local ext = (k == "main" and "") or "." .. k
  1844 			if posix.stat(self.contentdir .. "/" .. path .. ext,
  1845 				"mode") == "file" then
  1846 				dynamic[k] = e.dynamic and e.dynamic[k]
  1847 			end
  1848 		end
  1849 		local n = 0
  1850 		for k in pairs(dynamic) do
  1851 			n = n + 1
  1852 		end
  1853 		if n > 0 then
  1854 			e.dynamic = { }
  1855 			for k in pairs(dynamic) do
  1856 				e.dynamic[k] = true
  1857 			end
  1858 		else
  1859 			e.dynamic = nil
  1860 		end
  1861 		return path, dynamic
  1862 	end)
  1863 end
  1864 
  1865 
  1866 function Loona:isdynamic(path)
  1867 	path = path or self.sectionpath
  1868 	local exists
  1869 	local t, i = self:checkpath(path)
  1870 	if t then
  1871 		exists = true
  1872 		if t[i].redirect then
  1873 			path = t[i].redirect
  1874 			t, i, exists = self:isdynamic(path) -- TODO: prohibit endless recursion
  1875 		end
  1876 	end
  1877 	if t then
  1878 		if t[i] then
  1879 			t = t[i].dynamic
  1880 		end
  1881 	end
  1882 	return t, path, exists
  1883 end
  1884 
  1885 
  1886 function Loona:dumphtml(o)
  1887 	local outbuf = { }
  1888 	o = o or { }
  1889 	o.nologin = true
  1890 	o.out = function(self, s) table.insert(outbuf, s) end
  1891 	o.addheader = function(self, s) end
  1892 
  1893 	o = self:new(o):run()
  1894 	if not o:isdynamic() then
  1895 		local path = o.sectionname
  1896 		path = path == o.config.defname and "index" or path
  1897 		local srcname = o.config.htdocsdir .. "/" .. path .. o.htmlext
  1898 		local fh, msg = open(srcname .. ".tmp", "wb")
  1899 		assert(fh, self:dbmsg("Could not write cached HTML", msg))
  1900 		for _, line in ipairs(outbuf) do
  1901 			fh:write(line)
  1902 		end
  1903 		fh:close()
  1904 		local dstname = o.config.htmlcachedir .. "/" .. path .. o.htmlext
  1905 		local success, msg = posix.symlink(srcname, dstname .. ".tmp")
  1906 		-- assert(success, self:dbmsg("Could not link to cached HTML", msg))
  1907 	end
  1908 end