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