Add consistent monotonic day counter - get_day_count()
[oweals/minetest.git] / builtin / game / chatcommands.lua
1 -- Minetest: builtin/chatcommands.lua
2
3 --
4 -- Chat command handler
5 --
6
7 core.chatcommands = {}
8 function core.register_chatcommand(cmd, def)
9         def = def or {}
10         def.params = def.params or ""
11         def.description = def.description or ""
12         def.privs = def.privs or {}
13         def.mod_origin = core.get_current_modname() or "??"
14         core.chatcommands[cmd] = def
15 end
16
17 if core.setting_getbool("mod_profiling") then
18         local tracefct = profiling_print_log
19         profiling_print_log = nil
20         core.register_chatcommand("save_mod_profile",
21                         {
22                                 params      = "",
23                                 description = "save mod profiling data to logfile " ..
24                                                 "(depends on default loglevel)",
25                                 func        = tracefct,
26                                 privs       = { server=true }
27                         })
28 end
29
30 core.register_on_chat_message(function(name, message)
31         local cmd, param = string.match(message, "^/([^ ]+) *(.*)")
32         if not param then
33                 param = ""
34         end
35         local cmd_def = core.chatcommands[cmd]
36         if not cmd_def then
37                 return false
38         end
39         local has_privs, missing_privs = core.check_player_privs(name, cmd_def.privs)
40         if has_privs then
41                 core.set_last_run_mod(cmd_def.mod_origin)
42                 local success, message = cmd_def.func(name, param)
43                 if message then
44                         core.chat_send_player(name, message)
45                 end
46         else
47                 core.chat_send_player(name, "You don't have permission"
48                                 .. " to run this command (missing privileges: "
49                                 .. table.concat(missing_privs, ", ") .. ")")
50         end
51         return true  -- Handled chat message
52 end)
53
54 -- Parses a "range" string in the format of "here (number)" or
55 -- "(x1, y1, z1) (x2, y2, z2)", returning two position vectors
56 local function parse_range_str(player_name, str)
57         local p1, p2
58         local args = str:split(" ")
59
60         if args[1] == "here" then
61                 p1, p2 = core.get_player_radius_area(player_name, tonumber(args[2]))
62                 if p1 == nil then
63                         return false, "Unable to get player " .. player_name .. " position"
64                 end
65         else
66                 p1, p2 = core.string_to_area(str)
67                 if p1 == nil then
68                         return false, "Incorrect area format. Expected: (x1,y1,z1) (x2,y2,z2)"
69                 end
70         end
71
72         return p1, p2
73 end
74
75 --
76 -- Chat commands
77 --
78 core.register_chatcommand("me", {
79         params = "<action>",
80         description = "chat action (eg. /me orders a pizza)",
81         privs = {shout=true},
82         func = function(name, param)
83                 core.chat_send_all("* " .. name .. " " .. param)
84         end,
85 })
86
87 core.register_chatcommand("admin", {
88         description = "Show the name of the server owner",
89         func = function(name)
90                 local admin = minetest.setting_get("name")
91                 if admin then
92                         return true, "The administrator of this server is "..admin.."."
93                 else
94                         return false, "There's no administrator named in the config file."
95                 end
96         end,
97 })
98
99 core.register_chatcommand("help", {
100         privs = {},
101         params = "[all/privs/<cmd>]",
102         description = "Get help for commands or list privileges",
103         func = function(name, param)
104                 local function format_help_line(cmd, def)
105                         local msg = "/"..cmd
106                         if def.params and def.params ~= "" then
107                                 msg = msg .. " " .. def.params
108                         end
109                         if def.description and def.description ~= "" then
110                                 msg = msg .. ": " .. def.description
111                         end
112                         return msg
113                 end
114                 if param == "" then
115                         local msg = ""
116                         local cmds = {}
117                         for cmd, def in pairs(core.chatcommands) do
118                                 if core.check_player_privs(name, def.privs) then
119                                         cmds[#cmds + 1] = cmd
120                                 end
121                         end
122                         table.sort(cmds)
123                         return true, "Available commands: " .. table.concat(cmds, " ") .. "\n"
124                                         .. "Use '/help <cmd>' to get more information,"
125                                         .. " or '/help all' to list everything."
126                 elseif param == "all" then
127                         local cmds = {}
128                         for cmd, def in pairs(core.chatcommands) do
129                                 if core.check_player_privs(name, def.privs) then
130                                         cmds[#cmds + 1] = format_help_line(cmd, def)
131                                 end
132                         end
133                         table.sort(cmds)
134                         return true, "Available commands:\n"..table.concat(cmds, "\n")
135                 elseif param == "privs" then
136                         local privs = {}
137                         for priv, def in pairs(core.registered_privileges) do
138                                 privs[#privs + 1] = priv .. ": " .. def.description
139                         end
140                         table.sort(privs)
141                         return true, "Available privileges:\n"..table.concat(privs, "\n")
142                 else
143                         local cmd = param
144                         local def = core.chatcommands[cmd]
145                         if not def then
146                                 return false, "Command not available: "..cmd
147                         else
148                                 return true, format_help_line(cmd, def)
149                         end
150                 end
151         end,
152 })
153
154 core.register_chatcommand("privs", {
155         params = "<name>",
156         description = "print out privileges of player",
157         func = function(name, param)
158                 param = (param ~= "" and param or name)
159                 return true, "Privileges of " .. param .. ": "
160                         .. core.privs_to_string(
161                                 core.get_player_privs(param), ' ')
162         end,
163 })
164 core.register_chatcommand("grant", {
165         params = "<name> <privilege>|all",
166         description = "Give privilege to player",
167         func = function(name, param)
168                 if not core.check_player_privs(name, {privs=true}) and
169                                 not core.check_player_privs(name, {basic_privs=true}) then
170                         return false, "Your privileges are insufficient."
171                 end
172                 local grantname, grantprivstr = string.match(param, "([^ ]+) (.+)")
173                 if not grantname or not grantprivstr then
174                         return false, "Invalid parameters (see /help grant)"
175                 elseif not core.auth_table[grantname] then
176                         return false, "Player " .. grantname .. " does not exist."
177                 end
178                 local grantprivs = core.string_to_privs(grantprivstr)
179                 if grantprivstr == "all" then
180                         grantprivs = core.registered_privileges
181                 end
182                 local privs = core.get_player_privs(grantname)
183                 local privs_unknown = ""
184                 for priv, _ in pairs(grantprivs) do
185                         if priv ~= "interact" and priv ~= "shout" and
186                                         not core.check_player_privs(name, {privs=true}) then
187                                 return false, "Your privileges are insufficient."
188                         end
189                         if not core.registered_privileges[priv] then
190                                 privs_unknown = privs_unknown .. "Unknown privilege: " .. priv .. "\n"
191                         end
192                         privs[priv] = true
193                 end
194                 if privs_unknown ~= "" then
195                         return false, privs_unknown
196                 end
197                 core.set_player_privs(grantname, privs)
198                 core.log("action", name..' granted ('..core.privs_to_string(grantprivs, ', ')..') privileges to '..grantname)
199                 if grantname ~= name then
200                         core.chat_send_player(grantname, name
201                                         .. " granted you privileges: "
202                                         .. core.privs_to_string(grantprivs, ' '))
203                 end
204                 return true, "Privileges of " .. grantname .. ": "
205                         .. core.privs_to_string(
206                                 core.get_player_privs(grantname), ' ')
207         end,
208 })
209 core.register_chatcommand("revoke", {
210         params = "<name> <privilege>|all",
211         description = "Remove privilege from player",
212         privs = {},
213         func = function(name, param)
214                 if not core.check_player_privs(name, {privs=true}) and
215                                 not core.check_player_privs(name, {basic_privs=true}) then
216                         return false, "Your privileges are insufficient."
217                 end
218                 local revoke_name, revoke_priv_str = string.match(param, "([^ ]+) (.+)")
219                 if not revoke_name or not revoke_priv_str then
220                         return false, "Invalid parameters (see /help revoke)"
221                 elseif not core.auth_table[revoke_name] then
222                         return false, "Player " .. revoke_name .. " does not exist."
223                 end
224                 local revoke_privs = core.string_to_privs(revoke_priv_str)
225                 local privs = core.get_player_privs(revoke_name)
226                 for priv, _ in pairs(revoke_privs) do
227                         if priv ~= "interact" and priv ~= "shout" and
228                                         not core.check_player_privs(name, {privs=true}) then
229                                 return false, "Your privileges are insufficient."
230                         end
231                 end
232                 if revoke_priv_str == "all" then
233                         privs = {}
234                 else
235                         for priv, _ in pairs(revoke_privs) do
236                                 privs[priv] = nil
237                         end
238                 end
239                 core.set_player_privs(revoke_name, privs)
240                 core.log("action", name..' revoked ('
241                                 ..core.privs_to_string(revoke_privs, ', ')
242                                 ..') privileges from '..revoke_name)
243                 if revoke_name ~= name then
244                         core.chat_send_player(revoke_name, name
245                                         .. " revoked privileges from you: "
246                                         .. core.privs_to_string(revoke_privs, ' '))
247                 end
248                 return true, "Privileges of " .. revoke_name .. ": "
249                         .. core.privs_to_string(
250                                 core.get_player_privs(revoke_name), ' ')
251         end,
252 })
253
254 core.register_chatcommand("setpassword", {
255         params = "<name> <password>",
256         description = "set given password",
257         privs = {password=true},
258         func = function(name, param)
259                 local toname, raw_password = string.match(param, "^([^ ]+) +(.+)$")
260                 if not toname then
261                         toname = param:match("^([^ ]+) *$")
262                         raw_password = nil
263                 end
264                 if not toname then
265                         return false, "Name field required"
266                 end
267                 local act_str_past = "?"
268                 local act_str_pres = "?"
269                 if not raw_password then
270                         core.set_player_password(toname, "")
271                         act_str_past = "cleared"
272                         act_str_pres = "clears"
273                 else
274                         core.set_player_password(toname,
275                                         core.get_password_hash(toname,
276                                                         raw_password))
277                         act_str_past = "set"
278                         act_str_pres = "sets"
279                 end
280                 if toname ~= name then
281                         core.chat_send_player(toname, "Your password was "
282                                         .. act_str_past .. " by " .. name)
283                 end
284
285                 core.log("action", name .. " " .. act_str_pres
286                 .. " password of " .. toname .. ".")
287
288                 return true, "Password of player \"" .. toname .. "\" " .. act_str_past
289         end,
290 })
291
292 core.register_chatcommand("clearpassword", {
293         params = "<name>",
294         description = "set empty password",
295         privs = {password=true},
296         func = function(name, param)
297                 local toname = param
298                 if toname == "" then
299                         return false, "Name field required"
300                 end
301                 core.set_player_password(toname, '')
302
303                 core.log("action", name .. " clears password of " .. toname .. ".")
304
305                 return true, "Password of player \"" .. toname .. "\" cleared"
306         end,
307 })
308
309 core.register_chatcommand("auth_reload", {
310         params = "",
311         description = "reload authentication data",
312         privs = {server=true},
313         func = function(name, param)
314                 local done = core.auth_reload()
315                 return done, (done and "Done." or "Failed.")
316         end,
317 })
318
319 core.register_chatcommand("teleport", {
320         params = "<X>,<Y>,<Z> | <to_name> | <name> <X>,<Y>,<Z> | <name> <to_name>",
321         description = "teleport to given position",
322         privs = {teleport=true},
323         func = function(name, param)
324                 -- Returns (pos, true) if found, otherwise (pos, false)
325                 local function find_free_position_near(pos)
326                         local tries = {
327                                 {x=1,y=0,z=0},
328                                 {x=-1,y=0,z=0},
329                                 {x=0,y=0,z=1},
330                                 {x=0,y=0,z=-1},
331                         }
332                         for _, d in ipairs(tries) do
333                                 local p = {x = pos.x+d.x, y = pos.y+d.y, z = pos.z+d.z}
334                                 local n = core.get_node_or_nil(p)
335                                 if n and n.name then
336                                         local def = core.registered_nodes[n.name]
337                                         if def and not def.walkable then
338                                                 return p, true
339                                         end
340                                 end
341                         end
342                         return pos, false
343                 end
344
345                 local teleportee = nil
346                 local p = {}
347                 p.x, p.y, p.z = string.match(param, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
348                 p.x = tonumber(p.x)
349                 p.y = tonumber(p.y)
350                 p.z = tonumber(p.z)
351                 teleportee = core.get_player_by_name(name)
352                 if teleportee and p.x and p.y and p.z then
353                         teleportee:setpos(p)
354                         return true, "Teleporting to "..core.pos_to_string(p)
355                 end
356
357                 local teleportee = nil
358                 local p = nil
359                 local target_name = nil
360                 target_name = param:match("^([^ ]+)$")
361                 teleportee = core.get_player_by_name(name)
362                 if target_name then
363                         local target = core.get_player_by_name(target_name)
364                         if target then
365                                 p = target:getpos()
366                         end
367                 end
368                 if teleportee and p then
369                         p = find_free_position_near(p)
370                         teleportee:setpos(p)
371                         return true, "Teleporting to " .. target_name
372                                         .. " at "..core.pos_to_string(p)
373                 end
374
375                 if not core.check_player_privs(name, {bring=true}) then
376                         return false, "You don't have permission to teleport other players (missing bring privilege)"
377                 end
378
379                 local teleportee = nil
380                 local p = {}
381                 local teleportee_name = nil
382                 teleportee_name, p.x, p.y, p.z = param:match(
383                                 "^([^ ]+) +([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
384                 p.x, p.y, p.z = tonumber(p.x), tonumber(p.y), tonumber(p.z)
385                 if teleportee_name then
386                         teleportee = core.get_player_by_name(teleportee_name)
387                 end
388                 if teleportee and p.x and p.y and p.z then
389                         teleportee:setpos(p)
390                         return true, "Teleporting " .. teleportee_name
391                                         .. " to " .. core.pos_to_string(p)
392                 end
393
394                 local teleportee = nil
395                 local p = nil
396                 local teleportee_name = nil
397                 local target_name = nil
398                 teleportee_name, target_name = string.match(param, "^([^ ]+) +([^ ]+)$")
399                 if teleportee_name then
400                         teleportee = core.get_player_by_name(teleportee_name)
401                 end
402                 if target_name then
403                         local target = core.get_player_by_name(target_name)
404                         if target then
405                                 p = target:getpos()
406                         end
407                 end
408                 if teleportee and p then
409                         p = find_free_position_near(p)
410                         teleportee:setpos(p)
411                         return true, "Teleporting " .. teleportee_name
412                                         .. " to " .. target_name
413                                         .. " at " .. core.pos_to_string(p)
414                 end
415
416                 return false, 'Invalid parameters ("' .. param
417                                 .. '") or player not found (see /help teleport)'
418         end,
419 })
420
421 core.register_chatcommand("set", {
422         params = "[-n] <name> <value> | <name>",
423         description = "set or read server configuration setting",
424         privs = {server=true},
425         func = function(name, param)
426                 local arg, setname, setvalue = string.match(param, "(-[n]) ([^ ]+) (.+)")
427                 if arg and arg == "-n" and setname and setvalue then
428                         core.setting_set(setname, setvalue)
429                         return true, setname .. " = " .. setvalue
430                 end
431                 local setname, setvalue = string.match(param, "([^ ]+) (.+)")
432                 if setname and setvalue then
433                         if not core.setting_get(setname) then
434                                 return false, "Failed. Use '/set -n <name> <value>' to create a new setting."
435                         end
436                         core.setting_set(setname, setvalue)
437                         return true, setname .. " = " .. setvalue
438                 end
439                 local setname = string.match(param, "([^ ]+)")
440                 if setname then
441                         local setvalue = core.setting_get(setname)
442                         if not setvalue then
443                                 setvalue = "<not set>"
444                         end
445                         return true, setname .. " = " .. setvalue
446                 end
447                 return false, "Invalid parameters (see /help set)."
448         end,
449 })
450
451 local function emergeblocks_callback(pos, action, num_calls_remaining, ctx)
452         if ctx.total_blocks == 0 then
453                 ctx.total_blocks   = num_calls_remaining + 1
454                 ctx.current_blocks = 0
455         end
456         ctx.current_blocks = ctx.current_blocks + 1
457
458         if ctx.current_blocks == ctx.total_blocks then
459                 core.chat_send_player(ctx.requestor_name,
460                         string.format("Finished emerging %d blocks in %.2fms.",
461                         ctx.total_blocks, (os.clock() - ctx.start_time) * 1000))
462         end
463 end
464
465 local function emergeblocks_progress_update(ctx)
466         if ctx.current_blocks ~= ctx.total_blocks then
467                 core.chat_send_player(ctx.requestor_name,
468                         string.format("emergeblocks update: %d/%d blocks emerged (%.1f%%)",
469                         ctx.current_blocks, ctx.total_blocks,
470                         (ctx.current_blocks / ctx.total_blocks) * 100))
471
472                 core.after(2, emergeblocks_progress_update, ctx)
473         end
474 end
475
476 core.register_chatcommand("emergeblocks", {
477         params = "(here [radius]) | (<pos1> <pos2>)",
478         description = "starts loading (or generating, if inexistent) map blocks "
479                 .. "contained in area pos1 to pos2",
480         privs = {server=true},
481         func = function(name, param)
482                 local p1, p2 = parse_range_str(name, param)
483                 if p1 == false then
484                         return false, p2
485                 end
486
487                 local context = {
488                         current_blocks = 0,
489                         total_blocks   = 0,
490                         start_time     = os.clock(),
491                         requestor_name = name
492                 }
493
494                 core.emerge_area(p1, p2, emergeblocks_callback, context)
495                 core.after(2, emergeblocks_progress_update, context)
496
497                 return true, "Started emerge of area ranging from " ..
498                         core.pos_to_string(p1, 1) .. " to " .. core.pos_to_string(p2, 1)
499         end,
500 })
501
502 core.register_chatcommand("deleteblocks", {
503         params = "(here [radius]) | (<pos1> <pos2>)",
504         description = "delete map blocks contained in area pos1 to pos2",
505         privs = {server=true},
506         func = function(name, param)
507                 local p1, p2 = parse_range_str(name, param)
508                 if p1 == false then
509                         return false, p2
510                 end
511
512                 if core.delete_area(p1, p2) then
513                         return true, "Successfully cleared area ranging from " ..
514                                 core.pos_to_string(p1, 1) .. " to " .. core.pos_to_string(p2, 1)
515                 else
516                         return false, "Failed to clear one or more blocks in area"
517                 end
518         end,
519 })
520
521 core.register_chatcommand("mods", {
522         params = "",
523         description = "List mods installed on the server",
524         privs = {},
525         func = function(name, param)
526                 return true, table.concat(core.get_modnames(), ", ")
527         end,
528 })
529
530 local function handle_give_command(cmd, giver, receiver, stackstring)
531         core.log("action", giver .. " invoked " .. cmd
532                         .. ', stackstring="' .. stackstring .. '"')
533         local itemstack = ItemStack(stackstring)
534         if itemstack:is_empty() then
535                 return false, "Cannot give an empty item"
536         elseif not itemstack:is_known() then
537                 return false, "Cannot give an unknown item"
538         end
539         local receiverref = core.get_player_by_name(receiver)
540         if receiverref == nil then
541                 return false, receiver .. " is not a known player"
542         end
543         local leftover = receiverref:get_inventory():add_item("main", itemstack)
544         local partiality
545         if leftover:is_empty() then
546                 partiality = ""
547         elseif leftover:get_count() == itemstack:get_count() then
548                 partiality = "could not be "
549         else
550                 partiality = "partially "
551         end
552         -- The actual item stack string may be different from what the "giver"
553         -- entered (e.g. big numbers are always interpreted as 2^16-1).
554         stackstring = itemstack:to_string()
555         if giver == receiver then
556                 return true, ("%q %sadded to inventory.")
557                                 :format(stackstring, partiality)
558         else
559                 core.chat_send_player(receiver, ("%q %sadded to inventory.")
560                                 :format(stackstring, partiality))
561                 return true, ("%q %sadded to %s's inventory.")
562                                 :format(stackstring, partiality, receiver)
563         end
564 end
565
566 core.register_chatcommand("give", {
567         params = "<name> <ItemString>",
568         description = "give item to player",
569         privs = {give=true},
570         func = function(name, param)
571                 local toname, itemstring = string.match(param, "^([^ ]+) +(.+)$")
572                 if not toname or not itemstring then
573                         return false, "Name and ItemString required"
574                 end
575                 return handle_give_command("/give", name, toname, itemstring)
576         end,
577 })
578
579 core.register_chatcommand("giveme", {
580         params = "<ItemString>",
581         description = "give item to yourself",
582         privs = {give=true},
583         func = function(name, param)
584                 local itemstring = string.match(param, "(.+)$")
585                 if not itemstring then
586                         return false, "ItemString required"
587                 end
588                 return handle_give_command("/giveme", name, name, itemstring)
589         end,
590 })
591
592 core.register_chatcommand("spawnentity", {
593         params = "<EntityName> [<X>,<Y>,<Z>]",
594         description = "Spawn entity at given (or your) position",
595         privs = {give=true, interact=true},
596         func = function(name, param)
597                 local entityname, p = string.match(param, "^([^ ]+) *(.*)$")
598                 if not entityname then
599                         return false, "EntityName required"
600                 end
601                 core.log("action", ("%s invokes /spawnentity, entityname=%q")
602                                 :format(name, entityname))
603                 local player = core.get_player_by_name(name)
604                 if player == nil then
605                         core.log("error", "Unable to spawn entity, player is nil")
606                         return false, "Unable to spawn entity, player is nil"
607                 end
608                 if p == "" then
609                         p = player:getpos()
610                 else
611                         p = core.string_to_pos(p)
612                         if p == nil then
613                                 return false, "Invalid parameters ('" .. param .. "')"
614                         end
615                 end
616                 p.y = p.y + 1
617                 core.add_entity(p, entityname)
618                 return true, ("%q spawned."):format(entityname)
619         end,
620 })
621
622 core.register_chatcommand("pulverize", {
623         params = "",
624         description = "Destroy item in hand",
625         func = function(name, param)
626                 local player = core.get_player_by_name(name)
627                 if not player then
628                         core.log("error", "Unable to pulverize, no player.")
629                         return false, "Unable to pulverize, no player."
630                 end
631                 if player:get_wielded_item():is_empty() then
632                         return false, "Unable to pulverize, no item in hand."
633                 end
634                 player:set_wielded_item(nil)
635                 return true, "An item was pulverized."
636         end,
637 })
638
639 -- Key = player name
640 core.rollback_punch_callbacks = {}
641
642 core.register_on_punchnode(function(pos, node, puncher)
643         local name = puncher:get_player_name()
644         if core.rollback_punch_callbacks[name] then
645                 core.rollback_punch_callbacks[name](pos, node, puncher)
646                 core.rollback_punch_callbacks[name] = nil
647         end
648 end)
649
650 core.register_chatcommand("rollback_check", {
651         params = "[<range>] [<seconds>] [limit]",
652         description = "Check who has last touched a node or near it,"
653                         .. " max. <seconds> ago (default range=0,"
654                         .. " seconds=86400=24h, limit=5)",
655         privs = {rollback=true},
656         func = function(name, param)
657                 if not core.setting_getbool("enable_rollback_recording") then
658                         return false, "Rollback functions are disabled."
659                 end
660                 local range, seconds, limit =
661                         param:match("(%d+) *(%d*) *(%d*)")
662                 range = tonumber(range) or 0
663                 seconds = tonumber(seconds) or 86400
664                 limit = tonumber(limit) or 5
665                 if limit > 100 then
666                         return false, "That limit is too high!"
667                 end
668
669                 core.rollback_punch_callbacks[name] = function(pos, node, puncher)
670                         local name = puncher:get_player_name()
671                         core.chat_send_player(name, "Checking " .. core.pos_to_string(pos) .. "...")
672                         local actions = core.rollback_get_node_actions(pos, range, seconds, limit)
673                         if not actions then
674                                 core.chat_send_player(name, "Rollback functions are disabled")
675                                 return
676                         end
677                         local num_actions = #actions
678                         if num_actions == 0 then
679                                 core.chat_send_player(name, "Nobody has touched"
680                                                 .. " the specified location in "
681                                                 .. seconds .. " seconds")
682                                 return
683                         end
684                         local time = os.time()
685                         for i = num_actions, 1, -1 do
686                                 local action = actions[i]
687                                 core.chat_send_player(name,
688                                         ("%s %s %s -> %s %d seconds ago.")
689                                                 :format(
690                                                         core.pos_to_string(action.pos),
691                                                         action.actor,
692                                                         action.oldnode.name,
693                                                         action.newnode.name,
694                                                         time - action.time))
695                         end
696                 end
697
698                 return true, "Punch a node (range=" .. range .. ", seconds="
699                                 .. seconds .. "s, limit=" .. limit .. ")"
700         end,
701 })
702
703 core.register_chatcommand("rollback", {
704         params = "<player name> [<seconds>] | :<actor> [<seconds>]",
705         description = "revert actions of a player; default for <seconds> is 60",
706         privs = {rollback=true},
707         func = function(name, param)
708                 if not core.setting_getbool("enable_rollback_recording") then
709                         return false, "Rollback functions are disabled."
710                 end
711                 local target_name, seconds = string.match(param, ":([^ ]+) *(%d*)")
712                 if not target_name then
713                         local player_name = nil
714                         player_name, seconds = string.match(param, "([^ ]+) *(%d*)")
715                         if not player_name then
716                                 return false, "Invalid parameters. See /help rollback"
717                                                 .. " and /help rollback_check."
718                         end
719                         target_name = "player:"..player_name
720                 end
721                 seconds = tonumber(seconds) or 60
722                 core.chat_send_player(name, "Reverting actions of "
723                                 .. target_name .. " since "
724                                 .. seconds .. " seconds.")
725                 local success, log = core.rollback_revert_actions_by(
726                                 target_name, seconds)
727                 local response = ""
728                 if #log > 100 then
729                         response = "(log is too long to show)\n"
730                 else
731                         for _, line in pairs(log) do
732                                 response = response .. line .. "\n"
733                         end
734                 end
735                 response = response .. "Reverting actions "
736                                 .. (success and "succeeded." or "FAILED.")
737                 return success, response
738         end,
739 })
740
741 core.register_chatcommand("status", {
742         description = "Print server status",
743         func = function(name, param)
744                 return true, core.get_server_status()
745         end,
746 })
747
748 core.register_chatcommand("time", {
749         params = "<0..23>:<0..59> | <0..24000>",
750         description = "set time of day",
751         privs = {},
752         func = function(name, param)
753                 if param == "" then
754                         local current_time = math.floor(core.get_timeofday() * 1440)
755                         local minutes = current_time % 60
756                         local hour = (current_time - minutes) / 60
757                         return true, ("Current time is %d:%02d"):format(hour, minutes)
758                 end
759                 local player_privs = core.get_player_privs(name)
760                 if not player_privs.settime then
761                         return false, "You don't have permission to run this command " ..
762                                 "(missing privilege: settime)."
763                 end
764                 local hour, minute = param:match("^(%d+):(%d+)$")
765                 if not hour then
766                         local new_time = tonumber(param)
767                         if not new_time then
768                                 return false, "Invalid time."
769                         end
770                         -- Backward compatibility.
771                         core.set_timeofday((new_time % 24000) / 24000)
772                         core.log("action", name .. " sets time to " .. new_time)
773                         return true, "Time of day changed."
774                 end
775                 hour = tonumber(hour)
776                 minute = tonumber(minute)
777                 if hour < 0 or hour > 23 then
778                         return false, "Invalid hour (must be between 0 and 23 inclusive)."
779                 elseif minute < 0 or minute > 59 then
780                         return false, "Invalid minute (must be between 0 and 59 inclusive)."
781                 end
782                 core.set_timeofday((hour * 60 + minute) / 1440)
783                 core.log("action", ("%s sets time to %d:%02d"):format(name, hour, minute))
784                 return true, "Time of day changed."
785         end,
786 })
787
788 core.register_chatcommand("days", {
789         description = "Display day count",
790         func = function(name, param)
791                 return true, "Current day is " .. core.get_day_count()
792         end
793 })
794
795 core.register_chatcommand("shutdown", {
796         description = "shutdown server",
797         privs = {server=true},
798         func = function(name, param)
799                 core.log("action", name .. " shuts down server")
800                 core.request_shutdown()
801                 core.chat_send_all("*** Server shutting down (operator request).")
802         end,
803 })
804
805 core.register_chatcommand("ban", {
806         params = "<name>",
807         description = "Ban IP of player",
808         privs = {ban=true},
809         func = function(name, param)
810                 if param == "" then
811                         return true, "Ban list: " .. core.get_ban_list()
812                 end
813                 if not core.get_player_by_name(param) then
814                         return false, "No such player."
815                 end
816                 if not core.ban_player(param) then
817                         return false, "Failed to ban player."
818                 end
819                 local desc = core.get_ban_description(param)
820                 core.log("action", name .. " bans " .. desc .. ".")
821                 return true, "Banned " .. desc .. "."
822         end,
823 })
824
825 core.register_chatcommand("unban", {
826         params = "<name/ip>",
827         description = "remove IP ban",
828         privs = {ban=true},
829         func = function(name, param)
830                 if not core.unban_player_or_ip(param) then
831                         return false, "Failed to unban player/IP."
832                 end
833                 core.log("action", name .. " unbans " .. param)
834                 return true, "Unbanned " .. param
835         end,
836 })
837
838 core.register_chatcommand("kick", {
839         params = "<name> [reason]",
840         description = "kick a player",
841         privs = {kick=true},
842         func = function(name, param)
843                 local tokick, reason = param:match("([^ ]+) (.+)")
844                 tokick = tokick or param
845                 if not core.kick_player(tokick, reason) then
846                         return false, "Failed to kick player " .. tokick
847                 end
848                 local log_reason = ""
849                 if reason then
850                         log_reason = " with reason \"" .. reason .. "\""
851                 end
852                 core.log("action", name .. " kicks " .. tokick .. log_reason)
853                 return true, "Kicked " .. tokick
854         end,
855 })
856
857 core.register_chatcommand("clearobjects", {
858         params = "[full|quick]",
859         description = "clear all objects in world",
860         privs = {server=true},
861         func = function(name, param)
862                 options = {}
863                 if param == "" or param == "full" then
864                         options.mode = "full"
865                 elseif param == "quick" then
866                         options.mode = "quick"
867                 else
868                         return false, "Invalid usage, see /help clearobjects."
869                 end
870
871                 core.log("action", name .. " clears all objects ("
872                                 .. options.mode .. " mode).")
873                 core.chat_send_all("Clearing all objects.  This may take long."
874                                 .. "  You may experience a timeout.  (by "
875                                 .. name .. ")")
876                 core.clear_objects(options)
877                 core.log("action", "Object clearing done.")
878                 core.chat_send_all("*** Cleared all objects.")
879         end,
880 })
881
882 core.register_chatcommand("msg", {
883         params = "<name> <message>",
884         description = "Send a private message",
885         privs = {shout=true},
886         func = function(name, param)
887                 local sendto, message = param:match("^(%S+)%s(.+)$")
888                 if not sendto then
889                         return false, "Invalid usage, see /help msg."
890                 end
891                 if not core.get_player_by_name(sendto) then
892                         return false, "The player " .. sendto
893                                         .. " is not online."
894                 end
895                 core.log("action", "PM from " .. name .. " to " .. sendto
896                                 .. ": " .. message)
897                 core.chat_send_player(sendto, "PM from " .. name .. ": "
898                                 .. message)
899                 return true, "Message sent."
900         end,
901 })
902
903 core.register_chatcommand("last-login", {
904         params = "[name]",
905         description = "Get the last login time of a player",
906         func = function(name, param)
907                 if param == "" then
908                         param = name
909                 end
910                 local pauth = core.get_auth_handler().get_auth(param)
911                 if pauth and pauth.last_login then
912                         -- Time in UTC, ISO 8601 format
913                         return true, "Last login time was " ..
914                                 os.date("!%Y-%m-%dT%H:%M:%SZ", pauth.last_login)
915                 end
916                 return false, "Last login time is unknown"
917         end,
918 })