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