Add last_login field to auth.txt
[oweals/minetest.git] / builtin / common / misc_helpers.lua
1 -- Minetest: builtin/misc_helpers.lua
2
3 --------------------------------------------------------------------------------
4 function basic_dump(o)
5         local tp = type(o)
6         if tp == "number" then
7                 return tostring(o)
8         elseif tp == "string" then
9                 return string.format("%q", o)
10         elseif tp == "boolean" then
11                 return tostring(o)
12         elseif tp == "nil" then
13                 return "nil"
14         -- Uncomment for full function dumping support.
15         -- Not currently enabled because bytecode isn't very human-readable and
16         -- dump's output is intended for humans.
17         --elseif tp == "function" then
18         --      return string.format("loadstring(%q)", string.dump(o))
19         else
20                 return string.format("<%s>", tp)
21         end
22 end
23
24 local keywords = {
25         ["and"] = true,
26         ["break"] = true,
27         ["do"] = true,
28         ["else"] = true,
29         ["elseif"] = true,
30         ["end"] = true,
31         ["false"] = true,
32         ["for"] = true,
33         ["function"] = true,
34         ["goto"] = true,  -- Lua 5.2
35         ["if"] = true,
36         ["in"] = true,
37         ["local"] = true,
38         ["nil"] = true,
39         ["not"] = true,
40         ["or"] = true,
41         ["repeat"] = true,
42         ["return"] = true,
43         ["then"] = true,
44         ["true"] = true,
45         ["until"] = true,
46         ["while"] = true,
47 }
48 local function is_valid_identifier(str)
49         if not str:find("^[a-zA-Z_][a-zA-Z0-9_]*$") or keywords[str] then
50                 return false
51         end
52         return true
53 end
54
55 --------------------------------------------------------------------------------
56 -- Dumps values in a line-per-value format.
57 -- For example, {test = {"Testing..."}} becomes:
58 --   _["test"] = {}
59 --   _["test"][1] = "Testing..."
60 -- This handles tables as keys and circular references properly.
61 -- It also handles multiple references well, writing the table only once.
62 -- The dumped argument is internal-only.
63
64 function dump2(o, name, dumped)
65         name = name or "_"
66         -- "dumped" is used to keep track of serialized tables to handle
67         -- multiple references and circular tables properly.
68         -- It only contains tables as keys.  The value is the name that
69         -- the table has in the dump, eg:
70         -- {x = {"y"}} -> dumped[{"y"}] = '_["x"]'
71         dumped = dumped or {}
72         if type(o) ~= "table" then
73                 return string.format("%s = %s\n", name, basic_dump(o))
74         end
75         if dumped[o] then
76                 return string.format("%s = %s\n", name, dumped[o])
77         end
78         dumped[o] = name
79         -- This contains a list of strings to be concatenated later (because
80         -- Lua is slow at individual concatenation).
81         local t = {}
82         for k, v in pairs(o) do
83                 local keyStr
84                 if type(k) == "table" then
85                         if dumped[k] then
86                                 keyStr = dumped[k]
87                         else
88                                 -- Key tables don't have a name, so use one of
89                                 -- the form _G["table: 0xFFFFFFF"]
90                                 keyStr = string.format("_G[%q]", tostring(k))
91                                 -- Dump key table
92                                 table.insert(t, dump2(k, keyStr, dumped))
93                         end
94                 else
95                         keyStr = basic_dump(k)
96                 end
97                 local vname = string.format("%s[%s]", name, keyStr)
98                 table.insert(t, dump2(v, vname, dumped))
99         end
100         return string.format("%s = {}\n%s", name, table.concat(t))
101 end
102
103 --------------------------------------------------------------------------------
104 -- This dumps values in a one-statement format.
105 -- For example, {test = {"Testing..."}} becomes:
106 -- [[{
107 --      test = {
108 --              "Testing..."
109 --      }
110 -- }]]
111 -- This supports tables as keys, but not circular references.
112 -- It performs poorly with multiple references as it writes out the full
113 -- table each time.
114 -- The indent field specifies a indentation string, it defaults to a tab.
115 -- Use the empty string to disable indentation.
116 -- The dumped and level arguments are internal-only.
117
118 function dump(o, indent, nested, level)
119         if type(o) ~= "table" then
120                 return basic_dump(o)
121         end
122         -- Contains table -> true/nil of currently nested tables
123         nested = nested or {}
124         if nested[o] then
125                 return "<circular reference>"
126         end
127         nested[o] = true
128         indent = indent or "\t"
129         level = level or 1
130         local t = {}
131         local dumped_indexes = {}
132         for i, v in ipairs(o) do
133                 table.insert(t, dump(v, indent, nested, level + 1))
134                 dumped_indexes[i] = true
135         end
136         for k, v in pairs(o) do
137                 if not dumped_indexes[k] then
138                         if type(k) ~= "string" or not is_valid_identifier(k) then
139                                 k = "["..dump(k, indent, nested, level + 1).."]"
140                         end
141                         v = dump(v, indent, nested, level + 1)
142                         table.insert(t, k.." = "..v)
143                 end
144         end
145         nested[o] = nil
146         if indent ~= "" then
147                 local indent_str = "\n"..string.rep(indent, level)
148                 local end_indent_str = "\n"..string.rep("\t", level - 1)
149                 return string.format("{%s%s%s}",
150                                 indent_str,
151                                 table.concat(t, ","..indent_str),
152                                 end_indent_str)
153         end
154         return "{"..table.concat(t, ", ").."}"
155 end
156
157 --------------------------------------------------------------------------------
158 function string.split(str, delim, include_empty, max_splits)
159         delim = delim or ","
160         max_splits = max_splits or 0
161         local fields = {}
162         local num_splits = 0
163         local last_pos = 0
164         for part, pos in str:gmatch("(.-)[" .. delim .. "]()") do
165                 last_pos = pos
166                 if include_empty or part ~= "" then
167                         num_splits = num_splits + 1
168                         fields[num_splits] = part
169                         if max_splits > 0 and num_splits + 1 >= max_splits then
170                                 break
171                         end
172                 end
173         end
174         -- Handle the last field
175         if max_splits <= 0 or num_splits <= max_splits then
176                 local last_part = str:sub(last_pos)
177                 if include_empty or last_part ~= "" then
178                         fields[num_splits + 1] = last_part
179                 end
180         end
181         return fields
182 end
183
184
185 --------------------------------------------------------------------------------
186 function file_exists(filename)
187         local f = io.open(filename, "r")
188         if f==nil then
189                 return false
190         else
191                 f:close()
192                 return true
193         end
194 end
195
196 --------------------------------------------------------------------------------
197 function string:trim()
198         return (self:gsub("^%s*(.-)%s*$", "%1"))
199 end
200
201 assert(string.trim("\n \t\tfoo bar\t ") == "foo bar")
202
203 --------------------------------------------------------------------------------
204 function math.hypot(x, y)
205         local t
206         x = math.abs(x)
207         y = math.abs(y)
208         t = math.min(x, y)
209         x = math.max(x, y)
210         if x == 0 then return 0 end
211         t = t / x
212         return x * math.sqrt(1 + t * t)
213 end
214
215 --------------------------------------------------------------------------------
216 function get_last_folder(text,count)
217         local parts = text:split(DIR_DELIM)
218
219         if count == nil then
220                 return parts[#parts]
221         end
222
223         local retval = ""
224         for i=1,count,1 do
225                 retval = retval .. parts[#parts - (count-i)] .. DIR_DELIM
226         end
227
228         return retval
229 end
230
231 --------------------------------------------------------------------------------
232 function cleanup_path(temppath)
233
234         local parts = temppath:split("-")
235         temppath = ""
236         for i=1,#parts,1 do
237                 if temppath ~= "" then
238                         temppath = temppath .. "_"
239                 end
240                 temppath = temppath .. parts[i]
241         end
242
243         parts = temppath:split(".")
244         temppath = ""
245         for i=1,#parts,1 do
246                 if temppath ~= "" then
247                         temppath = temppath .. "_"
248                 end
249                 temppath = temppath .. parts[i]
250         end
251
252         parts = temppath:split("'")
253         temppath = ""
254         for i=1,#parts,1 do
255                 if temppath ~= "" then
256                         temppath = temppath .. ""
257                 end
258                 temppath = temppath .. parts[i]
259         end
260
261         parts = temppath:split(" ")
262         temppath = ""
263         for i=1,#parts,1 do
264                 if temppath ~= "" then
265                         temppath = temppath
266                 end
267                 temppath = temppath .. parts[i]
268         end
269
270         return temppath
271 end
272
273 function core.formspec_escape(text)
274         if text ~= nil then
275                 text = string.gsub(text,"\\","\\\\")
276                 text = string.gsub(text,"%]","\\]")
277                 text = string.gsub(text,"%[","\\[")
278                 text = string.gsub(text,";","\\;")
279                 text = string.gsub(text,",","\\,")
280         end
281         return text
282 end
283
284
285 function core.splittext(text,charlimit)
286         local retval = {}
287
288         local current_idx = 1
289
290         local start,stop = string.find(text," ",current_idx)
291         local nl_start,nl_stop = string.find(text,"\n",current_idx)
292         local gotnewline = false
293         if nl_start ~= nil and (start == nil or nl_start < start) then
294                 start = nl_start
295                 stop = nl_stop
296                 gotnewline = true
297         end
298         local last_line = ""
299         while start ~= nil do
300                 if string.len(last_line) + (stop-start) > charlimit then
301                         table.insert(retval,last_line)
302                         last_line = ""
303                 end
304
305                 if last_line ~= "" then
306                         last_line = last_line .. " "
307                 end
308
309                 last_line = last_line .. string.sub(text,current_idx,stop -1)
310
311                 if gotnewline then
312                         table.insert(retval,last_line)
313                         last_line = ""
314                         gotnewline = false
315                 end
316                 current_idx = stop+1
317
318                 start,stop = string.find(text," ",current_idx)
319                 nl_start,nl_stop = string.find(text,"\n",current_idx)
320
321                 if nl_start ~= nil and (start == nil or nl_start < start) then
322                         start = nl_start
323                         stop = nl_stop
324                         gotnewline = true
325                 end
326         end
327
328         --add last part of text
329         if string.len(last_line) + (string.len(text) - current_idx) > charlimit then
330                         table.insert(retval,last_line)
331                         table.insert(retval,string.sub(text,current_idx))
332         else
333                 last_line = last_line .. " " .. string.sub(text,current_idx)
334                 table.insert(retval,last_line)
335         end
336
337         return retval
338 end
339
340 --------------------------------------------------------------------------------
341
342 if INIT == "game" then
343         local dirs1 = {9, 18, 7, 12}
344         local dirs2 = {20, 23, 22, 21}
345
346         function core.rotate_and_place(itemstack, placer, pointed_thing,
347                                 infinitestacks, orient_flags)
348                 orient_flags = orient_flags or {}
349
350                 local unode = core.get_node_or_nil(pointed_thing.under)
351                 if not unode then
352                         return
353                 end
354                 local undef = core.registered_nodes[unode.name]
355                 if undef and undef.on_rightclick then
356                         undef.on_rightclick(pointed_thing.under, unode, placer,
357                                         itemstack, pointed_thing)
358                         return
359                 end
360                 local pitch = placer:get_look_pitch()
361                 local fdir = core.dir_to_facedir(placer:get_look_dir())
362                 local wield_name = itemstack:get_name()
363
364                 local above = pointed_thing.above
365                 local under = pointed_thing.under
366                 local iswall = (above.y == under.y)
367                 local isceiling = not iswall and (above.y < under.y)
368                 local anode = core.get_node_or_nil(above)
369                 if not anode then
370                         return
371                 end
372                 local pos = pointed_thing.above
373                 local node = anode
374
375                 if undef and undef.buildable_to then
376                         pos = pointed_thing.under
377                         node = unode
378                         iswall = false
379                 end
380
381                 if core.is_protected(pos, placer:get_player_name()) then
382                         core.record_protection_violation(pos,
383                                         placer:get_player_name())
384                         return
385                 end
386
387                 local ndef = core.registered_nodes[node.name]
388                 if not ndef or not ndef.buildable_to then
389                         return
390                 end
391
392                 if orient_flags.force_floor then
393                         iswall = false
394                         isceiling = false
395                 elseif orient_flags.force_ceiling then
396                         iswall = false
397                         isceiling = true
398                 elseif orient_flags.force_wall then
399                         iswall = true
400                         isceiling = false
401                 elseif orient_flags.invert_wall then
402                         iswall = not iswall
403                 end
404
405                 if iswall then
406                         core.set_node(pos, {name = wield_name,
407                                         param2 = dirs1[fdir+1]})
408                 elseif isceiling then
409                         if orient_flags.force_facedir then
410                                 core.set_node(pos, {name = wield_name,
411                                                 param2 = 20})
412                         else
413                                 core.set_node(pos, {name = wield_name,
414                                                 param2 = dirs2[fdir+1]})
415                         end
416                 else -- place right side up
417                         if orient_flags.force_facedir then
418                                 core.set_node(pos, {name = wield_name,
419                                                 param2 = 0})
420                         else
421                                 core.set_node(pos, {name = wield_name,
422                                                 param2 = fdir})
423                         end
424                 end
425
426                 if not infinitestacks then
427                         itemstack:take_item()
428                         return itemstack
429                 end
430         end
431
432
433 --------------------------------------------------------------------------------
434 --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
435 --implies infinite stacks when performing a 6d rotation.
436 --------------------------------------------------------------------------------
437
438
439         core.rotate_node = function(itemstack, placer, pointed_thing)
440                 core.rotate_and_place(itemstack, placer, pointed_thing,
441                                 core.setting_getbool("creative_mode"),
442                                 {invert_wall = placer:get_player_control().sneak})
443                 return itemstack
444         end
445 end
446
447 --------------------------------------------------------------------------------
448 function core.explode_table_event(evt)
449         if evt ~= nil then
450                 local parts = evt:split(":")
451                 if #parts == 3 then
452                         local t = parts[1]:trim()
453                         local r = tonumber(parts[2]:trim())
454                         local c = tonumber(parts[3]:trim())
455                         if type(r) == "number" and type(c) == "number" and t ~= "INV" then
456                                 return {type=t, row=r, column=c}
457                         end
458                 end
459         end
460         return {type="INV", row=0, column=0}
461 end
462
463 --------------------------------------------------------------------------------
464 function core.explode_textlist_event(evt)
465         if evt ~= nil then
466                 local parts = evt:split(":")
467                 if #parts == 2 then
468                         local t = parts[1]:trim()
469                         local r = tonumber(parts[2]:trim())
470                         if type(r) == "number" and t ~= "INV" then
471                                 return {type=t, index=r}
472                         end
473                 end
474         end
475         return {type="INV", index=0}
476 end
477
478 --------------------------------------------------------------------------------
479 function core.explode_scrollbar_event(evt)
480         local retval = core.explode_textlist_event(evt)
481
482         retval.value = retval.index
483         retval.index = nil
484
485         return retval
486 end
487
488 --------------------------------------------------------------------------------
489 function core.pos_to_string(pos)
490         return "(" .. pos.x .. "," .. pos.y .. "," .. pos.z .. ")"
491 end
492
493 --------------------------------------------------------------------------------
494 -- mainmenu only functions
495 --------------------------------------------------------------------------------
496 if INIT == "mainmenu" then
497         function core.get_game(index)
498                 local games = game.get_games()
499
500                 if index > 0 and index <= #games then
501                         return games[index]
502                 end
503
504                 return nil
505         end
506
507         function fgettext(text, ...)
508                 text = core.gettext(text)
509                 local arg = {n=select('#', ...), ...}
510                 if arg.n >= 1 then
511                         -- Insert positional parameters ($1, $2, ...)
512                         result = ''
513                         pos = 1
514                         while pos <= text:len() do
515                                 newpos = text:find('[$]', pos)
516                                 if newpos == nil then
517                                         result = result .. text:sub(pos)
518                                         pos = text:len() + 1
519                                 else
520                                         paramindex = tonumber(text:sub(newpos+1, newpos+1))
521                                         result = result .. text:sub(pos, newpos-1) .. tostring(arg[paramindex])
522                                         pos = newpos + 2
523                                 end
524                         end
525                         text = result
526                 end
527                 return core.formspec_escape(text)
528         end
529 end
530