Merge 0.6->0.7
[prosody.git] / plugins / muc / muc.lib.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 local datamanager = require "util.datamanager";
10 local datetime = require "util.datetime";
11
12 local jid_split = require "util.jid".split;
13 local jid_bare = require "util.jid".bare;
14 local jid_prep = require "util.jid".prep;
15 local st = require "util.stanza";
16 local log = require "util.logger".init("mod_muc");
17 local multitable_new = require "util.multitable".new;
18 local t_insert, t_remove = table.insert, table.remove;
19 local setmetatable = setmetatable;
20 local base64 = require "util.encodings".base64;
21 local md5 = require "util.hashes".md5;
22
23 local muc_domain = nil; --module:get_host();
24 local history_length = 20;
25
26 ------------
27 local function filter_xmlns_from_array(array, filters)
28         local count = 0;
29         for i=#array,1,-1 do
30                 local attr = array[i].attr;
31                 if filters[attr and attr.xmlns] then
32                         t_remove(array, i);
33                         count = count + 1;
34                 end
35         end
36         return count;
37 end
38 local function filter_xmlns_from_stanza(stanza, filters)
39         if filters then
40                 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
41                         return stanza, filter_xmlns_from_array(stanza, filters);
42                 end
43         end
44         return stanza, 0;
45 end
46 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
47 local function get_filtered_presence(stanza)
48         return filter_xmlns_from_stanza(st.clone(stanza):reset(), presence_filters);
49 end
50 local kickable_error_conditions = {
51         ["gone"] = true;
52         ["internal-server-error"] = true;
53         ["item-not-found"] = true;
54         ["jid-malformed"] = true;
55         ["recipient-unavailable"] = true;
56         ["redirect"] = true;
57         ["remote-server-not-found"] = true;
58         ["remote-server-timeout"] = true;
59         ["service-unavailable"] = true;
60         ["malformed error"] = true;
61 };
62
63 local function get_error_condition(stanza)
64         local _, condition = stanza:get_error();
65         return condition or "malformed error";
66 end
67
68 local function is_kickable_error(stanza)
69         local cond = get_error_condition(stanza);
70         return kickable_error_conditions[cond] and cond;
71 end
72 local function getUsingPath(stanza, path, getText)
73         local tag = stanza;
74         for _, name in ipairs(path) do
75                 if type(tag) ~= 'table' then return; end
76                 tag = tag:child_with_name(name);
77         end
78         if tag and getText then tag = table.concat(tag); end
79         return tag;
80 end
81 local function getTag(stanza, path) return getUsingPath(stanza, path); end
82 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
83 -----------
84
85 local room_mt = {};
86 room_mt.__index = room_mt;
87
88 function room_mt:get_default_role(affiliation)
89         if affiliation == "owner" or affiliation == "admin" then
90                 return "moderator";
91         elseif affiliation == "member" or not affiliation then
92                 return "participant";
93         end
94 end
95
96 function room_mt:broadcast_presence(stanza, sid, code, nick)
97         stanza = get_filtered_presence(stanza);
98         local occupant = self._occupants[stanza.attr.from];
99         stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
100                 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none", nick=nick}):up();
101         if code then
102                 stanza:tag("status", {code=code}):up();
103         end
104         self:broadcast_except_nick(stanza, stanza.attr.from);
105         local me = self._occupants[stanza.attr.from];
106         if me then
107                 stanza:tag("status", {code='110'});
108                 stanza.attr.to = sid;
109                 self:_route_stanza(stanza);
110         end
111 end
112 function room_mt:broadcast_message(stanza, historic)
113         local to = stanza.attr.to;
114         for occupant, o_data in pairs(self._occupants) do
115                 for jid in pairs(o_data.sessions) do
116                         stanza.attr.to = jid;
117                         self:_route_stanza(stanza);
118                 end
119         end
120         stanza.attr.to = to;
121         if historic then -- add to history
122                 local history = self._data['history'];
123                 if not history then history = {}; self._data['history'] = history; end
124                 stanza = st.clone(stanza);
125                 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = datetime.datetime()}):up(); -- XEP-0203
126                 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
127                 t_insert(history, st.preserialize(stanza));
128                 while #history > history_length do t_remove(history, 1) end
129         end
130 end
131 function room_mt:broadcast_except_nick(stanza, nick)
132         for rnick, occupant in pairs(self._occupants) do
133                 if rnick ~= nick then
134                         for jid in pairs(occupant.sessions) do
135                                 stanza.attr.to = jid;
136                                 self:_route_stanza(stanza);
137                         end
138                 end
139         end
140 end
141
142 function room_mt:send_occupant_list(to)
143         local current_nick = self._jid_nick[to];
144         for occupant, o_data in pairs(self._occupants) do
145                 if occupant ~= current_nick then
146                         local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
147                         pres.attr.to, pres.attr.from = to, occupant;
148                         pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
149                                 :tag("item", {affiliation=o_data.affiliation or "none", role=o_data.role or "none"}):up();
150                         self:_route_stanza(pres);
151                 end
152         end
153 end
154 function room_mt:send_history(to)
155         local history = self._data['history']; -- send discussion history
156         if history then
157                 for _, msg in ipairs(history) do
158                         msg = st.deserialize(msg);
159                         msg.attr.to=to;
160                         self:_route_stanza(msg);
161                 end
162         end
163         if self._data['subject'] then
164                 self:_route_stanza(st.message({type='groupchat', from=self.jid, to=to}):tag("subject"):text(self._data['subject']));
165         end
166 end
167
168 function room_mt:get_disco_info(stanza)
169         return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
170                 :tag("identity", {category="conference", type="text"}):up()
171                 :tag("feature", {var="http://jabber.org/protocol/muc"});
172 end
173 function room_mt:get_disco_items(stanza)
174         local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
175         for room_jid in pairs(self._occupants) do
176                 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
177         end
178         return reply;
179 end
180 function room_mt:set_subject(current_nick, subject)
181         -- TODO check nick's authority
182         if subject == "" then subject = nil; end
183         self._data['subject'] = subject;
184         if self.save then self:save(); end
185         local msg = st.message({type='groupchat', from=current_nick})
186                 :tag('subject'):text(subject):up();
187         self:broadcast_message(msg, false);
188         return true;
189 end
190
191 local function build_unavailable_presence_from_error(stanza)
192         local type, condition, text = stanza:get_error();
193         local error_message = "Kicked: "..condition:gsub("%-", " ");
194         if text then
195                 error_message = error_message..": "..text;
196         end
197         return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
198                 :tag('status'):text(error_message);
199 end
200
201 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
202         local from, to = stanza.attr.from, stanza.attr.to;
203         local room = jid_bare(to);
204         local current_nick = self._jid_nick[from];
205         local type = stanza.attr.type;
206         log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
207         if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
208         if stanza.name == "presence" then
209                 local pr = get_filtered_presence(stanza);
210                 pr.attr.from = current_nick;
211                 if type == "error" then -- error, kick em out!
212                         if current_nick then
213                                 log("debug", "kicking %s from %s", current_nick, room);
214                                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza));
215                         end
216                 elseif type == "unavailable" then -- unavailable
217                         if current_nick then
218                                 log("debug", "%s leaving %s", current_nick, room);
219                                 local occupant = self._occupants[current_nick];
220                                 local new_jid = next(occupant.sessions);
221                                 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
222                                 if new_jid then
223                                         local jid = occupant.jid;
224                                         occupant.jid = new_jid;
225                                         occupant.sessions[from] = nil;
226                                         pr.attr.to = from;
227                                         pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
228                                                 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
229                                                 :tag("status", {code='110'});
230                                         self:_route_stanza(pr);
231                                         if jid ~= new_jid then
232                                                 pr = st.clone(occupant.sessions[new_jid])
233                                                         :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
234                                                         :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
235                                                 pr.attr.from = current_nick;
236                                                 self:broadcast_except_nick(pr, current_nick);
237                                         end
238                                 else
239                                         occupant.role = 'none';
240                                         self:broadcast_presence(pr, from);
241                                         self._occupants[current_nick] = nil;
242                                 end
243                                 self._jid_nick[from] = nil;
244                         end
245                 elseif not type then -- available
246                         if current_nick then
247                                 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
248                                         if current_nick == to then -- simple presence
249                                                 log("debug", "%s broadcasted presence", current_nick);
250                                                 self._occupants[current_nick].sessions[from] = pr;
251                                                 self:broadcast_presence(pr, from);
252                                         else -- change nick
253                                                 local occupant = self._occupants[current_nick];
254                                                 local is_multisession = next(occupant.sessions, next(occupant.sessions));
255                                                 if self._occupants[to] or is_multisession then
256                                                         log("debug", "%s couldn't change nick", current_nick);
257                                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
258                                                         reply.tags[1].attr.code = "409";
259                                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
260                                                 else
261                                                         local data = self._occupants[current_nick];
262                                                         local to_nick = select(3, jid_split(to));
263                                                         if to_nick then
264                                                                 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
265                                                                 local p = st.presence({type='unavailable', from=current_nick});
266                                                                 self:broadcast_presence(p, from, '303', to_nick);
267                                                                 self._occupants[current_nick] = nil;
268                                                                 self._occupants[to] = data;
269                                                                 self._jid_nick[from] = to;
270                                                                 pr.attr.from = to;
271                                                                 self._occupants[to].sessions[from] = pr;
272                                                                 self:broadcast_presence(pr, from);
273                                                         else
274                                                                 --TODO malformed-jid
275                                                         end
276                                                 end
277                                         end
278                                 --else -- possible rejoin
279                                 --      log("debug", "%s had connection replaced", current_nick);
280                                 --      self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
281                                 --              :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
282                                 --      self:handle_to_occupant(origin, stanza); -- resend available
283                                 --end
284                         else -- enter room
285                                 local new_nick = to;
286                                 local is_merge;
287                                 if self._occupants[to] then
288                                         if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
289                                                 new_nick = nil;
290                                         end
291                                         is_merge = true;
292                                 end
293                                 if not new_nick then
294                                         log("debug", "%s couldn't join due to nick conflict: %s", from, to);
295                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
296                                         reply.tags[1].attr.code = "409";
297                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
298                                 else
299                                         log("debug", "%s joining as %s", from, to);
300                                         if not next(self._affiliations) then -- new room, no owners
301                                                 self._affiliations[jid_bare(from)] = "owner";
302                                         end
303                                         local affiliation = self:get_affiliation(from);
304                                         local role = self:get_default_role(affiliation)
305                                         if role then -- new occupant
306                                                 if not is_merge then
307                                                         self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
308                                                 else
309                                                         self._occupants[to].sessions[from] = get_filtered_presence(stanza);
310                                                 end
311                                                 self._jid_nick[from] = to;
312                                                 self:send_occupant_list(from);
313                                                 pr.attr.from = to;
314                                                 if not is_merge then
315                                                         self:broadcast_presence(pr, from);
316                                                 else
317                                                         pr.attr.to = from;
318                                                         self:_route_stanza(pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
319                                                                 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up()
320                                                                 :tag("status", {code='110'}));
321                                                 end
322                                                 self:send_history(from);
323                                         else -- banned
324                                                 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
325                                                 reply.tags[1].attr.code = "403";
326                                                 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
327                                         end
328                                 end
329                         end
330                 elseif type ~= 'result' then -- bad type
331                         if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
332                                 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
333                         end
334                 end
335         elseif not current_nick then -- not in room
336                 if type == "error" or type == "result" then
337                         local id = stanza.name == "iq" and stanza.attr.id and base64.decode(stanza.attr.id);
338                         local _nick, _id, _hash = (id or ""):match("^(.+)%z(.*)%z(.+)$");
339                         local occupant = self._occupants[stanza.attr.to];
340                         if occupant and _nick and self._jid_nick[_nick] and _id and _hash then
341                                 local id, _to = stanza.attr.id;
342                                 for jid in pairs(occupant.sessions) do
343                                         if md5(jid) == _hash then
344                                                 _to = jid;
345                                                 break;
346                                         end
347                                 end
348                                 if _to then
349                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = _to, self._jid_nick[_nick], _id;
350                                         self:_route_stanza(stanza);
351                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
352                                 end
353                         end
354                 else
355                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
356                 end
357         elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
358                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
359         elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
360                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
361                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
362         else -- private stanza
363                 local o_data = self._occupants[to];
364                 if o_data then
365                         log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
366                         local jid = o_data.jid;
367                         local bare = jid_bare(jid);
368                         stanza.attr.to, stanza.attr.from = jid, current_nick;
369                         local id = stanza.attr.id;
370                         if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' and bare ~= jid then
371                                 stanza.attr.to = bare;
372                                 stanza.attr.id = base64.encode(jid.."\0"..id.."\0"..md5(from));
373                         end
374                         self:_route_stanza(stanza);
375                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
376                 elseif type ~= "error" and type ~= "result" then -- recipient not in room
377                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
378                 end
379         end
380 end
381
382 function room_mt:send_form(origin, stanza)
383         local title = "Configuration for "..self.jid;
384         origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
385                 :tag("x", {xmlns='jabber:x:data', type='form'})
386                         :tag("title"):text(title):up()
387                         :tag("instructions"):text(title):up()
388                         :tag("field", {type='hidden', var='FORM_TYPE'}):tag("value"):text("http://jabber.org/protocol/muc#roomconfig"):up():up()
389                         :tag("field", {type='boolean', label='Make Room Persistent?', var='muc#roomconfig_persistentroom'})
390                                 :tag("value"):text(self._data.persistent and "1" or "0"):up()
391                         :up()
392                         :tag("field", {type='boolean', label='Make Room Publicly Searchable?', var='muc#roomconfig_publicroom'})
393                                 :tag("value"):text(self._data.hidden and "0" or "1"):up()
394                         :up()
395                         :tag("field", {type='list-single', label='Who May Discover Real JIDs?', var='muc#roomconfig_whois'})
396                             :tag("value"):text(self._data.whois or 'moderators'):up()
397                             :tag("option", {label = 'Moderators Only'})
398                                 :tag("value"):text('moderators'):up()
399                                 :up()
400                             :tag("option", {label = 'Anyone'})
401                                 :tag("value"):text('anyone'):up()
402                                 :up()
403                         :up()
404         );
405 end
406
407 local valid_whois = {
408     moderators = true,
409     anyone = true,
410 }
411
412 function room_mt:process_form(origin, stanza)
413         local query = stanza.tags[1];
414         local form;
415         for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
416         if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
417         if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
418         if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
419         local fields = {};
420         for _, field in pairs(form.tags) do
421                 if field.name == "field" and field.attr.var and field.tags[1].name == "value" and #field.tags[1].tags == 0 then
422                         fields[field.attr.var] = field.tags[1][1] or "";
423                 end
424         end
425         if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
426
427         local dirty = false
428
429         local persistent = fields['muc#roomconfig_persistentroom'];
430         if persistent == "0" or persistent == "false" then persistent = nil; elseif persistent == "1" or persistent == "true" then persistent = true;
431         else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
432         dirty = dirty or (self._data.persistent ~= persistent)
433         self._data.persistent = persistent;
434         module:log("debug", "persistent=%s", tostring(persistent));
435
436         local public = fields['muc#roomconfig_publicroom'];
437         if public == "0" or public == "false" then public = nil; elseif public == "1" or public == "true" then public = true;
438         else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
439         dirty = dirty or (self._data.hidden ~= (not public and true or nil))
440         self._data.hidden = not public and true or nil;
441
442         local whois = fields['muc#roomconfig_whois'];
443         if not valid_whois[whois] then
444             origin.send(st.error_reply(stanza, 'cancel', 'bad-request'));
445             return;
446         end
447         local whois_changed = self._data.whois ~= whois
448         self._data.whois = whois
449         module:log('debug', 'whois=%s', tostring(whois))
450
451         if self.save then self:save(true); end
452         origin.send(st.reply(stanza));
453
454         if dirty or whois_changed then
455             local msg = st.message({type='groupchat', from=self.jid})
456                     :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
457
458             if dirty then
459                 msg.tags[1]:tag('status', {code = '104'})
460             end
461             if whois_changed then
462                 local code = (whois == 'moderators') and 173 or 172
463                 msg.tags[1]:tag('status', {code = code})
464             end
465
466             self:broadcast_message(msg, false)
467         end
468 end
469
470 function room_mt:destroy(newjid, reason, password)
471         local pr = st.presence({type = "unavailable"})
472                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
473                         :tag("item", { affiliation='none', role='none' }):up()
474                         :tag("destroy", {jid=newjid})
475         if reason then pr:tag("reason"):text(reason):up(); end
476         if password then pr:tag("password"):text(password):up(); end
477         for nick, occupant in pairs(self._occupants) do
478                 pr.attr.from = nick;
479                 for jid in pairs(occupant.sessions) do
480                         pr.attr.to = jid;
481                         self:_route_stanza(pr);
482                         self._jid_nick[jid] = nil;
483                 end
484                 self._occupants[nick] = nil;
485         end
486         self._data.persistent = nil;
487         if self.save then self:save(true); end
488 end
489
490 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
491         local type = stanza.attr.type;
492         local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
493         if stanza.name == "iq" then
494                 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then
495                         origin.send(self:get_disco_info(stanza));
496                 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then
497                         origin.send(self:get_disco_items(stanza));
498                 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
499                         local actor = stanza.attr.from;
500                         local affiliation = self:get_affiliation(actor);
501                         local current_nick = self._jid_nick[actor];
502                         local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
503                         local item = stanza.tags[1].tags[1];
504                         if item and item.name == "item" then
505                                 if type == "set" then
506                                         local callback = function() origin.send(st.reply(stanza)); end
507                                         if item.attr.jid then -- Validate provided JID
508                                                 item.attr.jid = jid_prep(item.attr.jid);
509                                                 if not item.attr.jid then
510                                                         origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
511                                                         return;
512                                                 end
513                                         end
514                                         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
515                                                 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
516                                                 if occupant then item.attr.jid = occupant.jid; end
517                                         elseif not item.attr.nick and item.attr.jid then
518                                                 local nick = self._jid_nick[item.attr.jid];
519                                                 if nick then item.attr.nick = select(3, jid_split(nick)); end
520                                         end
521                                         local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
522                                         if item.attr.affiliation and item.attr.jid and not item.attr.role then
523                                                 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
524                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
525                                         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
526                                                 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
527                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
528                                         else
529                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
530                                         end
531                                 elseif type == "get" then
532                                         local _aff = item.attr.affiliation;
533                                         local _rol = item.attr.role;
534                                         if _aff and not _rol then
535                                                 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
536                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
537                                                         for jid, affiliation in pairs(self._affiliations) do
538                                                                 if affiliation == _aff then
539                                                                         reply:tag("item", {affiliation = _aff, jid = jid}):up();
540                                                                 end
541                                                         end
542                                                         origin.send(reply);
543                                                 else
544                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
545                                                 end
546                                         elseif _rol and not _aff then
547                                                 if role == "moderator" then
548                                                         -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
549                                                         if _rol == "none" then _rol = nil; end
550                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
551                                                         for occupant_jid, occupant in pairs(self._occupants) do
552                                                                 if occupant.role == _rol then
553                                                                         reply:tag("item", {
554                                                                                 nick = select(3, jid_split(occupant_jid)),
555                                                                                 role = _rol or "none",
556                                                                                 affiliation = occupant.affiliation or "none",
557                                                                                 jid = occupant.jid
558                                                                                 }):up();
559                                                                 end
560                                                         end
561                                                         origin.send(reply);
562                                                 else
563                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
564                                                 end
565                                         else
566                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
567                                         end
568                                 end
569                         elseif type == "set" or type == "get" then
570                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
571                         end
572                 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
573                         if self:get_affiliation(stanza.attr.from) ~= "owner" then
574                                 origin.send(st.error_reply(stanza, "auth", "forbidden"));
575                         elseif stanza.attr.type == "get" then
576                                 self:send_form(origin, stanza);
577                         elseif stanza.attr.type == "set" then
578                                 local child = stanza.tags[1].tags[1];
579                                 if not child then
580                                         origin.send(st.error_reply(stanza, "auth", "bad-request"));
581                                 elseif child.name == "destroy" then
582                                         local newjid = child.attr.jid;
583                                         local reason, password;
584                                         for _,tag in ipairs(child.tags) do
585                                                 if tag.name == "reason" then
586                                                         reason = #tag.tags == 0 and tag[1];
587                                                 elseif tag.name == "password" then
588                                                         password = #tag.tags == 0 and tag[1];
589                                                 end
590                                         end
591                                         self:destroy(newjid, reason, password);
592                                         origin.send(st.reply(stanza));
593                                 else
594                                         self:process_form(origin, stanza);
595                                 end
596                         end
597                 elseif type == "set" or type == "get" then
598                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
599                 end
600         elseif stanza.name == "message" and type == "groupchat" then
601                 local from, to = stanza.attr.from, stanza.attr.to;
602                 local room = jid_bare(to);
603                 local current_nick = self._jid_nick[from];
604                 local occupant = self._occupants[current_nick];
605                 if not occupant then -- not in room
606                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
607                 elseif occupant.role == "visitor" then
608                         origin.send(st.error_reply(stanza, "cancel", "forbidden"));
609                 else
610                         local from = stanza.attr.from;
611                         stanza.attr.from = current_nick;
612                         local subject = getText(stanza, {"subject"});
613                         if subject then
614                                 if occupant.role == "moderator" then
615                                         self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
616                                 else
617                                         stanza.attr.from = from;
618                                         origin.send(st.error_reply(stanza, "cancel", "forbidden"));
619                                 end
620                         else
621                                 self:broadcast_message(stanza, true);
622                         end
623                         stanza.attr.from = from;
624                 end
625         elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
626                 local current_nick = self._jid_nick[stanza.attr.from];
627                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
628                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
629         elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
630                 local to = stanza.attr.to;
631                 local current_nick = self._jid_nick[stanza.attr.from];
632                 if current_nick then
633                         stanza.attr.to = current_nick;
634                         self:handle_to_occupant(origin, stanza);
635                         stanza.attr.to = to;
636                 elseif type ~= "error" and type ~= "result" then
637                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
638                 end
639         elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
640                 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
641                 local x = stanza.tags[1];
642                 local payload = (#x.tags == 1 and x.tags[1]);
643                 if payload and payload.name == "invite" and payload.attr.to then
644                         local _from, _to = stanza.attr.from, stanza.attr.to;
645                         local _invitee = jid_prep(payload.attr.to);
646                         if _invitee then
647                                 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
648                                 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
649                                         :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
650                                                 :tag('invite', {from=_from})
651                                                         :tag('reason'):text(_reason or ""):up()
652                                                 :up()
653                                         :up()
654                                         :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
655                                                 :text(_reason or "")
656                                         :up()
657                                         :tag('body') -- Add a plain message for clients which don't support invites
658                                                 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
659                                         :up();
660                                 self:_route_stanza(invite);
661                         else
662                                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
663                         end
664                 else
665                         origin.send(st.error_reply(stanza, "cancel", "bad-request"));
666                 end
667         else
668                 if type == "error" or type == "result" then return; end
669                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
670         end
671 end
672
673 function room_mt:handle_stanza(origin, stanza)
674         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
675         if to_resource then
676                 self:handle_to_occupant(origin, stanza);
677         else
678                 self:handle_to_room(origin, stanza);
679         end
680 end
681
682 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
683
684 function room_mt:get_affiliation(jid)
685         local node, host, resource = jid_split(jid);
686         local bare = node and node.."@"..host or host;
687         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
688         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
689         return result;
690 end
691 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
692         jid = jid_bare(jid);
693         if affiliation == "none" then affiliation = nil; end
694         if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
695                 return nil, "modify", "not-acceptable";
696         end
697         if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
698         if jid_bare(actor) == jid then return nil, "cancel", "not-allowed"; end
699         self._affiliations[jid] = affiliation;
700         local role = self:get_default_role(affiliation);
701         local p = st.presence()
702                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
703                         :tag("item", {affiliation=affiliation or "none", role=role or "none"})
704                                 :tag("reason"):text(reason or ""):up()
705                         :up();
706         local x = p.tags[1];
707         local item = x.tags[1];
708         if not role then -- getting kicked
709                 p.attr.type = "unavailable";
710                 if affiliation == "outcast" then
711                         x:tag("status", {code="301"}):up(); -- banned
712                 else
713                         x:tag("status", {code="321"}):up(); -- affiliation change
714                 end
715         end
716         local modified_nicks = {};
717         for nick, occupant in pairs(self._occupants) do
718                 if jid_bare(occupant.jid) == jid then
719                         if not role then -- getting kicked
720                                 self._occupants[nick] = nil;
721                         else
722                                 t_insert(modified_nicks, nick);
723                                 occupant.affiliation, occupant.role = affiliation, role;
724                         end
725                         p.attr.from = nick;
726                         for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
727                                 if not role then self._jid_nick[jid] = nil; end
728                                 p.attr.to = jid;
729                                 self:_route_stanza(p);
730                         end
731                 end
732         end
733         if self.save then self:save(); end
734         if callback then callback(); end
735         for _, nick in ipairs(modified_nicks) do
736                 p.attr.from = nick;
737                 self:broadcast_except_nick(p, nick);
738         end
739         return true;
740 end
741
742 function room_mt:get_role(nick)
743         local session = self._occupants[nick];
744         return session and session.role or nil;
745 end
746 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
747         if role == "none" then role = nil; end
748         if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
749         if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
750         local occupant = self._occupants[occupant_jid];
751         if not occupant then return nil, "modify", "not-acceptable"; end
752         if occupant.affiliation == "owner" or occupant.affiliation == "admin" then return nil, "cancel", "not-allowed"; end
753         local p = st.presence({from = occupant_jid})
754                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
755                         :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
756                                 :tag("reason"):text(reason or ""):up()
757                         :up();
758         if not role then -- kick
759                 p.attr.type = "unavailable";
760                 self._occupants[occupant_jid] = nil;
761                 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
762                         self._jid_nick[jid] = nil;
763                 end
764                 p:tag("status", {code = "307"}):up();
765         else
766                 occupant.role = role;
767         end
768         for jid in pairs(occupant.sessions) do -- send to all sessions of the nick
769                 p.attr.to = jid;
770                 self:_route_stanza(p);
771         end
772         if callback then callback(); end
773         self:broadcast_except_nick(p, occupant_jid);
774         return true;
775 end
776
777 function room_mt:_route_stanza(stanza)
778         local muc_child;
779         local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
780         local from_occupant = self._occupants[stanza.attr.from];
781         if stanza.name == "presence" then
782                 if to_occupant and from_occupant then
783                         if self._data.whois == 'anyone' then
784                             muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
785                         else
786                                 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
787                                         muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
788                                 end
789                         end
790                 end
791         end
792         if muc_child then
793                 for _, item in pairs(muc_child.tags) do
794                         if item.name == "item" then
795                                 if from_occupant == to_occupant then
796                                         item.attr.jid = stanza.attr.to;
797                                 else
798                                         item.attr.jid = from_occupant.jid;
799                                 end
800                         end
801                 end
802                 if self._data.whois == 'anyone' then
803                     muc_child:tag('status', { code = '100' });
804                 end
805         end
806         self:route_stanza(stanza);
807         if muc_child then
808                 for _, item in pairs(muc_child.tags) do
809                         if item.name == "item" then
810                                 item.attr.jid = nil;
811                         end
812                 end
813         end
814 end
815
816 local _M = {}; -- module "muc"
817
818 function _M.new_room(jid)
819         return setmetatable({
820                 jid = jid;
821                 _jid_nick = {};
822                 _occupants = {};
823                 _data = {
824                     whois = 'moderators',
825                 };
826                 _affiliations = {};
827         }, room_mt);
828 end
829
830 return _M;