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