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