]> git.lizzy.rs Git - dragonfireclient.git/blob - builtin/game/chat.lua
b73e32876429ff96db7998dc27d9e119899cf47e
[dragonfireclient.git] / builtin / game / chat.lua
1 -- Minetest: builtin/game/chat.lua
2
3 local S = core.get_translator("__builtin")
4
5 -- Helper function that implements search and replace without pattern matching
6 -- Returns the string and a boolean indicating whether or not the string was modified
7 local function safe_gsub(s, replace, with)
8         local i1, i2 = s:find(replace, 1, true)
9         if not i1 then
10                 return s, false
11         end
12
13         return s:sub(1, i1 - 1) .. with .. s:sub(i2 + 1), true
14 end
15
16 --
17 -- Chat message formatter
18 --
19
20 -- Implemented in Lua to allow redefinition
21 function core.format_chat_message(name, message)
22         local error_str = "Invalid chat message format - missing %s"
23         local str = core.settings:get("chat_message_format")
24         local replaced
25
26         -- Name
27         str, replaced = safe_gsub(str, "@name", name)
28         if not replaced then
29                 error(error_str:format("@name"), 2)
30         end
31
32         -- Timestamp
33         str = safe_gsub(str, "@timestamp", os.date("%H:%M:%S", os.time()))
34
35         -- Insert the message into the string only after finishing all other processing
36         str, replaced = safe_gsub(str, "@message", message)
37         if not replaced then
38                 error(error_str:format("@message"), 2)
39         end
40
41         return str
42 end
43
44 --
45 -- Chat command handler
46 --
47
48 core.chatcommands = core.registered_chatcommands -- BACKWARDS COMPATIBILITY
49
50 local msg_time_threshold =
51         tonumber(core.settings:get("chatcommand_msg_time_threshold")) or 0.1
52 core.register_on_chat_message(function(name, message)
53         if message:sub(1,1) ~= "/" then
54                 return
55         end
56
57         local cmd, param = string.match(message, "^/([^ ]+) *(.*)")
58         if not cmd then
59                 core.chat_send_player(name, "-!- "..S("Empty command."))
60                 return true
61         end
62
63         param = param or ""
64
65         -- Run core.registered_on_chatcommands callbacks.
66         if core.run_callbacks(core.registered_on_chatcommands, 5, name, cmd, param) then
67                 return true
68         end
69
70         local cmd_def = core.registered_chatcommands[cmd]
71         if not cmd_def then
72                 core.chat_send_player(name, "-!- "..S("Invalid command: @1", cmd))
73                 return true
74         end
75         local has_privs, missing_privs = core.check_player_privs(name, cmd_def.privs)
76         if has_privs then
77                 core.set_last_run_mod(cmd_def.mod_origin)
78                 local t_before = core.get_us_time()
79                 local success, result = cmd_def.func(name, param)
80                 local delay = (core.get_us_time() - t_before) / 1000000
81                 if success == false and result == nil then
82                         core.chat_send_player(name, "-!- "..S("Invalid command usage."))
83                         local help_def = core.registered_chatcommands["help"]
84                         if help_def then
85                                 local _, helpmsg = help_def.func(name, cmd)
86                                 if helpmsg then
87                                         core.chat_send_player(name, helpmsg)
88                                 end
89                         end
90                 else
91                         if delay > msg_time_threshold then
92                                 -- Show how much time it took to execute the command
93                                 if result then
94                                         result = result .. core.colorize("#f3d2ff", S(" (@1 s)",
95                                                 string.format("%.5f", delay)))
96                                 else
97                                         result = core.colorize("#f3d2ff", S(
98                                                 "Command execution took @1 s",
99                                                 string.format("%.5f", delay)))
100                                 end
101                         end
102                         if result then
103                                 core.chat_send_player(name, result)
104                         end
105                 end
106         else
107                 core.chat_send_player(name,
108                                 S("You don't have permission to run this command "
109                                 .. "(missing privileges: @1).",
110                                 table.concat(missing_privs, ", ")))
111         end
112         return true  -- Handled chat message
113 end)
114
115 if core.settings:get_bool("profiler.load") then
116         -- Run after register_chatcommand and its register_on_chat_message
117         -- Before any chatcommands that should be profiled
118         profiler.init_chatcommand()
119 end
120
121 -- Parses a "range" string in the format of "here (number)" or
122 -- "(x1, y1, z1) (x2, y2, z2)", returning two position vectors
123 local function parse_range_str(player_name, str)
124         local p1, p2
125         local args = str:split(" ")
126
127         if args[1] == "here" then
128                 p1, p2 = core.get_player_radius_area(player_name, tonumber(args[2]))
129                 if p1 == nil then
130                         return false, S("Unable to get position of player @1.", player_name)
131                 end
132         else
133                 p1, p2 = core.string_to_area(str)
134                 if p1 == nil then
135                         return false, S("Incorrect area format. "
136                                 .. "Expected: (x1,y1,z1) (x2,y2,z2)")
137                 end
138         end
139
140         return p1, p2
141 end
142
143 --
144 -- Chat commands
145 --
146 core.register_chatcommand("me", {
147         params = S("<action>"),
148         description = S("Show chat action (e.g., '/me orders a pizza' "
149                 .. "displays '<player name> orders a pizza')"),
150         privs = {shout=true},
151         func = function(name, param)
152                 core.chat_send_all("* " .. name .. " " .. param)
153                 return true
154         end,
155 })
156
157 core.register_chatcommand("admin", {
158         description = S("Show the name of the server owner"),
159         func = function(name)
160                 local admin = core.settings:get("name")
161                 if admin then
162                         return true, S("The administrator of this server is @1.", admin)
163                 else
164                         return false, S("There's no administrator named "
165                                 .. "in the config file.")
166                 end
167         end,
168 })
169
170 local function privileges_of(name, privs)
171         if not privs then
172                 privs = core.get_player_privs(name)
173         end
174         local privstr = core.privs_to_string(privs, ", ")
175         if privstr == "" then
176                 return S("@1 does not have any privileges.", name)
177         else
178                 return S("Privileges of @1: @2", name, privstr)
179         end
180 end
181
182 core.register_chatcommand("privs", {
183         params = S("[<name>]"),
184         description = S("Show privileges of yourself or another player"),
185         func = function(caller, param)
186                 param = param:trim()
187                 local name = (param ~= "" and param or caller)
188                 if not core.player_exists(name) then
189                         return false, S("Player @1 does not exist.", name)
190                 end
191                 return true, privileges_of(name)
192         end,
193 })
194
195 core.register_chatcommand("haspriv", {
196         params = S("<privilege>"),
197         description = S("Return list of all online players with privilege"),
198         privs = {basic_privs = true},
199         func = function(caller, param)
200                 param = param:trim()
201                 if param == "" then
202                         return false, S("Invalid parameters (see /help haspriv).")
203                 end
204                 if not core.registered_privileges[param] then
205                         return false, S("Unknown privilege!")
206                 end
207                 local privs = core.string_to_privs(param)
208                 local players_with_priv = {}
209                 for _, player in pairs(core.get_connected_players()) do
210                         local player_name = player:get_player_name()
211                         if core.check_player_privs(player_name, privs) then
212                                 table.insert(players_with_priv, player_name)
213                         end
214                 end
215                 if #players_with_priv == 0 then
216                         return true, S("No online player has the \"@1\" privilege.",
217                                         param)
218                 else
219                         return true, S("Players online with the \"@1\" privilege: @2",
220                                         param,
221                                         table.concat(players_with_priv, ", "))
222                 end
223         end
224 })
225
226 local function handle_grant_command(caller, grantname, grantprivstr)
227         local caller_privs = core.get_player_privs(caller)
228         if not (caller_privs.privs or caller_privs.basic_privs) then
229                 return false, S("Your privileges are insufficient.")
230         end
231
232         if not core.get_auth_handler().get_auth(grantname) then
233                 return false, S("Player @1 does not exist.", grantname)
234         end
235         local grantprivs = core.string_to_privs(grantprivstr)
236         if grantprivstr == "all" then
237                 grantprivs = core.registered_privileges
238         end
239         local privs = core.get_player_privs(grantname)
240         local privs_unknown = ""
241         local basic_privs =
242                 core.string_to_privs(core.settings:get("basic_privs") or "interact,shout")
243         for priv, _ in pairs(grantprivs) do
244                 if not basic_privs[priv] and not caller_privs.privs then
245                         return false, S("Your privileges are insufficient. "..
246                                         "'@1' only allows you to grant: @2",
247                                         "basic_privs",
248                                         core.privs_to_string(basic_privs, ', '))
249                 end
250                 if not core.registered_privileges[priv] then
251                         privs_unknown = privs_unknown .. S("Unknown privilege: @1", priv) .. "\n"
252                 end
253                 privs[priv] = true
254         end
255         if privs_unknown ~= "" then
256                 return false, privs_unknown
257         end
258         core.set_player_privs(grantname, privs)
259         for priv, _ in pairs(grantprivs) do
260                 -- call the on_grant callbacks
261                 core.run_priv_callbacks(grantname, priv, caller, "grant")
262         end
263         core.log("action", caller..' granted ('..core.privs_to_string(grantprivs, ', ')..') privileges to '..grantname)
264         if grantname ~= caller then
265                 core.chat_send_player(grantname,
266                                 S("@1 granted you privileges: @2", caller,
267                                 core.privs_to_string(grantprivs, ', ')))
268         end
269         return true, privileges_of(grantname)
270 end
271
272 core.register_chatcommand("grant", {
273         params = S("<name> (<privilege> [, <privilege2> [<...>]] | all)"),
274         description = S("Give privileges to player"),
275         func = function(name, param)
276                 local grantname, grantprivstr = string.match(param, "([^ ]+) (.+)")
277                 if not grantname or not grantprivstr then
278                         return false, S("Invalid parameters (see /help grant).")
279                 end
280                 return handle_grant_command(name, grantname, grantprivstr)
281         end,
282 })
283
284 core.register_chatcommand("grantme", {
285         params = S("<privilege> [, <privilege2> [<...>]] | all"),
286         description = S("Grant privileges to yourself"),
287         func = function(name, param)
288                 if param == "" then
289                         return false, S("Invalid parameters (see /help grantme).")
290                 end
291                 return handle_grant_command(name, name, param)
292         end,
293 })
294
295 local function handle_revoke_command(caller, revokename, revokeprivstr)
296         local caller_privs = core.get_player_privs(caller)
297         if not (caller_privs.privs or caller_privs.basic_privs) then
298                 return false, S("Your privileges are insufficient.")
299         end
300
301         if not core.get_auth_handler().get_auth(revokename) then
302                 return false, S("Player @1 does not exist.", revokename)
303         end
304
305         local privs = core.get_player_privs(revokename)
306
307         local revokeprivs = core.string_to_privs(revokeprivstr)
308         local is_singleplayer = core.is_singleplayer()
309         local is_admin = not is_singleplayer
310                         and revokename == core.settings:get("name")
311                         and revokename ~= ""
312         if revokeprivstr == "all" then
313                 revokeprivs = privs
314                 privs = {}
315         else
316                 for priv, _ in pairs(revokeprivs) do
317                         privs[priv] = nil
318                 end
319         end
320
321         local privs_unknown = ""
322         local basic_privs =
323                 core.string_to_privs(core.settings:get("basic_privs") or "interact,shout")
324         local irrevokable = {}
325         local has_irrevokable_priv = false
326         for priv, _ in pairs(revokeprivs) do
327                 if not basic_privs[priv] and not caller_privs.privs then
328                         return false, S("Your privileges are insufficient. "..
329                                         "'@1' only allows you to revoke: @2",
330                                         "basic_privs",
331                                         core.privs_to_string(basic_privs, ', '))
332                 end
333                 local def = core.registered_privileges[priv]
334                 if not def then
335                         privs_unknown = privs_unknown .. S("Unknown privilege: @1", priv) .. "\n"
336                 elseif is_singleplayer and def.give_to_singleplayer then
337                         irrevokable[priv] = true
338                 elseif is_admin and def.give_to_admin then
339                         irrevokable[priv] = true
340                 end
341         end
342         for priv, _ in pairs(irrevokable) do
343                 revokeprivs[priv] = nil
344                 has_irrevokable_priv = true
345         end
346         if privs_unknown ~= "" then
347                 return false, privs_unknown
348         end
349         if has_irrevokable_priv then
350                 if is_singleplayer then
351                         core.chat_send_player(caller,
352                                         S("Note: Cannot revoke in singleplayer: @1",
353                                         core.privs_to_string(irrevokable, ', ')))
354                 elseif is_admin then
355                         core.chat_send_player(caller,
356                                         S("Note: Cannot revoke from admin: @1",
357                                         core.privs_to_string(irrevokable, ', ')))
358                 end
359         end
360
361         local revokecount = 0
362
363         core.set_player_privs(revokename, privs)
364         for priv, _ in pairs(revokeprivs) do
365                 -- call the on_revoke callbacks
366                 core.run_priv_callbacks(revokename, priv, caller, "revoke")
367                 revokecount = revokecount + 1
368         end
369         local new_privs = core.get_player_privs(revokename)
370
371         if revokecount == 0 then
372                 return false, S("No privileges were revoked.")
373         end
374
375         core.log("action", caller..' revoked ('
376                         ..core.privs_to_string(revokeprivs, ', ')
377                         ..') privileges from '..revokename)
378         if revokename ~= caller then
379                 core.chat_send_player(revokename,
380                         S("@1 revoked privileges from you: @2", caller,
381                         core.privs_to_string(revokeprivs, ', ')))
382         end
383         return true, privileges_of(revokename, new_privs)
384 end
385
386 core.register_chatcommand("revoke", {
387         params = S("<name> (<privilege> [, <privilege2> [<...>]] | all)"),
388         description = S("Remove privileges from player"),
389         privs = {},
390         func = function(name, param)
391                 local revokename, revokeprivstr = string.match(param, "([^ ]+) (.+)")
392                 if not revokename or not revokeprivstr then
393                         return false, S("Invalid parameters (see /help revoke).")
394                 end
395                 return handle_revoke_command(name, revokename, revokeprivstr)
396         end,
397 })
398
399 core.register_chatcommand("revokeme", {
400         params = S("<privilege> [, <privilege2> [<...>]] | all"),
401         description = S("Revoke privileges from yourself"),
402         privs = {},
403         func = function(name, param)
404                 if param == "" then
405                         return false, S("Invalid parameters (see /help revokeme).")
406                 end
407                 return handle_revoke_command(name, name, param)
408         end,
409 })
410
411 core.register_chatcommand("setpassword", {
412         params = S("<name> <password>"),
413         description = S("Set player's password"),
414         privs = {password=true},
415         func = function(name, param)
416                 local toname, raw_password = string.match(param, "^([^ ]+) +(.+)$")
417                 if not toname then
418                         toname = param:match("^([^ ]+) *$")
419                         raw_password = nil
420                 end
421
422                 if not toname then
423                         return false, S("Name field required.")
424                 end
425
426                 local msg_chat, msg_log, msg_ret
427                 if not raw_password then
428                         core.set_player_password(toname, "")
429                         msg_chat = S("Your password was cleared by @1.", name)
430                         msg_log = name .. " clears password of " .. toname .. "."
431                         msg_ret = S("Password of player \"@1\" cleared.", toname)
432                 else
433                         core.set_player_password(toname,
434                                         core.get_password_hash(toname,
435                                                         raw_password))
436                         msg_chat = S("Your password was set by @1.", name)
437                         msg_log = name .. " sets password of " .. toname .. "."
438                         msg_ret = S("Password of player \"@1\" set.", toname)
439                 end
440
441                 if toname ~= name then
442                         core.chat_send_player(toname, msg_chat)
443                 end
444
445                 core.log("action", msg_log)
446
447                 return true, msg_ret
448         end,
449 })
450
451 core.register_chatcommand("clearpassword", {
452         params = S("<name>"),
453         description = S("Set empty password for a player"),
454         privs = {password=true},
455         func = function(name, param)
456                 local toname = param
457                 if toname == "" then
458                         return false, S("Name field required.")
459                 end
460                 core.set_player_password(toname, '')
461
462                 core.log("action", name .. " clears password of " .. toname .. ".")
463
464                 return true, S("Password of player \"@1\" cleared.", toname)
465         end,
466 })
467
468 core.register_chatcommand("auth_reload", {
469         params = "",
470         description = S("Reload authentication data"),
471         privs = {server=true},
472         func = function(name, param)
473                 local done = core.auth_reload()
474                 return done, (done and S("Done.") or S("Failed."))
475         end,
476 })
477
478 core.register_chatcommand("remove_player", {
479         params = S("<name>"),
480         description = S("Remove a player's data"),
481         privs = {server=true},
482         func = function(name, param)
483                 local toname = param
484                 if toname == "" then
485                         return false, S("Name field required.")
486                 end
487
488                 local rc = core.remove_player(toname)
489
490                 if rc == 0 then
491                         core.log("action", name .. " removed player data of " .. toname .. ".")
492                         return true, S("Player \"@1\" removed.", toname)
493                 elseif rc == 1 then
494                         return true, S("No such player \"@1\" to remove.", toname)
495                 elseif rc == 2 then
496                         return true, S("Player \"@1\" is connected, cannot remove.", toname)
497                 end
498
499                 return false, S("Unhandled remove_player return code @1.", tostring(rc))
500         end,
501 })
502
503
504 -- pos may be a non-integer position
505 local function find_free_position_near(pos)
506         local tries = {
507                 vector.new( 1, 0,  0),
508                 vector.new(-1, 0,  0),
509                 vector.new( 0, 0,  1),
510                 vector.new( 0, 0, -1),
511         }
512         for _, d in ipairs(tries) do
513                 local p = vector.add(pos, d)
514                 local n = core.get_node_or_nil(p)
515                 if n then
516                         local def = core.registered_nodes[n.name]
517                         if def and not def.walkable then
518                                 return p
519                         end
520                 end
521         end
522         return pos
523 end
524
525 -- Teleports player <name> to <p> if possible
526 local function teleport_to_pos(name, p)
527         local lm = 31007 -- equals MAX_MAP_GENERATION_LIMIT in C++
528         if p.x < -lm or p.x > lm or p.y < -lm or p.y > lm
529                         or p.z < -lm or p.z > lm then
530                 return false, S("Cannot teleport out of map bounds!")
531         end
532         local teleportee = core.get_player_by_name(name)
533         if not teleportee then
534                 return false, S("Cannot get player with name @1.", name)
535         end
536         if teleportee:get_attach() then
537                 return false, S("Cannot teleport, @1 " ..
538                         "is attached to an object!", name)
539         end
540         teleportee:set_pos(p)
541         return true, S("Teleporting @1 to @2.", name, core.pos_to_string(p, 1))
542 end
543
544 -- Teleports player <name> next to player <target_name> if possible
545 local function teleport_to_player(name, target_name)
546         if name == target_name then
547                 return false, S("One does not teleport to oneself.")
548         end
549         local teleportee = core.get_player_by_name(name)
550         if not teleportee then
551                 return false, S("Cannot get teleportee with name @1.", name)
552         end
553         if teleportee:get_attach() then
554                 return false, S("Cannot teleport, @1 " ..
555                         "is attached to an object!", name)
556         end
557         local target = core.get_player_by_name(target_name)
558         if not target then
559                 return false, S("Cannot get target player with name @1.", target_name)
560         end
561         local p = find_free_position_near(target:get_pos())
562         teleportee:set_pos(p)
563         return true, S("Teleporting @1 to @2 at @3.", name, target_name,
564                 core.pos_to_string(p, 1))
565 end
566
567 core.register_chatcommand("teleport", {
568         params = S("<X>,<Y>,<Z> | <to_name> | <name> <X>,<Y>,<Z> | <name> <to_name>"),
569         description = S("Teleport to position or player"),
570         privs = {teleport=true},
571         func = function(name, param)
572                 local p = {}
573                 p.x, p.y, p.z = param:match("^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
574                 p = vector.apply(p, tonumber)
575                 if p.x and p.y and p.z then
576                         return teleport_to_pos(name, p)
577                 end
578
579                 local target_name = param:match("^([^ ]+)$")
580                 if target_name then
581                         return teleport_to_player(name, target_name)
582                 end
583
584                 local has_bring_priv = core.check_player_privs(name, {bring=true})
585                 local missing_bring_msg = S("You don't have permission to teleport " ..
586                         "other players (missing privilege: @1).", "bring")
587
588                 local teleportee_name
589                 teleportee_name, p.x, p.y, p.z = param:match(
590                                 "^([^ ]+) +([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
591                 p = vector.apply(p, tonumber)
592                 if teleportee_name and p.x and p.y and p.z then
593                         if not has_bring_priv then
594                                 return false, missing_bring_msg
595                         end
596                         return teleport_to_pos(teleportee_name, p)
597                 end
598
599                 teleportee_name, target_name = string.match(param, "^([^ ]+) +([^ ]+)$")
600                 if teleportee_name and target_name then
601                         if not has_bring_priv then
602                                 return false, missing_bring_msg
603                         end
604                         return teleport_to_player(teleportee_name, target_name)
605                 end
606
607                 return false
608         end,
609 })
610
611 core.register_chatcommand("set", {
612         params = S("([-n] <name> <value>) | <name>"),
613         description = S("Set or read server configuration setting"),
614         privs = {server=true},
615         func = function(name, param)
616                 local arg, setname, setvalue = string.match(param, "(-[n]) ([^ ]+) (.+)")
617                 if arg and arg == "-n" and setname and setvalue then
618                         core.settings:set(setname, setvalue)
619                         return true, setname .. " = " .. setvalue
620                 end
621
622                 setname, setvalue = string.match(param, "([^ ]+) (.+)")
623                 if setname and setvalue then
624                         if not core.settings:get(setname) then
625                                 return false, S("Failed. Use '/set -n <name> <value>' "
626                                         .. "to create a new setting.")
627                         end
628                         core.settings:set(setname, setvalue)
629                         return true, S("@1 = @2", setname, setvalue)
630                 end
631
632                 setname = string.match(param, "([^ ]+)")
633                 if setname then
634                         setvalue = core.settings:get(setname)
635                         if not setvalue then
636                                 setvalue = S("<not set>")
637                         end
638                         return true, S("@1 = @2", setname, setvalue)
639                 end
640
641                 return false, S("Invalid parameters (see /help set).")
642         end,
643 })
644
645 local function emergeblocks_callback(pos, action, num_calls_remaining, ctx)
646         if ctx.total_blocks == 0 then
647                 ctx.total_blocks   = num_calls_remaining + 1
648                 ctx.current_blocks = 0
649         end
650         ctx.current_blocks = ctx.current_blocks + 1
651
652         if ctx.current_blocks == ctx.total_blocks then
653                 core.chat_send_player(ctx.requestor_name,
654                         S("Finished emerging @1 blocks in @2ms.",
655                                 ctx.total_blocks,
656                                 string.format("%.2f", (os.clock() - ctx.start_time) * 1000)))
657         end
658 end
659
660 local function emergeblocks_progress_update(ctx)
661         if ctx.current_blocks ~= ctx.total_blocks then
662                 core.chat_send_player(ctx.requestor_name,
663                         S("emergeblocks update: @1/@2 blocks emerged (@3%)",
664                         ctx.current_blocks, ctx.total_blocks,
665                         string.format("%.1f", (ctx.current_blocks / ctx.total_blocks) * 100)))
666
667                 core.after(2, emergeblocks_progress_update, ctx)
668         end
669 end
670
671 core.register_chatcommand("emergeblocks", {
672         params = S("(here [<radius>]) | (<pos1> <pos2>)"),
673         description = S("Load (or, if nonexistent, generate) map blocks contained in "
674                 .. "area pos1 to pos2 (<pos1> and <pos2> must be in parentheses)"),
675         privs = {server=true},
676         func = function(name, param)
677                 local p1, p2 = parse_range_str(name, param)
678                 if p1 == false then
679                         return false, p2
680                 end
681
682                 local context = {
683                         current_blocks = 0,
684                         total_blocks   = 0,
685                         start_time     = os.clock(),
686                         requestor_name = name
687                 }
688
689                 core.emerge_area(p1, p2, emergeblocks_callback, context)
690                 core.after(2, emergeblocks_progress_update, context)
691
692                 return true, S("Started emerge of area ranging from @1 to @2.",
693                         core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
694         end,
695 })
696
697 core.register_chatcommand("deleteblocks", {
698         params = S("(here [<radius>]) | (<pos1> <pos2>)"),
699         description = S("Delete map blocks contained in area pos1 to pos2 "
700                 .. "(<pos1> and <pos2> must be in parentheses)"),
701         privs = {server=true},
702         func = function(name, param)
703                 local p1, p2 = parse_range_str(name, param)
704                 if p1 == false then
705                         return false, p2
706                 end
707
708                 if core.delete_area(p1, p2) then
709                         return true, S("Successfully cleared area "
710                                 .. "ranging from @1 to @2.",
711                                 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
712                 else
713                         return false, S("Failed to clear one or more "
714                                 .. "blocks in area.")
715                 end
716         end,
717 })
718
719 core.register_chatcommand("fixlight", {
720         params = S("(here [<radius>]) | (<pos1> <pos2>)"),
721         description = S("Resets lighting in the area between pos1 and pos2 "
722                 .. "(<pos1> and <pos2> must be in parentheses)"),
723         privs = {server = true},
724         func = function(name, param)
725                 local p1, p2 = parse_range_str(name, param)
726                 if p1 == false then
727                         return false, p2
728                 end
729
730                 if core.fix_light(p1, p2) then
731                         return true, S("Successfully reset light in the area "
732                                 .. "ranging from @1 to @2.",
733                                 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
734                 else
735                         return false, S("Failed to load one or more blocks in area.")
736                 end
737         end,
738 })
739
740 core.register_chatcommand("mods", {
741         params = "",
742         description = S("List mods installed on the server"),
743         privs = {},
744         func = function(name, param)
745                 local mods = core.get_modnames()
746                 if #mods == 0 then
747                         return true, S("No mods installed.")
748                 else
749                         return true, table.concat(core.get_modnames(), ", ")
750                 end
751         end,
752 })
753
754 local function handle_give_command(cmd, giver, receiver, stackstring)
755         core.log("action", giver .. " invoked " .. cmd
756                         .. ', stackstring="' .. stackstring .. '"')
757         local itemstack = ItemStack(stackstring)
758         if itemstack:is_empty() then
759                 return false, S("Cannot give an empty item.")
760         elseif (not itemstack:is_known()) or (itemstack:get_name() == "unknown") then
761                 return false, S("Cannot give an unknown item.")
762         -- Forbid giving 'ignore' due to unwanted side effects
763         elseif itemstack:get_name() == "ignore" then
764                 return false, S("Giving 'ignore' is not allowed.")
765         end
766         local receiverref = core.get_player_by_name(receiver)
767         if receiverref == nil then
768                 return false, S("@1 is not a known player.", receiver)
769         end
770         local leftover = receiverref:get_inventory():add_item("main", itemstack)
771         local partiality
772         if leftover:is_empty() then
773                 partiality = nil
774         elseif leftover:get_count() == itemstack:get_count() then
775                 partiality = false
776         else
777                 partiality = true
778         end
779         -- The actual item stack string may be different from what the "giver"
780         -- entered (e.g. big numbers are always interpreted as 2^16-1).
781         stackstring = itemstack:to_string()
782         local msg
783         if partiality == true then
784                 msg = S("@1 partially added to inventory.", stackstring)
785         elseif partiality == false then
786                 msg = S("@1 could not be added to inventory.", stackstring)
787         else
788                 msg = S("@1 added to inventory.", stackstring)
789         end
790         if giver == receiver then
791                 return true, msg
792         else
793                 core.chat_send_player(receiver, msg)
794                 local msg_other
795                 if partiality == true then
796                         msg_other = S("@1 partially added to inventory of @2.",
797                                         stackstring, receiver)
798                 elseif partiality == false then
799                         msg_other = S("@1 could not be added to inventory of @2.",
800                                         stackstring, receiver)
801                 else
802                         msg_other = S("@1 added to inventory of @2.",
803                                         stackstring, receiver)
804                 end
805                 return true, msg_other
806         end
807 end
808
809 core.register_chatcommand("give", {
810         params = S("<name> <ItemString> [<count> [<wear>]]"),
811         description = S("Give item to player"),
812         privs = {give=true},
813         func = function(name, param)
814                 local toname, itemstring = string.match(param, "^([^ ]+) +(.+)$")
815                 if not toname or not itemstring then
816                         return false, S("Name and ItemString required.")
817                 end
818                 return handle_give_command("/give", name, toname, itemstring)
819         end,
820 })
821
822 core.register_chatcommand("giveme", {
823         params = S("<ItemString> [<count> [<wear>]]"),
824         description = S("Give item to yourself"),
825         privs = {give=true},
826         func = function(name, param)
827                 local itemstring = string.match(param, "(.+)$")
828                 if not itemstring then
829                         return false, S("ItemString required.")
830                 end
831                 return handle_give_command("/giveme", name, name, itemstring)
832         end,
833 })
834
835 core.register_chatcommand("spawnentity", {
836         params = S("<EntityName> [<X>,<Y>,<Z>]"),
837         description = S("Spawn entity at given (or your) position"),
838         privs = {give=true, interact=true},
839         func = function(name, param)
840                 local entityname, p = string.match(param, "^([^ ]+) *(.*)$")
841                 if not entityname then
842                         return false, S("EntityName required.")
843                 end
844                 core.log("action", ("%s invokes /spawnentity, entityname=%q")
845                                 :format(name, entityname))
846                 local player = core.get_player_by_name(name)
847                 if player == nil then
848                         core.log("error", "Unable to spawn entity, player is nil")
849                         return false, S("Unable to spawn entity, player is nil.")
850                 end
851                 if not core.registered_entities[entityname] then
852                         return false, S("Cannot spawn an unknown entity.")
853                 end
854                 if p == "" then
855                         p = player:get_pos()
856                 else
857                         p = core.string_to_pos(p)
858                         if p == nil then
859                                 return false, S("Invalid parameters (@1).", param)
860                         end
861                 end
862                 p.y = p.y + 1
863                 local obj = core.add_entity(p, entityname)
864                 if obj then
865                         return true, S("@1 spawned.", entityname)
866                 else
867                         return true, S("@1 failed to spawn.", entityname)
868                 end
869         end,
870 })
871
872 core.register_chatcommand("pulverize", {
873         params = "",
874         description = S("Destroy item in hand"),
875         func = function(name, param)
876                 local player = core.get_player_by_name(name)
877                 if not player then
878                         core.log("error", "Unable to pulverize, no player.")
879                         return false, S("Unable to pulverize, no player.")
880                 end
881                 local wielded_item = player:get_wielded_item()
882                 if wielded_item:is_empty() then
883                         return false, S("Unable to pulverize, no item in hand.")
884                 end
885                 core.log("action", name .. " pulverized \"" ..
886                         wielded_item:get_name() .. " " .. wielded_item:get_count() .. "\"")
887                 player:set_wielded_item(nil)
888                 return true, S("An item was pulverized.")
889         end,
890 })
891
892 -- Key = player name
893 core.rollback_punch_callbacks = {}
894
895 core.register_on_punchnode(function(pos, node, puncher)
896         local name = puncher and puncher:get_player_name()
897         if name and core.rollback_punch_callbacks[name] then
898                 core.rollback_punch_callbacks[name](pos, node, puncher)
899                 core.rollback_punch_callbacks[name] = nil
900         end
901 end)
902
903 core.register_chatcommand("rollback_check", {
904         params = S("[<range>] [<seconds>] [<limit>]"),
905         description = S("Check who last touched a node or a node near it "
906                 .. "within the time specified by <seconds>. "
907                 .. "Default: range = 0, seconds = 86400 = 24h, limit = 5. "
908                 .. "Set <seconds> to inf for no time limit"),
909         privs = {rollback=true},
910         func = function(name, param)
911                 if not core.settings:get_bool("enable_rollback_recording") then
912                         return false, S("Rollback functions are disabled.")
913                 end
914                 local range, seconds, limit =
915                         param:match("(%d+) *(%d*) *(%d*)")
916                 range = tonumber(range) or 0
917                 seconds = tonumber(seconds) or 86400
918                 limit = tonumber(limit) or 5
919                 if limit > 100 then
920                         return false, S("That limit is too high!")
921                 end
922
923                 core.rollback_punch_callbacks[name] = function(pos, node, puncher)
924                         local name = puncher:get_player_name()
925                         core.chat_send_player(name, S("Checking @1 ...", core.pos_to_string(pos)))
926                         local actions = core.rollback_get_node_actions(pos, range, seconds, limit)
927                         if not actions then
928                                 core.chat_send_player(name, S("Rollback functions are disabled."))
929                                 return
930                         end
931                         local num_actions = #actions
932                         if num_actions == 0 then
933                                 core.chat_send_player(name,
934                                                 S("Nobody has touched the specified "
935                                                 .. "location in @1 seconds.",
936                                                 seconds))
937                                 return
938                         end
939                         local time = os.time()
940                         for i = num_actions, 1, -1 do
941                                 local action = actions[i]
942                                 core.chat_send_player(name,
943                                         S("@1 @2 @3 -> @4 @5 seconds ago.",
944                                                         core.pos_to_string(action.pos),
945                                                         action.actor,
946                                                         action.oldnode.name,
947                                                         action.newnode.name,
948                                                         time - action.time))
949                         end
950                 end
951
952                 return true, S("Punch a node (range=@1, seconds=@2, limit=@3).",
953                                 range, seconds, limit)
954         end,
955 })
956
957 core.register_chatcommand("rollback", {
958         params = S("(<name> [<seconds>]) | (:<actor> [<seconds>])"),
959         description = S("Revert actions of a player. "
960                 .. "Default for <seconds> is 60. "
961                 .. "Set <seconds> to inf for no time limit"),
962         privs = {rollback=true},
963         func = function(name, param)
964                 if not core.settings:get_bool("enable_rollback_recording") then
965                         return false, S("Rollback functions are disabled.")
966                 end
967                 local target_name, seconds = string.match(param, ":([^ ]+) *(%d*)")
968                 local rev_msg
969                 if not target_name then
970                         local player_name
971                         player_name, seconds = string.match(param, "([^ ]+) *(%d*)")
972                         if not player_name then
973                                 return false, S("Invalid parameters. "
974                                         .. "See /help rollback and "
975                                         .. "/help rollback_check.")
976                         end
977                         seconds = tonumber(seconds) or 60
978                         target_name = "player:"..player_name
979                         rev_msg = S("Reverting actions of player '@1' since @2 seconds.",
980                                 player_name, seconds)
981                 else
982                         seconds = tonumber(seconds) or 60
983                         rev_msg = S("Reverting actions of @1 since @2 seconds.",
984                                 target_name, seconds)
985                 end
986                 core.chat_send_player(name, rev_msg)
987                 local success, log = core.rollback_revert_actions_by(
988                                 target_name, seconds)
989                 local response = ""
990                 if #log > 100 then
991                         response = S("(log is too long to show)").."\n"
992                 else
993                         for _, line in pairs(log) do
994                                 response = response .. line .. "\n"
995                         end
996                 end
997                 if success then
998                         response = response .. S("Reverting actions succeeded.")
999                 else
1000                         response = response .. S("Reverting actions FAILED.")
1001                 end
1002                 return success, response
1003         end,
1004 })
1005
1006 core.register_chatcommand("status", {
1007         description = S("Show server status"),
1008         func = function(name, param)
1009                 local status = core.get_server_status(name, false)
1010                 if status and status ~= "" then
1011                         return true, status
1012                 end
1013                 return false, S("This command was disabled by a mod or game.")
1014         end,
1015 })
1016
1017 core.register_chatcommand("time", {
1018         params = S("[<0..23>:<0..59> | <0..24000>]"),
1019         description = S("Show or set time of day"),
1020         privs = {},
1021         func = function(name, param)
1022                 if param == "" then
1023                         local current_time = math.floor(core.get_timeofday() * 1440)
1024                         local minutes = current_time % 60
1025                         local hour = (current_time - minutes) / 60
1026                         return true, S("Current time is @1:@2.",
1027                                         string.format("%d", hour),
1028                                         string.format("%02d", minutes))
1029                 end
1030                 local player_privs = core.get_player_privs(name)
1031                 if not player_privs.settime then
1032                         return false, S("You don't have permission to run "
1033                                 .. "this command (missing privilege: @1).", "settime")
1034                 end
1035                 local hour, minute = param:match("^(%d+):(%d+)$")
1036                 if not hour then
1037                         local new_time = tonumber(param) or -1
1038                         if new_time ~= new_time or new_time < 0 or new_time > 24000 then
1039                                 return false, S("Invalid time (must be between 0 and 24000).")
1040                         end
1041                         core.set_timeofday(new_time / 24000)
1042                         core.log("action", name .. " sets time to " .. new_time)
1043                         return true, S("Time of day changed.")
1044                 end
1045                 hour = tonumber(hour)
1046                 minute = tonumber(minute)
1047                 if hour < 0 or hour > 23 then
1048                         return false, S("Invalid hour (must be between 0 and 23 inclusive).")
1049                 elseif minute < 0 or minute > 59 then
1050                         return false, S("Invalid minute (must be between 0 and 59 inclusive).")
1051                 end
1052                 core.set_timeofday((hour * 60 + minute) / 1440)
1053                 core.log("action", ("%s sets time to %d:%02d"):format(name, hour, minute))
1054                 return true, S("Time of day changed.")
1055         end,
1056 })
1057
1058 core.register_chatcommand("days", {
1059         description = S("Show day count since world creation"),
1060         func = function(name, param)
1061                 return true, S("Current day is @1.", core.get_day_count())
1062         end
1063 })
1064
1065 local function parse_shutdown_param(param)
1066         local delay, reconnect, message
1067         local one, two, three
1068         one, two, three = param:match("^(%S+) +(%-r) +(.*)")
1069         if one and two and three then
1070                 -- 3 arguments: delay, reconnect and message
1071                 return one, two, three
1072         end
1073         -- 2 arguments
1074         one, two = param:match("^(%S+) +(.*)")
1075         if one and two then
1076                 if tonumber(one) then
1077                         delay = one
1078                         if two == "-r" then
1079                                 reconnect = two
1080                         else
1081                                 message = two
1082                         end
1083                 elseif one == "-r" then
1084                         reconnect, message = one, two
1085                 end
1086                 return delay, reconnect, message
1087         end
1088         -- 1 argument
1089         one = param:match("(.*)")
1090         if tonumber(one) then
1091                 delay = one
1092         elseif one == "-r" then
1093                 reconnect = one
1094         else
1095                 message = one
1096         end
1097         return delay, reconnect, message
1098 end
1099
1100 core.register_chatcommand("shutdown", {
1101         params = S("[<delay_in_seconds> | -1] [-r] [<message>]"),
1102         description = S("Shutdown server (-1 cancels a delayed shutdown, -r allows players to reconnect)"),
1103         privs = {server=true},
1104         func = function(name, param)
1105                 local delay, reconnect, message = parse_shutdown_param(param)
1106                 local bool_reconnect = reconnect == "-r"
1107                 if not message then
1108                         message = ""
1109                 end
1110                 delay = tonumber(delay) or 0
1111
1112                 if delay == 0 then
1113                         core.log("action", name .. " shuts down server")
1114                         core.chat_send_all("*** "..S("Server shutting down (operator request)."))
1115                 end
1116                 core.request_shutdown(message:trim(), bool_reconnect, delay)
1117                 return true
1118         end,
1119 })
1120
1121 core.register_chatcommand("ban", {
1122         params = S("[<name>]"),
1123         description = S("Ban the IP of a player or show the ban list"),
1124         privs = {ban=true},
1125         func = function(name, param)
1126                 if param == "" then
1127                         local ban_list = core.get_ban_list()
1128                         if ban_list == "" then
1129                                 return true, S("The ban list is empty.")
1130                         else
1131                                 return true, S("Ban list: @1", ban_list)
1132                         end
1133                 end
1134                 if not core.get_player_by_name(param) then
1135                         return false, S("Player is not online.")
1136                 end
1137                 if not core.ban_player(param) then
1138                         return false, S("Failed to ban player.")
1139                 end
1140                 local desc = core.get_ban_description(param)
1141                 core.log("action", name .. " bans " .. desc .. ".")
1142                 return true, S("Banned @1.", desc)
1143         end,
1144 })
1145
1146 core.register_chatcommand("unban", {
1147         params = S("<name> | <IP_address>"),
1148         description = S("Remove IP ban belonging to a player/IP"),
1149         privs = {ban=true},
1150         func = function(name, param)
1151                 if not core.unban_player_or_ip(param) then
1152                         return false, S("Failed to unban player/IP.")
1153                 end
1154                 core.log("action", name .. " unbans " .. param)
1155                 return true, S("Unbanned @1.", param)
1156         end,
1157 })
1158
1159 core.register_chatcommand("kick", {
1160         params = S("<name> [<reason>]"),
1161         description = S("Kick a player"),
1162         privs = {kick=true},
1163         func = function(name, param)
1164                 local tokick, reason = param:match("([^ ]+) (.+)")
1165                 tokick = tokick or param
1166                 if not core.kick_player(tokick, reason) then
1167                         return false, S("Failed to kick player @1.", tokick)
1168                 end
1169                 local log_reason = ""
1170                 if reason then
1171                         log_reason = " with reason \"" .. reason .. "\""
1172                 end
1173                 core.log("action", name .. " kicks " .. tokick .. log_reason)
1174                 return true, S("Kicked @1.", tokick)
1175         end,
1176 })
1177
1178 core.register_chatcommand("clearobjects", {
1179         params = S("[full | quick]"),
1180         description = S("Clear all objects in world"),
1181         privs = {server=true},
1182         func = function(name, param)
1183                 local options = {}
1184                 if param == "" or param == "quick" then
1185                         options.mode = "quick"
1186                 elseif param == "full" then
1187                         options.mode = "full"
1188                 else
1189                         return false, S("Invalid usage, see /help clearobjects.")
1190                 end
1191
1192                 core.log("action", name .. " clears objects ("
1193                                 .. options.mode .. " mode).")
1194                 if options.mode == "full" then
1195                         core.chat_send_all(S("Clearing all objects. This may take a long time. "
1196                                 .. "You may experience a timeout. (by @1)", name))
1197                 end
1198                 core.clear_objects(options)
1199                 core.log("action", "Object clearing done.")
1200                 core.chat_send_all("*** "..S("Cleared all objects."))
1201                 return true
1202         end,
1203 })
1204
1205 core.register_chatcommand("msg", {
1206         params = S("<name> <message>"),
1207         description = S("Send a direct message to a player"),
1208         privs = {shout=true},
1209         func = function(name, param)
1210                 local sendto, message = param:match("^(%S+)%s(.+)$")
1211                 if not sendto then
1212                         return false, S("Invalid usage, see /help msg.")
1213                 end
1214                 if not core.get_player_by_name(sendto) then
1215                         return false, S("The player @1 is not online.", sendto)
1216                 end
1217                 core.log("action", "DM from " .. name .. " to " .. sendto
1218                                 .. ": " .. message)
1219                 core.chat_send_player(sendto, S("DM from @1: @2", name, message))
1220                 return true, S("Message sent.")
1221         end,
1222 })
1223
1224 core.register_chatcommand("last-login", {
1225         params = S("[<name>]"),
1226         description = S("Get the last login time of a player or yourself"),
1227         func = function(name, param)
1228                 if param == "" then
1229                         param = name
1230                 end
1231                 local pauth = core.get_auth_handler().get_auth(param)
1232                 if pauth and pauth.last_login and pauth.last_login ~= -1 then
1233                         -- Time in UTC, ISO 8601 format
1234                         return true, S("@1's last login time was @2.",
1235                                 param,
1236                                 os.date("!%Y-%m-%dT%H:%M:%SZ", pauth.last_login))
1237                 end
1238                 return false, S("@1's last login time is unknown.", param)
1239         end,
1240 })
1241
1242 core.register_chatcommand("clearinv", {
1243         params = S("[<name>]"),
1244         description = S("Clear the inventory of yourself or another player"),
1245         func = function(name, param)
1246                 local player
1247                 if param and param ~= "" and param ~= name then
1248                         if not core.check_player_privs(name, {server=true}) then
1249                                 return false, S("You don't have permission to "
1250                                         .. "clear another player's inventory "
1251                                         .. "(missing privilege: @1).", "server")
1252                         end
1253                         player = core.get_player_by_name(param)
1254                         core.chat_send_player(param, S("@1 cleared your inventory.", name))
1255                 else
1256                         player = core.get_player_by_name(name)
1257                 end
1258
1259                 if player then
1260                         player:get_inventory():set_list("main", {})
1261                         player:get_inventory():set_list("craft", {})
1262                         player:get_inventory():set_list("craftpreview", {})
1263                         core.log("action", name.." clears "..player:get_player_name().."'s inventory")
1264                         return true, S("Cleared @1's inventory.", player:get_player_name())
1265                 else
1266                         return false, S("Player must be online to clear inventory!")
1267                 end
1268         end,
1269 })
1270
1271 local function handle_kill_command(killer, victim)
1272         if core.settings:get_bool("enable_damage") == false then
1273                 return false, S("Players can't be killed, damage has been disabled.")
1274         end
1275         local victimref = core.get_player_by_name(victim)
1276         if victimref == nil then
1277                 return false, S("Player @1 is not online.", victim)
1278         elseif victimref:get_hp() <= 0 then
1279                 if killer == victim then
1280                         return false, S("You are already dead.")
1281                 else
1282                         return false, S("@1 is already dead.", victim)
1283                 end
1284         end
1285         if not killer == victim then
1286                 core.log("action", string.format("%s killed %s", killer, victim))
1287         end
1288         -- Kill victim
1289         victimref:set_hp(0)
1290         return true, S("@1 has been killed.", victim)
1291 end
1292
1293 core.register_chatcommand("kill", {
1294         params = S("[<name>]"),
1295         description = S("Kill player or yourself"),
1296         privs = {server=true},
1297         func = function(name, param)
1298                 return handle_kill_command(name, param == "" and name or param)
1299         end,
1300 })