• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

processone / ejabberd / 1258

12 Dec 2025 03:57PM UTC coverage: 33.638% (-0.006%) from 33.644%
1258

push

github

badlop
Container: Apply commit a22c88a

ejabberdctl.template: Show meaningful error when ERL_DIST_PORT is in use

15554 of 46240 relevant lines covered (33.64%)

1078.28 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

9.39
/src/mod_admin_extra.erl
1
%%%-------------------------------------------------------------------
2
%%% File    : mod_admin_extra.erl
3
%%% Author  : Badlop <badlop@process-one.net>
4
%%% Purpose : Contributed administrative functions and commands
5
%%% Created : 10 Aug 2008 by Badlop <badlop@process-one.net>
6
%%%
7
%%%
8
%%% ejabberd, Copyright (C) 2002-2025   ProcessOne
9
%%%
10
%%% This program is free software; you can redistribute it and/or
11
%%% modify it under the terms of the GNU General Public License as
12
%%% published by the Free Software Foundation; either version 2 of the
13
%%% License, or (at your option) any later version.
14
%%%
15
%%% This program is distributed in the hope that it will be useful,
16
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
17
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18
%%% General Public License for more details.
19
%%%
20
%%% You should have received a copy of the GNU General Public License along
21
%%% with this program; if not, write to the Free Software Foundation, Inc.,
22
%%% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23
%%%
24
%%%-------------------------------------------------------------------
25

26
-module(mod_admin_extra).
27
-author('badlop@process-one.net').
28

29
-behaviour(gen_mod).
30

31
-include("logger.hrl").
32
-include("translate.hrl").
33

34
-export([start/2, stop/1, reload/3, mod_options/1,
35
         get_commands_spec/0, depends/2, mod_doc/0]).
36

37
% Commands API
38
-export([
39
         % Adminsys
40
         compile/1, get_cookie/0,
41
         restart_module/2,
42

43
         % Sessions
44
         num_resources/2, resource_num/3,
45
         kick_session/4, status_num/2, status_num/1,
46
         status_list/2, status_list_v3/2,
47
         status_list/1, status_list_v3/1, connected_users_info/0,
48
         connected_users_vhost/1, set_presence/7,
49
         get_presence/2, user_sessions_info/2, get_last/2, set_last/4,
50

51
         % Accounts
52
         set_password/3, check_password_hash/4, delete_old_users/1,
53
         delete_old_users_vhost/2, check_password/3,
54
         list_banned/1, count_banned/1,
55
         ban_account/3, ban_account_v2/3, get_ban_details/2, unban_account/2,
56

57
         % vCard
58
         set_nickname/3, get_vcard/3,
59
         get_vcard/4, get_vcard_multi/4, set_vcard/4,
60
         set_vcard/5,
61

62
         % Roster
63
         add_rosteritem/7, delete_rosteritem/4,
64
         get_roster/2, get_roster_count/2, push_roster/3,
65
         push_roster_all/1, push_alltoall/2,
66
         push_roster_item/5, build_roster_item/3,
67

68
         % Private storage
69
         private_get/4, private_set/3,
70

71
         % Shared roster
72
         srg_create/5, srg_add/2,
73
         srg_delete/2, srg_list/1, srg_get_info/2,
74
         srg_set_info/4,
75
         srg_get_displayed/2, srg_add_displayed/3, srg_del_displayed/3,
76
         srg_get_members/2, srg_user_add/4, srg_user_del/4,
77

78
         % Send message
79
         send_message/5, send_stanza/3, send_stanza_c2s/4,
80

81
         % Privacy list
82
         privacy_set/3,
83

84
         % Stats
85
         stats/1, stats/2
86
        ]).
87
-export([web_menu_main/2, web_page_main/2,
88
         web_menu_host/3, web_page_host/3,
89
         web_menu_hostuser/4, web_page_hostuser/4,
90
         web_menu_hostnode/4, web_page_hostnode/4,
91
         web_menu_node/3, web_page_node/3]).
92

93
-import(ejabberd_web_admin, [make_command/4, make_table/2]).
94

95
-include("ejabberd_commands.hrl").
96
-include("ejabberd_http.hrl").
97
-include("ejabberd_web_admin.hrl").
98
-include("mod_roster.hrl").
99
-include("mod_privacy.hrl").
100
-include("ejabberd_sm.hrl").
101
-include_lib("xmpp/include/scram.hrl").
102
-include_lib("xmpp/include/xmpp.hrl").
103

104
%%%
105
%%% gen_mod
106
%%%
107

108
start(_Host, _Opts) ->
109
    {ok, [{commands, get_commands_spec()},
90✔
110
          {hook, webadmin_menu_main, web_menu_main, 50, global},
111
          {hook, webadmin_page_main, web_page_main, 50, global},
112
          {hook, webadmin_menu_host, web_menu_host, 50},
113
          {hook, webadmin_page_host, web_page_host, 50},
114
          {hook, webadmin_menu_hostuser, web_menu_hostuser, 50},
115
          {hook, webadmin_page_hostuser, web_page_hostuser, 50},
116
          {hook, webadmin_menu_hostnode, web_menu_hostnode, 50},
117
          {hook, webadmin_page_hostnode, web_page_hostnode, 50},
118
          {hook, webadmin_menu_node, web_menu_node, 50, global},
119
          {hook, webadmin_page_node, web_page_node, 50, global}]}.
120

121
stop(_Host) ->
122
    ok.
90✔
123

124
reload(_Host, _NewOpts, _OldOpts) ->
125
    ok.
×
126

127
depends(_Host, _Opts) ->
128
    [].
108✔
129

130
%%%
131
%%% Register commands
132
%%%
133

134
get_commands_spec() ->
135
    Vcard1FieldsString = "Some vcard field names in `get`/`set_vcard` are:\n\n"
90✔
136
        "* FN           - Full Name\n"
137
        "* NICKNAME     - Nickname\n"
138
        "* BDAY         - Birthday\n"
139
        "* TITLE        - Work: Position\n"
140
        "* ROLE         - Work: Role\n",
141

142
    Vcard2FieldsString = "Some vcard field names and subnames in `get`/`set_vcard2` are:\n\n"
90✔
143
        "* N FAMILY     - Family name\n"
144
        "* N GIVEN      - Given name\n"
145
        "* N MIDDLE     - Middle name\n"
146
        "* ADR CTRY     - Address: Country\n"
147
        "* ADR LOCALITY - Address: City\n"
148
        "* TEL HOME     - Telephone: Home\n"
149
        "* TEL CELL     - Telephone: Cellphone\n"
150
        "* TEL WORK     - Telephone: Work\n"
151
        "* TEL VOICE    - Telephone: Voice\n"
152
        "* EMAIL USERID - E-Mail Address\n"
153
        "* ORG ORGNAME  - Work: Company\n"
154
        "* ORG ORGUNIT  - Work: Department\n",
155

156
    VcardXEP = "For a full list of vCard fields check [XEP-0054: vcard-temp]"
90✔
157
        "(https://xmpp.org/extensions/xep-0054.html)",
158

159
    [
160
     #ejabberd_commands{name = compile, tags = [erlang],
90✔
161
                        desc = "Recompile and reload Erlang source code file",
162
                        module = ?MODULE, function = compile,
163
                        args = [{file, string}],
164
                        args_example = ["/home/me/srcs/ejabberd/mod_example.erl"],
165
                        args_desc = ["Filename of erlang source file to compile"],
166
                        result = {res, rescode},
167
                        result_example = ok},
168
     #ejabberd_commands{name = get_cookie, tags = [erlang],
169
                        desc = "Get the Erlang cookie of this node",
170
                        module = ?MODULE, function = get_cookie,
171
                        args = [],
172
                        result = {cookie, string},
173
                        result_example = "MWTAVMODFELNLSMYXPPD",
174
                        result_desc = "Erlang cookie used for authentication by ejabberd"},
175
    #ejabberd_commands{name = restart_module, tags = [erlang],
176
                        desc = "Stop an ejabberd module, reload code and start",
177
                        module = ?MODULE, function = restart_module,
178
                        args = [{host, binary}, {module, binary}],
179
                        args_example = ["myserver.com","mod_admin_extra"],
180
                        args_desc = ["Server name", "Module to restart"],
181
                        result = {res, integer},
182
                        result_example = 0,
183
                        result_desc = "Returns integer code:\n"
184
                                      " - `0`: code reloaded, module restarted\n"
185
                                      " - `1`: error: module not loaded\n"
186
                                      " - `2`: code not reloaded, but module restarted"},
187
     #ejabberd_commands{name = delete_old_users, tags = [accounts, purge],
188
                        desc = "Delete users that didn't log in last days, or that never logged",
189
                        longdesc = "To protect admin accounts, configure this for example:\n"
190
                            "``` yaml\n"
191
                            "access_rules:\n"
192
                            "  protect_old_users:\n"
193
                            "    - allow: admin\n"
194
                            "    - deny: all\n"
195
                            "```\n",
196
                        module = ?MODULE, function = delete_old_users,
197
                        args = [{days, integer}],
198
                        args_example = [30],
199
                        args_desc = ["Last login age in days of accounts that should be removed"],
200
                        result = {res, restuple},
201
                        result_example = {ok, <<"Deleted 2 users: [\"oldman@myserver.com\", \"test@myserver.com\"]">>},
202
                        result_desc = "Result tuple"},
203
     #ejabberd_commands{name = delete_old_users_vhost, tags = [accounts, purge],
204
                        desc = "Delete users that didn't log in last days in vhost, or that never logged",
205
                        longdesc = "To protect admin accounts, configure this for example:\n"
206
                            "``` yaml\n"
207
                            "access_rules:\n"
208
                            "  delete_old_users:\n"
209
                            "    - deny: admin\n"
210
                            "    - allow: all\n"
211
                            "```\n",
212
                        module = ?MODULE, function = delete_old_users_vhost,
213
                        args = [{host, binary}, {days, integer}],
214
                        args_example = [<<"myserver.com">>, 30],
215
                        args_desc = ["Server name",
216
                                     "Last login age in days of accounts that should be removed"],
217
                        result = {res, restuple},
218
                        result_example = {ok, <<"Deleted 2 users: [\"oldman@myserver.com\", \"test@myserver.com\"]">>},
219
                        result_desc = "Result tuple"},
220
     #ejabberd_commands{name = check_account, tags = [accounts],
221
                        desc = "Check if an account exists or not",
222
                        module = ejabberd_auth, function = user_exists,
223
                        args = [{user, binary}, {host, binary}],
224
                        args_example = [<<"peter">>, <<"myserver.com">>],
225
                        args_desc = ["User name to check", "Server to check"],
226
                        result = {res, rescode},
227
                        result_example = ok},
228
     #ejabberd_commands{name = check_password, tags = [accounts],
229
                        desc = "Check if a password is correct",
230
                        module = ?MODULE, function = check_password,
231
                        args = [{user, binary}, {host, binary}, {password, binary}],
232
                        args_example = [<<"peter">>, <<"myserver.com">>, <<"secret">>],
233
                        args_desc = ["User name to check", "Server to check", "Password to check"],
234
                        result = {res, rescode},
235
                        result_example = ok},
236
     #ejabberd_commands{name = check_password_hash, tags = [accounts],
237
                        desc = "Check if the password hash is correct",
238
                        longdesc = "Allows hash methods from the Erlang/OTP "
239
                        "[crypto](https://www.erlang.org/doc/apps/crypto/crypto.html) application.",
240
                        module = ?MODULE, function = check_password_hash,
241
                        args = [{user, binary}, {host, binary}, {passwordhash, binary},
242
                                {hashmethod, binary}],
243
                        args_example = [<<"peter">>, <<"myserver.com">>,
244
                                        <<"5ebe2294ecd0e0f08eab7690d2a6ee69">>, <<"md5">>],
245
                        args_desc = ["User name to check", "Server to check",
246
                                     "Password's hash value", "Name of hash method"],
247
                        result = {res, rescode},
248
                        result_example = ok},
249
     #ejabberd_commands{name = change_password, tags = [accounts],
250
                        desc = "Change the password of an account",
251
                        module = ?MODULE, function = set_password,
252
                        args = [{user, binary}, {host, binary}, {newpass, binary}],
253
                        args_example = [<<"peter">>, <<"myserver.com">>, <<"blank">>],
254
                        args_desc = ["User name", "Server name",
255
                                     "New password for user"],
256
                        result = {res, rescode},
257
                        result_example = ok},
258

259
     #ejabberd_commands{name = list_banned, tags = [accounts],
260
                        desc = "List banned accounts",
261
                        longdesc = "The HOST argument can be `all` to query all vhosts.",
262
                        note = "added in 25.10",
263
                        module = ?MODULE, function = list_banned,
264
                        args = [{host, binary}],
265
                        args_example = [<<"myserver.com">>],
266
                        args_desc = ["Server name"],
267
                        result = {banned, {list, {jid, string}}},
268
                             result_desc = "The list of accounts that are banned",
269
                        result_example = ["attacker@example.com", "user3@example.com"]},
270
     #ejabberd_commands{name = count_banned, tags = [accounts],
271
                        desc = "Count number of banned accounts",
272
                        longdesc = "The HOST argument can be `all` to query all vhosts.",
273
                        note = "added in 25.10",
274
                        module = ?MODULE, function = count_banned,
275
                        args = [{host, binary}],
276
                        args_example = [<<"myserver.com">>],
277
                        args_desc = ["Server name"],
278
                        result_example = 6,
279
                        result_desc = "Number of banned accounts",
280
                        result = {banned, integer}},
281
     #ejabberd_commands{name = ban_account, tags = [accounts],
282
                        desc = "Ban an account: kick sessions and set random password",
283
                        longdesc = "This simply sets a random password.",
284
                        module = ?MODULE, function = ban_account,
285
                        args = [{user, binary}, {host, binary}, {reason, binary}],
286
                        args_example = [<<"attacker">>, <<"myserver.com">>, <<"Spaming other users">>],
287
                        args_desc = ["User name to ban", "Server name",
288
                                     "Reason for banning user"],
289
                        result = {res, rescode},
290
                        result_example = ok},
291
     #ejabberd_commands{name = ban_account, tags = [accounts],
292
                        desc = "Ban an account",
293
                        longdesc = "This command kicks the account sessions, "
294
                        "stores ban details in the account private storage, "
295
                        "which blocks login to the account. "
296
                        "This command requires _`mod_private`_ to be enabled. "
297
                        "Check also _`get_ban_details`_ API "
298
                        "and _`unban_account`_ API.",
299
                        module = ?MODULE, function = ban_account_v2,
300
                        version = 2,
301
                        note = "improved in 25.08",
302
                        args = [{user, binary}, {host, binary}, {reason, binary}],
303
                        args_example = [<<"attacker">>, <<"myserver.com">>, <<"Spaming other users">>],
304
                        args_desc = ["User name to ban", "Server name",
305
                                     "Reason for banning user"],
306
                        result = {res, rescode},
307
                        result_example = ok},
308
     #ejabberd_commands{name = get_ban_details, tags = [accounts],
309
                        desc = "Get ban details about an account",
310
                        longdesc = "Check _`ban_account`_ API.",
311
                        module = ?MODULE, function = get_ban_details,
312
                        version = 2,
313
                        note = "added in 24.06",
314
                        args = [{user, binary}, {host, binary}],
315
                        args_example = [<<"attacker">>, <<"myserver.com">>],
316
                        args_desc = ["Name of a user to check ban information", "Server name"],
317
                        result = {ban_details, {list,
318
                                          {detail, {tuple, [{name, string},
319
                                                            {value, string}
320
                                                           ]}}
321
                                         }},
322
                        result_example = [{"reason", "Spamming other users"},
323
                                          {"bandate", "2024-04-22T09:16:47.975312Z"},
324
                                          {"lastdate", "2024-04-22T08:39:12Z"},
325
                                          {"lastreason", "Connection reset by peer"}]},
326
     #ejabberd_commands{name = unban_account, tags = [accounts],
327
                        desc = "Remove the ban from an account",
328
                        longdesc = "Check _`ban_account`_ API.",
329
                        module = ?MODULE, function = unban_account,
330
                        version = 2,
331
                        note = "added in 24.06",
332
                        args = [{user, binary}, {host, binary}],
333
                        args_example = [<<"gooduser">>, <<"myserver.com">>],
334
                        args_desc = ["User name to unban", "Server name"],
335
                        result = {res, rescode},
336
                        result_example = ok},
337

338
     #ejabberd_commands{name = num_resources, tags = [session],
339
                        desc = "Get the number of resources of a user",
340
                        module = ?MODULE, function = num_resources,
341
                        args = [{user, binary}, {host, binary}],
342
                        args_example = [<<"peter">>, <<"myserver.com">>],
343
                        args_desc = ["User name", "Server name"],
344
                        result = {resources, integer},
345
                        result_example = 5,
346
                        result_desc = "Number of active resources for a user"},
347
     #ejabberd_commands{name = resource_num, tags = [session],
348
                        desc = "Resource string of a session number",
349
                        module = ?MODULE, function = resource_num,
350
                        args = [{user, binary}, {host, binary}, {num, integer}],
351
                        args_example = [<<"peter">>, <<"myserver.com">>, 2],
352
                        args_desc = ["User name", "Server name", "ID of resource to return"],
353
                        result = {resource, string},
354
                        result_example = <<"Psi">>,
355
                        result_desc = "Name of user resource"},
356
     #ejabberd_commands{name = kick_session, tags = [session],
357
                        desc = "Kick a user session",
358
                        module = ?MODULE, function = kick_session,
359
                        args = [{user, binary}, {host, binary}, {resource, binary}, {reason, binary}],
360
                        args_example = [<<"peter">>, <<"myserver.com">>, <<"Psi">>,
361
                                        <<"Stuck connection">>],
362
                        args_desc = ["User name", "Server name", "User's resource",
363
                                     "Reason for closing session"],
364
                        result = {res, rescode},
365
                        result_example = ok},
366
     #ejabberd_commands{name = status_num_host, tags = [session, statistics],
367
                        desc = "Number of logged users with this status in host",
368
                        policy = admin,
369
                        module = ?MODULE, function = status_num,
370
                        args = [{host, binary}, {status, binary}],
371
                        args_example = [<<"myserver.com">>, <<"dnd">>],
372
                        args_desc = ["Server name", "Status type to check"],
373
                        result = {users, integer},
374
                        result_example = 23,
375
                        result_desc = "Number of connected sessions with given status type"},
376
     #ejabberd_commands{name = status_num, tags = [session, statistics],
377
                        desc = "Number of logged users with this status",
378
                        policy = admin,
379
                        module = ?MODULE, function = status_num,
380
                        args = [{status, binary}],
381
                        args_example = [<<"dnd">>],
382
                        args_desc = ["Status type to check"],
383
                        result = {users, integer},
384
                        result_example = 23,
385
                        result_desc = "Number of connected sessions with given status type"},
386
     #ejabberd_commands{name = status_list_host, tags = [session],
387
                        desc = "List of users logged in host with their statuses",
388
                        module = ?MODULE, function = status_list,
389
                        args = [{host, binary}, {status, binary}],
390
                        args_example = [<<"myserver.com">>, <<"dnd">>],
391
                        args_desc = ["Server name", "Status type to check"],
392
                        result_example = [{<<"peter">>,<<"myserver.com">>,<<"tka">>,6,<<"Busy">>}],
393
                        result = {users, {list,
394
                                          {userstatus, {tuple, [
395
                                                                {user, string},
396
                                                                {host, string},
397
                                                                {resource, string},
398
                                                                {priority, integer},
399
                                                                {status, string}
400
                                                               ]}}
401
                                         }}},
402
     #ejabberd_commands{name = status_list_host, tags = [session],
403
                        desc = "List of users logged in host with their statuses",
404
                        module = ?MODULE, function = status_list_v3,
405
                        version = 3,
406
                        note = "updated in 24.12",
407
                        args = [{host, binary}, {status, binary}],
408
                        args_example = [<<"myserver.com">>, <<"dnd">>],
409
                        args_desc = ["Server name", "Status type to check"],
410
                        result_example = [{<<"peter@myserver.com/tka">>,6,<<"Busy">>}],
411
                        result = {users, {list,
412
                                          {userstatus, {tuple, [{jid, string},
413
                                                                {priority, integer},
414
                                                                {status, string}
415
                                                               ]}}
416
                                         }}},
417
     #ejabberd_commands{name = status_list, tags = [session],
418
                        desc = "List of logged users with this status",
419
                        module = ?MODULE, function = status_list,
420
                        args = [{status, binary}],
421
                        args_example = [<<"dnd">>],
422
                        args_desc = ["Status type to check"],
423
                        result_example = [{<<"peter">>,<<"myserver.com">>,<<"tka">>,6,<<"Busy">>}],
424
                        result = {users, {list,
425
                                          {userstatus, {tuple, [
426
                                                                {user, string},
427
                                                                {host, string},
428
                                                                {resource, string},
429
                                                                {priority, integer},
430
                                                                {status, string}
431
                                                               ]}}
432
                                         }}},
433
     #ejabberd_commands{name = status_list, tags = [session],
434
                        desc = "List of logged users with this status",
435
                        module = ?MODULE, function = status_list_v3,
436
                        version = 3,
437
                        note = "updated in 24.12",
438
                        args = [{status, binary}],
439
                        args_example = [<<"dnd">>],
440
                        args_desc = ["Status type to check"],
441
                        result_example = [{<<"peter@myserver.com/tka">>,6,<<"Busy">>}],
442
                        result = {users, {list,
443
                                          {userstatus, {tuple, [{jid, string},
444
                                                                {priority, integer},
445
                                                                {status, string}
446
                                                               ]}}
447
                                         }}},
448
     #ejabberd_commands{name = connected_users_info,
449
                        tags = [session],
450
                        desc = "List all established sessions and their information",
451
                        module = ?MODULE, function = connected_users_info,
452
                        args = [],
453
                        result_example = [{"user1@myserver.com/tka",
454
                                            "c2s", "127.0.0.1", 42656,8, "ejabberd@localhost",
455
                                           231, <<"dnd">>, <<"tka">>, <<>>}],
456
                        result = {connected_users_info,
457
                                  {list,
458
                                   {session, {tuple,
459
                                              [{jid, string},
460
                                               {connection, string},
461
                                               {ip, string},
462
                                               {port, integer},
463
                                               {priority, integer},
464
                                               {node, string},
465
                                               {uptime, integer},
466
                                               {status, string},
467
                                               {resource, string},
468
                                               {statustext, string}
469
                                              ]}}
470
                                  }}},
471

472
     #ejabberd_commands{name = connected_users_vhost,
473
                        tags = [session],
474
                        desc = "Get the list of established sessions in a vhost",
475
                        module = ?MODULE, function = connected_users_vhost,
476
                        args_example = [<<"myexample.com">>],
477
                        args_desc = ["Server name"],
478
                        args = [{host, binary}],
479
                        result_example = [<<"user1@myserver.com/tka">>, <<"user2@localhost/tka">>],
480
                        result_desc = "List of sessions full JIDs",
481
                        result = {connected_users_vhost, {list, {sessions, string}}}},
482
     #ejabberd_commands{name = user_sessions_info,
483
                        tags = [session],
484
                        desc = "Get information about all sessions of a user",
485
                        module = ?MODULE, function = user_sessions_info,
486
                        args = [{user, binary}, {host, binary}],
487
                        args_example = [<<"peter">>, <<"myserver.com">>],
488
                        args_desc = ["User name", "Server name"],
489
                        result_example = [{"c2s", "127.0.0.1", 42656,8, "ejabberd@localhost",
490
                                           231, <<"dnd">>, <<"tka">>, <<>>}],
491
                        result = {sessions_info,
492
                                  {list,
493
                                   {session, {tuple,
494
                                              [{connection, string},
495
                                               {ip, string},
496
                                               {port, integer},
497
                                               {priority, integer},
498
                                               {node, string},
499
                                               {uptime, integer},
500
                                               {status, string},
501
                                               {resource, string},
502
                                               {statustext, string}
503
                                              ]}}
504
                                  }}},
505

506
     #ejabberd_commands{name = get_presence, tags = [session],
507
                        desc =
508
                            "Retrieve the resource with highest priority, "
509
                            "and its presence (show and status message) "
510
                            "for a given user.",
511
                        longdesc =
512
                            "The `jid` value contains the user JID "
513
                            "with resource.\n\nThe `show` value contains "
514
                            "the user presence flag. It can take "
515
                            "limited values:\n\n - `available`\n - `chat` "
516
                            "(Free for chat)\n - `away`\n - `dnd` (Do "
517
                            "not disturb)\n - `xa` (Not available, "
518
                            "extended away)\n - `unavailable` (Not "
519
                            "connected)\n\n`status` is a free text "
520
                            "defined by the user client.",
521
                        module = ?MODULE, function = get_presence,
522
                        args = [{user, binary}, {host, binary}],
523
                        args_rename = [{server, host}],
524
                        args_example = [<<"peter">>, <<"myexample.com">>],
525
                        args_desc = ["User name", "Server name"],
526
                        result_example = {<<"user1@myserver.com/tka">>, <<"dnd">>, <<"Busy">>},
527
                        result =
528
                            {presence,
529
                             {tuple,
530
                              [{jid, string}, {show, string},
531
                               {status, string}]}}},
532
     #ejabberd_commands{name = set_presence,
533
                        tags = [session],
534
                        desc = "Set presence of a session",
535
                        module = ?MODULE, function = set_presence,
536
                        args = [{user, binary}, {host, binary},
537
                                {resource, binary}, {type, binary},
538
                                {show, binary}, {status, binary},
539
                                {priority, binary}],
540
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"tka1">>,
541
                                        <<"available">>,<<"away">>,<<"BB">>, <<"7">>],
542
                        args_desc = ["User name", "Server name", "Resource",
543
                                        "Type: `available`, `error`, `probe`...",
544
                                        "Show: `away`, `chat`, `dnd`, `xa`.", "Status text",
545
                                        "Priority, provide this value as an integer"],
546
                        result = {res, rescode}},
547
     #ejabberd_commands{name = set_presence,
548
                        tags = [session],
549
                        desc = "Set presence of a session",
550
                        module = ?MODULE, function = set_presence,
551
                        version = 1,
552
                        note = "updated in 24.02",
553
                        args = [{user, binary}, {host, binary},
554
                                {resource, binary}, {type, binary},
555
                                {show, binary}, {status, binary},
556
                                {priority, integer}],
557
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"tka1">>,
558
                                        <<"available">>,<<"away">>,<<"BB">>, 7],
559
                        args_desc = ["User name", "Server name", "Resource",
560
                                        "Type: `available`, `error`, `probe`...",
561
                                        "Show: `away`, `chat`, `dnd`, `xa`.", "Status text",
562
                                        "Priority, provide this value as an integer"],
563
                        result = {res, rescode}},
564

565
     #ejabberd_commands{name = set_nickname, tags = [vcard],
566
                        desc = "Set nickname in a user's vCard",
567
                        module = ?MODULE, function = set_nickname,
568
                        args = [{user, binary}, {host, binary}, {nickname, binary}],
569
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"User 1">>],
570
                        args_desc = ["User name", "Server name", "Nickname"],
571
                        result = {res, rescode}},
572
     #ejabberd_commands{name = get_vcard, tags = [vcard],
573
                        desc = "Get content from a vCard field",
574
                        longdesc = Vcard1FieldsString ++ "\n" ++ VcardXEP,
575
                        module = ?MODULE, function = get_vcard,
576
                        args = [{user, binary}, {host, binary}, {name, binary}],
577
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"NICKNAME">>],
578
                        args_desc = ["User name", "Server name", "Field name"],
579
                        result_example = "User 1",
580
                        result_desc = "Field content",
581
                        result = {content, string}},
582
     #ejabberd_commands{name = get_vcard2, tags = [vcard],
583
                        desc = "Get content from a vCard subfield",
584
                        longdesc = Vcard2FieldsString ++ "\n" ++ VcardXEP,
585
                        module = ?MODULE, function = get_vcard,
586
                        args = [{user, binary}, {host, binary}, {name, binary}, {subname, binary}],
587
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"N">>, <<"FAMILY">>],
588
                        args_desc = ["User name", "Server name", "Field name", "Subfield name"],
589
                        result_example = "Schubert",
590
                        result_desc = "Field content",
591
                        result = {content, string}},
592
     #ejabberd_commands{name = get_vcard2_multi, tags = [vcard],
593
                        desc = "Get multiple contents from a vCard field",
594
                        longdesc = Vcard2FieldsString ++ "\n" ++ VcardXEP,
595
                        module = ?MODULE, function = get_vcard_multi,
596
                        args = [{user, binary}, {host, binary}, {name, binary}, {subname, binary}],
597
                        result = {contents, {list, {value, string}}}},
598

599
     #ejabberd_commands{name = set_vcard, tags = [vcard],
600
                        desc = "Set content in a vCard field",
601
                        longdesc = Vcard1FieldsString ++ "\n" ++ VcardXEP,
602
                        module = ?MODULE, function = set_vcard,
603
                        args = [{user, binary}, {host, binary}, {name, binary}, {content, binary}],
604
                        args_example = [<<"user1">>,<<"myserver.com">>, <<"URL">>, <<"www.example.com">>],
605
                        args_desc = ["User name", "Server name", "Field name", "Value"],
606
                        result = {res, rescode}},
607
     #ejabberd_commands{name = set_vcard2, tags = [vcard],
608
                        desc = "Set content in a vCard subfield",
609
                        longdesc = Vcard2FieldsString ++ "\n" ++ VcardXEP,
610
                        module = ?MODULE, function = set_vcard,
611
                        args = [{user, binary}, {host, binary}, {name, binary}, {subname, binary}, {content, binary}],
612
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"TEL">>, <<"NUMBER">>, <<"123456">>],
613
                        args_desc = ["User name", "Server name", "Field name", "Subfield name", "Value"],
614
                        result = {res, rescode}},
615
     #ejabberd_commands{name = set_vcard2_multi, tags = [vcard],
616
                        desc = "Set multiple contents in a vCard subfield",
617
                        longdesc = Vcard2FieldsString ++ "\n" ++ VcardXEP,
618
                        module = ?MODULE, function = set_vcard,
619
                        args = [{user, binary}, {host, binary}, {name, binary}, {subname, binary}, {contents, {list, {value, binary}}}],
620
                        result = {res, rescode}},
621

622
     #ejabberd_commands{name = add_rosteritem, tags = [roster],
623
                        desc = "Add an item to a user's roster (supports ODBC)",
624
                        longdesc = "Group can be several groups separated by `;` for example: `g1;g2;g3`",
625
                        module = ?MODULE, function = add_rosteritem,
626
                        args = [{localuser, binary}, {localhost, binary},
627
                                {user, binary}, {host, binary},
628
                                {nick, binary}, {group, binary},
629
                                {subs, binary}],
630
                        args_rename = [{localserver, localhost}, {server, host}],
631
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"user2">>, <<"myserver.com">>,
632
                                <<"User 2">>, <<"Friends">>, <<"both">>],
633
                        args_desc = ["User name", "Server name", "Contact user name", "Contact server name",
634
                                "Nickname", "Group", "Subscription"],
635
                        result = {res, rescode}},
636
     #ejabberd_commands{name = add_rosteritem, tags = [roster],
637
                        desc = "Add an item to a user's roster (supports ODBC)",
638
                        longdesc = "The client will receive a `jabber:iq:roster` IQ notifying them of the added entry.",
639
                        module = ?MODULE, function = add_rosteritem,
640
                        version = 1,
641
                        note = "updated in 24.02",
642
                        args = [{localuser, binary}, {localhost, binary},
643
                                {user, binary}, {host, binary},
644
                                {nick, binary}, {groups, {list, {group, binary}}},
645
                                {subs, binary}],
646
                        args_rename = [{localserver, localhost}, {server, host}],
647
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"user2">>, <<"myserver.com">>,
648
                                <<"User 2">>, [<<"Friends">>, <<"Team 1">>], <<"both">>],
649
                        args_desc = ["User name", "Server name", "Contact user name", "Contact server name",
650
                                "Nickname", "Groups", "Subscription"],
651
                        result = {res, rescode}},
652
     %%{"", "subs= none, from, to or both"},
653
     %%{"", "example: add-roster peter localhost mike server.com MiKe Employees both"},
654
     %%{"", "will add mike@server.com to peter@localhost roster"},
655
     #ejabberd_commands{name = delete_rosteritem, tags = [roster],
656
                        desc = "Delete an item from a user's roster (supports ODBC)",
657
                        longdesc = "The client will receive a `jabber:iq:roster` IQ notifying them of the removed entry.",
658
                        module = ?MODULE, function = delete_rosteritem,
659
                        args = [{localuser, binary}, {localhost, binary},
660
                                {user, binary}, {host, binary}],
661
                        args_rename = [{localserver, localhost}, {server, host}],
662
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"user2">>, <<"myserver.com">>],
663
                        args_desc = ["User name", "Server name", "Contact user name", "Contact server name"],
664
                        result = {res, rescode}},
665
     #ejabberd_commands{name = process_rosteritems, tags = [roster],
666
                        desc = "List/delete rosteritems that match filter",
667
                        longdesc = "Explanation of each argument:\n\n"
668
                        "* `action`: what to do with each rosteritem that "
669
                        "matches all the filtering options\n"
670
                        "* `subs`: subscription type\n"
671
                        "* `asks`: pending subscription\n"
672
                        "* `users`: the JIDs of the local user\n"
673
                        "* `contacts`: the JIDs of the contact in the roster\n"
674
                        "\n"
675
                        "**Mnesia backend:**\n"
676
                        "\n"
677
                        "Allowed values in the arguments:\n\n"
678
                        "* `action` = `list` | `delete`\n"
679
                        "* `subs` = `any` | SUB[:SUB]*\n"
680
                        "* `asks` = `any` | ASK[:ASK]*\n"
681
                        "* `users` = `any` | JID[:JID]*\n"
682
                        "* `contacts` = `any` | JID[:JID]*\n"
683
                        "\nwhere\n\n"
684
                        "* SUB = `none` | `from `| `to` | `both`\n"
685
                        "* ASK = `none` | `out` | `in`\n"
686
                        "* JID = characters valid in a JID, and can use the "
687
                        "globs: `*`, `?`, `!` and `[...]`\n"
688
                        "\n"
689
                        "This example will list roster items with subscription "
690
                        "`none`, `from` or `to` that have any ask property, of "
691
                        "local users which JID is in the virtual host "
692
                        "`example.org` and that the contact JID is either a "
693
                        "bare server name (without user part) or that has a "
694
                        "user part and the server part contains the word `icq`"
695
                        ":\n  `list none:from:to any *@example.org *:*@*icq*`"
696
                        "\n\n"
697
                        "**SQL backend:**\n"
698
                        "\n"
699
                        "Allowed values in the arguments:\n\n"
700
                        "* `action` = `list` | `delete`\n"
701
                        "* `subs` = `any` | SUB\n"
702
                        "* `asks` = `any` | ASK\n"
703
                        "* `users` = JID\n"
704
                        "* `contacts` = JID\n"
705
                        "\nwhere\n\n"
706
                        "* SUB = `none` | `from` | `to` | `both`\n"
707
                        "* ASK = `none` | `out` | `in`\n"
708
                        "* JID = characters valid in a JID, and can use the "
709
                        "globs: `_` and `%`\n"
710
                        "\n"
711
                        "This example will list roster items with subscription "
712
                        "`to` that have any ask property, of "
713
                        "local users which JID is in the virtual host "
714
                        "`example.org` and that the contact JID's "
715
                        "server part contains the word `icq`"
716
                        ":\n  `list to any %@example.org %@%icq%`",
717
                        module = mod_roster, function = process_rosteritems,
718
                        args = [{action, string}, {subs, string},
719
                                {asks, string}, {users, string},
720
                                {contacts, string}],
721
                        result = {response,
722
                                  {list,
723
                                   {pairs, {tuple,
724
                                               [{user, string},
725
                                                {contact, string}
726
                                               ]}}
727
                                  }}},
728
     #ejabberd_commands{name = get_roster, tags = [roster],
729
                        desc = "Get list of contacts in a local user roster",
730
                        longdesc =
731
                            "`subscription` can be: `none`, `from`, `to`, `both`.\n\n"
732
                            "`pending` can be: `in`, `out`, `none`.",
733
                        note = "improved in 23.10",
734
                        policy = user,
735
                        module = ?MODULE, function = get_roster,
736
                        args = [],
737
                        args_rename = [{server, host}],
738
                        result_example = [{<<"user2@localhost">>, <<"User 2">>, <<"none">>, <<"subscribe">>, [<<"Group1">>]}],
739
                        result = {contacts, {list, {contact, {tuple, [
740
                                                                      {jid, string},
741
                                                                      {nick, string},
742
                                                                      {subscription, string},
743
                                                                      {pending, string},
744
                                                                      {groups, {list, {group, string}}}
745
                                                                     ]}}}}},
746
     #ejabberd_commands{name = get_roster_count, tags = [roster],
747
                        desc = "Get number of contacts in a local user roster",
748
                        note = "added in 24.06",
749
                        policy = user,
750
                        module = ?MODULE, function = get_roster_count,
751
                        args = [],
752
                        args_rename = [{server, host}],
753
                        result_example = 5,
754
                        result_desc = "Number",
755
                        result = {value, integer}},
756
     #ejabberd_commands{name = push_roster, tags = [roster],
757
                        desc = "Push template roster from file to a user",
758
                        longdesc = "The text file must contain an erlang term: a list "
759
                            "of tuples with username, servername, group and nick. For example:\n"
760
                            "`[{\"user1\", \"localhost\", \"Workers\", \"User 1\"},\n"
761
                            " {\"user2\", \"localhost\", \"Workers\", \"User 2\"}].`\n\n"
762
                            "If there are problems parsing UTF8 character encoding, "
763
                            "provide the corresponding string with the `<<\"STRING\"/utf8>>` syntax, for example:\n"
764
                            "`[{\"user2\", \"localhost\", \"Workers\", <<\"User 2\"/utf8>>}]`.",
765
                        module = ?MODULE, function = push_roster,
766
                        args = [{file, binary}, {user, binary}, {host, binary}],
767
                        args_example = [<<"/home/ejabberd/roster.txt">>, <<"user1">>, <<"localhost">>],
768
                        args_desc = ["File path", "User name", "Server name"],
769
                        result = {res, rescode}},
770
     #ejabberd_commands{name = push_roster_all, tags = [roster],
771
                        desc = "Push template roster from file to all those users",
772
                        longdesc = "The text file must contain an erlang term: a list "
773
                            "of tuples with username, servername, group and nick. Example:\n"
774
                            "`[{\"user1\", \"localhost\", \"Workers\", \"User 1\"},\n"
775
                            " {\"user2\", \"localhost\", \"Workers\", \"User 2\"}].`",
776
                        module = ?MODULE, function = push_roster_all,
777
                        args = [{file, binary}],
778
                        args_example = [<<"/home/ejabberd/roster.txt">>],
779
                        args_desc = ["File path"],
780
                        result = {res, rescode}},
781
     #ejabberd_commands{name = push_alltoall, tags = [roster],
782
                        desc = "Add all the users to all the users of Host in Group",
783
                        module = ?MODULE, function = push_alltoall,
784
                        args = [{host, binary}, {group, binary}],
785
                        args_example = [<<"myserver.com">>,<<"Everybody">>],
786
                        args_desc = ["Server name", "Group name"],
787
                        result = {res, rescode}},
788

789
     #ejabberd_commands{name = get_last, tags = [last],
790
                        desc = "Get last activity information",
791
                        longdesc = "Timestamp is UTC and "
792
                            "[XEP-0082](https://xmpp.org/extensions/xep-0082.html)"
793
                            " format, for example: "
794
                            "`2017-02-23T22:25:28.063062Z     ONLINE`",
795
                        module = ?MODULE, function = get_last,
796
                        args = [{user, binary}, {host, binary}],
797
                        args_example = [<<"user1">>,<<"myserver.com">>],
798
                        args_desc = ["User name", "Server name"],
799
                        result_example = {<<"2017-06-30T14:32:16.060684Z">>, "ONLINE"},
800
                        result_desc = "Last activity timestamp and status",
801
                        result = {last_activity,
802
                                  {tuple, [{timestamp, string},
803
                                           {status, string}
804
                                          ]}}},
805
     #ejabberd_commands{name = set_last, tags = [last],
806
                        desc = "Set last activity information",
807
                        longdesc = "Timestamp is the seconds since "
808
                        "`1970-01-01 00:00:00 UTC`. For example value see `date +%s`",
809
                        module = ?MODULE, function = set_last,
810
                        args = [{user, binary}, {host, binary}, {timestamp, integer}, {status, binary}],
811
                        args_example = [<<"user1">>,<<"myserver.com">>, 1500045311, <<"GoSleeping">>],
812
                        args_desc = ["User name", "Server name", "Number of seconds since epoch", "Status message"],
813
                        result = {res, rescode}},
814

815
     #ejabberd_commands{name = private_get, tags = [private],
816
                        desc = "Get some information from a user private storage",
817
                        module = ?MODULE, function = private_get,
818
                        args = [{user, binary}, {host, binary}, {element, binary}, {ns, binary}],
819
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"storage">>, <<"storage:rosternotes">>],
820
                        args_desc = ["User name", "Server name", "Element name", "Namespace"],
821
                        result = {res, string}},
822
     #ejabberd_commands{name = private_set, tags = [private],
823
                        desc = "Set to the user private storage",
824
                        module = ?MODULE, function = private_set,
825
                        args = [{user, binary}, {host, binary}, {element, binary}],
826
                        args_example = [<<"user1">>,<<"myserver.com">>,
827
                            <<"<storage xmlns='storage:rosternotes'/>">>],
828
                        args_desc = ["User name", "Server name", "XML storage element"],
829
                        result = {res, rescode}},
830

831
     #ejabberd_commands{name = srg_create, tags = [shared_roster_group],
832
                        desc = "Create a Shared Roster Group",
833
                        longdesc = "If you want to specify several group "
834
                        "identifiers in the Display argument,\n"
835
                        "put `\\ \"` around the argument and\nseparate the "
836
                        "identifiers with `\\ \\ n`\n"
837
                        "For example:\n"
838
                        "  `ejabberdctl srg_create group3 myserver.com "
839
                        "name desc \\\"group1\\\\ngroup2\\\"`",
840
                        note = "changed in 21.07",
841
                        module = ?MODULE, function = srg_create,
842
                        args = [{group, binary}, {host, binary},
843
                                {label, binary}, {description, binary}, {display, binary}],
844
                        args_rename = [{name, label}],
845
                        args_example = [<<"group3">>, <<"myserver.com">>, <<"Group3">>,
846
                                <<"Third group">>, <<"group1\\\\ngroup2">>],
847
                        args_desc = ["Group identifier", "Group server name", "Group name",
848
                                "Group description", "Groups to display"],
849
                        result = {res, rescode}},
850
     #ejabberd_commands{name = srg_create, tags = [shared_roster_group],
851
                        desc = "Create a Shared Roster Group",
852
                        module = ?MODULE, function = srg_create,
853
                        version = 1,
854
                        note = "updated in 24.02",
855
                        args = [{group, binary}, {host, binary},
856
                                {label, binary}, {description, binary}, {display, {list, {group, binary}}}],
857
                        args_rename = [{name, label}],
858
                        args_example = [<<"group3">>, <<"myserver.com">>, <<"Group3">>,
859
                                <<"Third group">>, [<<"group1">>, <<"group2">>]],
860
                        args_desc = ["Group identifier", "Group server name", "Group name",
861
                                "Group description", "List of groups to display"],
862
                        result = {res, rescode}},
863
     #ejabberd_commands{name = srg_add, tags = [shared_roster_group],
864
                        desc = "Add/Create a Shared Roster Group (without details)",
865
                        module = ?MODULE, function = srg_add,
866
                        note = "added in 24.06",
867
                        args = [{group, binary}, {host, binary}],
868
                        args_example = [<<"group3">>, <<"myserver.com">>],
869
                        args_desc = ["Group identifier", "Group server name"],
870
                        result = {res, rescode}},
871
     #ejabberd_commands{name = srg_delete, tags = [shared_roster_group],
872
                        desc = "Delete a Shared Roster Group",
873
                        module = ?MODULE, function = srg_delete,
874
                        args = [{group, binary}, {host, binary}],
875
                        args_example = [<<"group3">>, <<"myserver.com">>],
876
                        args_desc = ["Group identifier", "Group server name"],
877
                        result = {res, rescode}},
878
     #ejabberd_commands{name = srg_list, tags = [shared_roster_group],
879
                        desc = "List the Shared Roster Groups in Host",
880
                        module = ?MODULE, function = srg_list,
881
                        args = [{host, binary}],
882
                        args_example = [<<"myserver.com">>],
883
                        args_desc = ["Server name"],
884
                        result_example = [<<"group1">>, <<"group2">>],
885
                        result_desc = "List of group identifiers",
886
                        result = {groups, {list, {id, string}}}},
887
     #ejabberd_commands{name = srg_get_info, tags = [shared_roster_group],
888
                        desc = "Get info of a Shared Roster Group",
889
                        module = ?MODULE, function = srg_get_info,
890
                        args = [{group, binary}, {host, binary}],
891
                        args_example = [<<"group3">>, <<"myserver.com">>],
892
                        args_desc = ["Group identifier", "Group server name"],
893
                        result_example = [{<<"name">>, "Group 3"}, {<<"displayed_groups">>, "group1"}],
894
                        result_desc = "List of group information, as key and value",
895
                        result = {informations, {list, {information, {tuple, [{key, string}, {value, string}]}}}}},
896
     #ejabberd_commands{name = srg_set_info, tags = [shared_roster_group],
897
                        desc = "Set info of a Shared Roster Group",
898
                        module = ?MODULE, function = srg_set_info,
899
                        note = "added in 24.06",
900
                        args = [{group, binary}, {host, binary}, {key, binary}, {value, binary}],
901
                        args_example = [<<"group3">>, <<"myserver.com">>, <<"label">>, <<"Family">>],
902
                        args_desc = ["Group identifier", "Group server name",
903
                                     "Information key: label, description",
904
                                     "Information value"],
905
                        result = {res, rescode}},
906

907
     #ejabberd_commands{name = srg_get_displayed, tags = [shared_roster_group],
908
                        desc = "Get displayed groups of a Shared Roster Group",
909
                        module = ?MODULE, function = srg_get_displayed,
910
                        note = "added in 24.06",
911
                        args = [{group, binary}, {host, binary}],
912
                        args_example = [<<"group3">>, <<"myserver.com">>],
913
                        args_desc = ["Group identifier", "Group server name"],
914
                        result_example = [<<"group1">>, <<"group2">>],
915
                        result_desc = "List of groups to display",
916
                        result = {display, {list, {group, binary}}}},
917
     #ejabberd_commands{name = srg_add_displayed, tags = [shared_roster_group],
918
                        desc = "Add a group to displayed_groups of a Shared Roster Group",
919
                        module = ?MODULE, function = srg_add_displayed,
920
                        note = "added in 24.06",
921
                        args = [{group, binary}, {host, binary},
922
                                {add, binary}],
923
                        args_example = [<<"group3">>, <<"myserver.com">>, <<"group1">>],
924
                        args_desc = ["Group identifier", "Group server name",
925
                                "Group to add to displayed_groups"],
926
                        result = {res, rescode}},
927
     #ejabberd_commands{name = srg_del_displayed, tags = [shared_roster_group],
928
                        desc = "Delete a group from displayed_groups of a Shared Roster Group",
929
                        module = ?MODULE, function = srg_del_displayed,
930
                        note = "added in 24.06",
931
                        args = [{group, binary}, {host, binary},
932
                                {del, binary}],
933
                        args_example = [<<"group3">>, <<"myserver.com">>, <<"group1">>],
934
                        args_desc = ["Group identifier", "Group server name",
935
                                "Group to delete from displayed_groups"],
936
                        result = {res, rescode}},
937

938
     #ejabberd_commands{name = srg_get_members, tags = [shared_roster_group],
939
                        desc = "Get members of a Shared Roster Group",
940
                        module = ?MODULE, function = srg_get_members,
941
                        args = [{group, binary}, {host, binary}],
942
                        args_example = [<<"group3">>, <<"myserver.com">>],
943
                        args_desc = ["Group identifier", "Group server name"],
944
                        result_example = [<<"user1@localhost">>, <<"user2@localhost">>],
945
                        result_desc = "List of group identifiers",
946
                        result = {members, {list, {member, string}}}},
947
     #ejabberd_commands{name = srg_user_add, tags = [shared_roster_group],
948
                        desc = "Add the JID user@host to the Shared Roster Group",
949
                        module = ?MODULE, function = srg_user_add,
950
                        args = [{user, binary}, {host, binary}, {group, binary}, {grouphost, binary}],
951
                        args_example = [<<"user1">>, <<"myserver.com">>, <<"group3">>, <<"myserver.com">>],
952
                        args_desc = ["Username", "User server name", "Group identifier", "Group server name"],
953
                        result = {res, rescode}},
954
     #ejabberd_commands{name = srg_user_del, tags = [shared_roster_group],
955
                        desc = "Delete this JID user@host from the Shared Roster Group",
956
                        module = ?MODULE, function = srg_user_del,
957
                        args = [{user, binary}, {host, binary}, {group, binary}, {grouphost, binary}],
958
                        args_example = [<<"user1">>, <<"myserver.com">>, <<"group3">>, <<"myserver.com">>],
959
                        args_desc = ["Username", "User server name", "Group identifier", "Group server name"],
960
                        result = {res, rescode}},
961

962
     #ejabberd_commands{name = get_offline_count,
963
                        tags = [offline],
964
                        desc = "Get the number of unread offline messages",
965
                        policy = user,
966
                        module = mod_offline, function = count_offline_messages,
967
                        args = [],
968
                        args_rename = [{server, host}],
969
                        result_example = 5,
970
                        result_desc = "Number",
971
                        result = {value, integer}},
972
     #ejabberd_commands{name = get_offline_messages,
973
                        tags = [internal, offline],
974
                        desc = "Get the offline messages",
975
                        policy = user,
976
                        module = mod_offline, function = get_offline_messages,
977
                        args = [],
978
                        result = {queue, {list, {messages, {tuple, [{time, string},
979
                                                                    {from, string},
980
                                                                    {to, string},
981
                                                                    {packet, string}
982
                                                                   ]}}}}},
983

984
     #ejabberd_commands{name = send_message, tags = [stanza],
985
                        desc = "Send a message to a local or remote bare of full JID",
986
                        longdesc = "When sending a groupchat message to a MUC room, "
987
                        "`from` must be the full JID of a room occupant, "
988
                        "or the bare JID of a MUC service admin, "
989
                        "or the bare JID of a MUC/Sub subscribed user.",
990
                        module = ?MODULE, function = send_message,
991
                        args = [{type, binary}, {from, binary}, {to, binary},
992
                                {subject, binary}, {body, binary}],
993
                        args_example = [<<"headline">>, <<"admin@localhost">>, <<"user1@localhost">>,
994
                                <<"Restart">>, <<"In 5 minutes">>],
995
                        args_desc = ["Message type: `normal`, `chat`, `headline`, `groupchat`", "Sender JID",
996
                                "Receiver JID", "Subject, or empty string", "Body"],
997
                        result = {res, rescode}},
998
     #ejabberd_commands{name = send_stanza_c2s, tags = [stanza],
999
                        desc = "Send a stanza from an existing C2S session",
1000
                        longdesc = "`user`@`host`/`resource` must be an existing C2S session."
1001
                        " As an alternative, use _`send_stanza`_ API instead.",
1002
                        module = ?MODULE, function = send_stanza_c2s,
1003
                        args = [{user, binary}, {host, binary}, {resource, binary}, {stanza, binary}],
1004
                        args_example = [<<"admin">>, <<"myserver.com">>, <<"bot">>,
1005
                                <<"<message to='user1@localhost'><ext attr='value'/></message>">>],
1006
                        args_desc = ["Username", "Server name", "Resource", "Stanza"],
1007
                        result = {res, rescode}},
1008
     #ejabberd_commands{name = send_stanza, tags = [stanza],
1009
                        desc = "Send a stanza; provide From JID and valid To JID",
1010
                        module = ?MODULE, function = send_stanza,
1011
                        args = [{from, binary}, {to, binary}, {stanza, binary}],
1012
                        args_example = [<<"admin@localhost">>, <<"user1@localhost">>,
1013
                                <<"<message><ext attr='value'/></message>">>],
1014
                        args_desc = ["Sender JID", "Destination JID", "Stanza"],
1015
                        result = {res, rescode}},
1016
     #ejabberd_commands{name = privacy_set, tags = [stanza],
1017
                        desc = "Send a IQ set privacy stanza for a local account",
1018
                        module = ?MODULE, function = privacy_set,
1019
                        args = [{user, binary}, {host, binary}, {xmlquery, binary}],
1020
                        args_example = [<<"user1">>, <<"myserver.com">>,
1021
                                <<"<query xmlns='jabber:iq:privacy'>...">>],
1022
                        args_desc = ["Username", "Server name", "Query XML element"],
1023
                        result = {res, rescode}},
1024

1025
     #ejabberd_commands{name = stats, tags = [statistics],
1026
                        desc = "Get some statistical value for the whole ejabberd server",
1027
                        longdesc = "Allowed statistics `name` are: `registeredusers`, "
1028
                            "`onlineusers`, `onlineusersnode`, `uptimeseconds`, `processes`.",
1029
                        policy = admin,
1030
                        module = ?MODULE, function = stats,
1031
                        args = [{name, binary}],
1032
                        args_example = [<<"registeredusers">>],
1033
                        args_desc = ["Statistic name"],
1034
                        result_example = 6,
1035
                        result_desc = "Integer statistic value",
1036
                        result = {stat, integer}},
1037
     #ejabberd_commands{name = stats_host, tags = [statistics],
1038
                        desc = "Get some statistical value for this host",
1039
                        longdesc = "Allowed statistics `name` are: `registeredusers`, `onlineusers`.",
1040
                        policy = admin,
1041
                        module = ?MODULE, function = stats,
1042
                        args = [{name, binary}, {host, binary}],
1043
                        args_example = [<<"registeredusers">>, <<"example.com">>],
1044
                        args_desc = ["Statistic name", "Server JID"],
1045
                        result_example = 6,
1046
                        result_desc = "Integer statistic value",
1047
                        result = {stat, integer}}
1048
    ].
1049

1050

1051
%%%
1052
%%% Adminsys
1053
%%%
1054

1055
compile(File) ->
1056
    Ebin = filename:join(code:lib_dir(ejabberd), "ebin"),
×
1057
    case ext_mod:compile_erlang_file(Ebin, File) of
×
1058
        {ok, Module} ->
1059
            code:purge(Module),
×
1060
            code:load_file(Module),
×
1061
            ok;
×
1062
        _ ->
1063
            error
×
1064
    end.
1065

1066
get_cookie() ->
1067
    atom_to_list(erlang:get_cookie()).
×
1068

1069
restart_module(Host, Module) when is_binary(Module) ->
1070
    restart_module(Host, misc:binary_to_atom(Module));
×
1071
restart_module(Host, Module) when is_atom(Module) ->
1072
    case gen_mod:is_loaded(Host, Module) of
×
1073
        false ->
1074
            % not a running module, force code reload anyway
1075
            code:purge(Module),
×
1076
            code:delete(Module),
×
1077
            code:load_file(Module),
×
1078
            1;
×
1079
        true ->
1080
            gen_mod:stop_module(Host, Module),
×
1081
            case code:soft_purge(Module) of
×
1082
                true ->
1083
                    code:delete(Module),
×
1084
                    code:load_file(Module),
×
1085
                    gen_mod:start_module(Host, Module),
×
1086
                    0;
×
1087
                false ->
1088
                    gen_mod:start_module(Host, Module),
×
1089
                    2
×
1090
            end
1091
    end.
1092

1093
%%%
1094
%%% Accounts
1095
%%%
1096

1097
set_password(User, Host, Password) ->
1098
    Fun = fun () -> ejabberd_auth:set_password(User, Host, Password) end,
8✔
1099
    user_action(User, Host, Fun, ok).
8✔
1100

1101
check_password(User, Host, Password) ->
1102
    ejabberd_auth:check_password(User, <<>>, Host, Password).
×
1103

1104
%% Copied some code from ejabberd_commands.erln
1105
check_password_hash(User, Host, PasswordHash, HashMethod) ->
1106
    AccountPass = ejabberd_auth:get_password_s(User, Host),
×
1107
    Methods = lists:map(fun(A) -> atom_to_binary(A, latin1) end,
×
1108
                   proplists:get_value(hashs, crypto:supports())),
1109
    MethodAllowed = lists:member(HashMethod, Methods),
×
1110
    AccountPassHash = case {AccountPass, MethodAllowed} of
×
1111
                          {A, _} when is_tuple(A) -> scrammed;
×
1112
                          {_, true} -> get_hash(AccountPass, HashMethod);
×
1113
                          {_, false} ->
1114
                              ?ERROR_MSG("Check_password_hash called "
×
1115
                                         "with hash method: ~p", [HashMethod]),
×
1116
                              undefined
×
1117
                      end,
1118
    case AccountPassHash of
×
1119
        scrammed ->
1120
            ?ERROR_MSG("Passwords are scrammed, and check_password_hash cannot work.", []),
×
1121
            throw(passwords_scrammed_command_cannot_work);
×
1122
        undefined -> throw(unkown_hash_method);
×
1123
        PasswordHash -> ok;
×
1124
        _ -> false
×
1125
    end.
1126

1127
get_hash(AccountPass, Method) ->
1128
    iolist_to_binary([io_lib:format("~2.16.0B", [X])
×
1129
          || X <- binary_to_list(
×
1130
              crypto:hash(binary_to_atom(Method, latin1), AccountPass))]).
1131

1132
delete_old_users(Days) ->
1133
    %% Get the list of registered users
1134
    Users = ejabberd_auth:get_users(),
1✔
1135

1136
    {removed, N, UR} = delete_old_users(Days, Users),
1✔
1137
    {ok, io_lib:format("Deleted ~p users: ~p", [N, UR])}.
1✔
1138

1139
delete_old_users_vhost(Host, Days) ->
1140
    %% Get the list of registered users
1141
    Users = ejabberd_auth:get_users(Host),
×
1142

1143
    {removed, N, UR} = delete_old_users(Days, Users),
×
1144
    {ok, io_lib:format("Deleted ~p users: ~p", [N, UR])}.
×
1145

1146
delete_old_users(Days, Users) ->
1147
    SecOlder = Days*24*60*60,
1✔
1148
    TimeStamp_now = erlang:system_time(second),
1✔
1149
    TimeStamp_oldest = TimeStamp_now - SecOlder,
1✔
1150
    F = fun({LUser, LServer}) ->
1✔
1151
            case catch delete_or_not(LUser, LServer, TimeStamp_oldest) of
2✔
1152
                true ->
1153
                    ejabberd_auth:remove_user(LUser, LServer),
×
1154
                    true;
×
1155
                _ ->
1156
                    false
2✔
1157
            end
1158
        end,
1159
    Users_removed = lists:filter(F, Users),
1✔
1160
    {removed, length(Users_removed), Users_removed}.
1✔
1161

1162
delete_or_not(LUser, LServer, TimeStamp_oldest) ->
1163
    deny = acl:match_rule(LServer, protect_old_users, jid:make(LUser, LServer)),
2✔
1164
    [] = ejabberd_sm:get_user_resources(LUser, LServer),
2✔
1165
    case mod_last:get_last_info(LUser, LServer) of
×
1166
        {ok, TimeStamp, _Status} ->
1167
            if TimeStamp_oldest < TimeStamp ->
×
1168
                    false;
×
1169
                true ->
1170
                    true
×
1171
            end;
1172
        not_found ->
1173
            true
×
1174
    end.
1175

1176
%%
1177
%% Ban account v0
1178

1179
-define(NS_BANNED, <<"jabber:ejabberd:banned">>).
1180

1181
list_banned(<<"all">>) ->
1182
    lists:flatten([list_banned(Host) || Host <- ejabberd_option:hosts()]);
×
1183
list_banned(Host) ->
1184
    [jid:encode(Jid) || Jid <- mod_private:get_users_with_data(Host, ?NS_BANNED)].
×
1185

1186
count_banned(<<"all">>) ->
1187
    lists:sum([count_banned(Host) || Host <- ejabberd_option:hosts()]);
×
1188
count_banned(Host) ->
1189
    mod_private:count_users_with_data(Host, ?NS_BANNED).
×
1190

1191
ban_account(User, Host, ReasonText) ->
1192
    Reason = prepare_reason(ReasonText),
×
1193
    kick_sessions(User, Host, Reason),
×
1194
    set_random_password(User, Host, Reason),
×
1195
    ok.
×
1196

1197
kick_sessions(User, Server, Reason) ->
1198
    ejabberd_hooks:run(sm_kick_user, Server, [User, Server]),
×
1199
    lists:map(
×
1200
      fun(Resource) ->
1201
              kick_this_session(User, Server, Resource, Reason)
×
1202
      end,
1203
      ejabberd_sm:get_user_resources(User, Server)).
1204

1205
set_random_password(User, Server, Reason) ->
1206
    NewPass = build_random_password(Reason),
×
1207
    set_password_auth(User, Server, NewPass).
×
1208

1209
build_random_password(Reason) ->
1210
    {{Year, Month, Day}, {Hour, Minute, Second}} = calendar:universal_time(),
×
1211
    Date = str:format("~4..0B~2..0B~2..0BT~2..0B:~2..0B:~2..0B",
×
1212
                      [Year, Month, Day, Hour, Minute, Second]),
1213
    RandomString = p1_rand:get_string(),
×
1214
    <<"BANNED_ACCOUNT--", Date/binary, "--", RandomString/binary, "--", Reason/binary>>.
×
1215

1216
set_password_auth(User, Server, Password) ->
1217
    ok = ejabberd_auth:set_password(User, Server, Password).
×
1218

1219
prepare_reason([]) ->
1220
    <<"Kicked by administrator">>;
×
1221
prepare_reason([Reason]) ->
1222
    Reason;
×
1223
prepare_reason(Reason) when is_binary(Reason) ->
1224
    Reason.
×
1225

1226
%%
1227
%% Ban account v2
1228

1229
ban_account_v2(User, Host, ReasonText) ->
1230
    IsPrivateEnabled = gen_mod:is_loaded(Host, mod_private),
×
1231
    Exists = ejabberd_auth:user_exists(User, Host),
×
1232
    IsBanned = is_banned(User, Host),
×
1233
    case {IsPrivateEnabled, Exists, IsBanned} of
×
1234
        {true, true, false} ->
1235
            ban_account_v2_b(User, Host, ReasonText);
×
1236
        {false, _, _} ->
1237
            mod_private_is_required_but_disabled;
×
1238
        {_, false, _} ->
1239
            account_does_not_exist;
×
1240
        {_, _, true} ->
1241
            account_was_already_banned;
×
1242
        {_, _, _} ->
1243
            other_error
×
1244
    end.
1245

1246
ban_account_v2_b(User, Host, ReasonText) ->
1247
    Reason = prepare_reason(ReasonText),
×
1248
    Last = get_last(User, Host),
×
1249
    BanDate = xmpp_util:encode_timestamp(erlang:timestamp()),
×
1250
    Hash = get_hash_value(User, Host),
×
1251
    BanPrivateXml = build_ban_xmlel(Reason, Last, BanDate, Hash),
×
1252
    ok = private_set2(User, Host, BanPrivateXml),
×
1253
    kick_sessions(User, Host, Reason),
×
1254
    ok.
×
1255

1256
get_hash_value(User, Host) ->
1257
    Cookie = misc:atom_to_binary(erlang:get_cookie()),
1,952✔
1258
    misc:term_to_base64(crypto:hash(sha256, <<User/binary, Host/binary, Cookie/binary>>)).
1,952✔
1259

1260
build_ban_xmlel(Reason, {LastDate, LastReason}, BanDate, Hash) ->
1261
    #xmlel{name = <<"banned">>,
×
1262
           attrs = [{<<"xmlns">>, ?NS_BANNED}],
1263
           children = [#xmlel{name = <<"reason">>, attrs = [], children = [{xmlcdata, Reason}]},
1264
                       #xmlel{name = <<"lastdate">>, attrs = [], children = [{xmlcdata, LastDate}]},
1265
                       #xmlel{name = <<"lastreason">>, attrs = [], children = [{xmlcdata, LastReason}]},
1266
                       #xmlel{name = <<"bandate">>, attrs = [], children = [{xmlcdata, BanDate}]},
1267
                       #xmlel{name = <<"hash">>, attrs = [], children = [{xmlcdata, Hash}]}
1268
                       ]}.
1269

1270
%%
1271
%% Get ban details
1272

1273
get_ban_details(User, Host) ->
1274
    case private_get2(User, Host, <<"banned">>, ?NS_BANNED) of
2,124✔
1275
        [El] ->
1276
            get_ban_details(User, Host, El);
1,952✔
1277
        [] ->
1278
            []
172✔
1279
    end.
1280

1281
get_ban_details(User, Host, El) ->
1282
    Reason = fxml:get_subtag_cdata(El, <<"reason">>),
1,952✔
1283
    LastDate = fxml:get_subtag_cdata(El, <<"lastdate">>),
1,952✔
1284
    LastReason = fxml:get_subtag_cdata(El, <<"lastreason">>),
1,952✔
1285
    BanDate = fxml:get_subtag_cdata(El, <<"bandate">>),
1,952✔
1286
    Hash = fxml:get_subtag_cdata(El, <<"hash">>),
1,952✔
1287
    case Hash == get_hash_value(User, Host) of
1,952✔
1288
        true ->
1289
            [{"reason", Reason},
×
1290
             {"bandate", BanDate},
1291
             {"lastdate", LastDate},
1292
             {"lastreason", LastReason}];
1293
        false ->
1294
            []
1,952✔
1295
    end.
1296

1297
is_banned(User, Host) ->
1298
    case lists:keyfind("bandate", 1, get_ban_details(User, Host)) of
×
1299
        {_, BanDate} when BanDate /= <<>> ->
1300
            true;
×
1301
        _ ->
1302
            false
×
1303
    end.
1304

1305
%%
1306
%% Unban account
1307

1308
unban_account(User, Host) ->
1309
    IsPrivateEnabled = gen_mod:is_loaded(Host, mod_private),
×
1310
    Exists = ejabberd_auth:user_exists(User, Host),
×
1311
    IsBanned = is_banned(User, Host),
×
1312
    case {IsPrivateEnabled, Exists, IsBanned} of
×
1313
        {true, true, true} ->
1314
            unban_account2(User, Host);
×
1315
        {false, _, _} ->
1316
            mod_private_is_required_but_disabled;
×
1317
        {_, false, _} ->
1318
            account_does_not_exist;
×
1319
        {_, _, false} ->
1320
            account_was_not_banned;
×
1321
        {_, _, _} ->
1322
            other_error
×
1323
    end.
1324

1325
unban_account2(User, Host) ->
1326
    mod_private:del_data(jid:nodeprep(User), jid:nameprep(Host), ?NS_BANNED),
×
1327
        ok.
×
1328

1329
%%%
1330
%%% Sessions
1331
%%%
1332

1333
num_resources(User, Host) ->
1334
    length(ejabberd_sm:get_user_resources(User, Host)).
×
1335

1336
resource_num(User, Host, Num) ->
1337
    Resources = ejabberd_sm:get_user_resources(User, Host),
×
1338
    case (0<Num) and (Num=<length(Resources)) of
×
1339
        true ->
1340
            lists:nth(Num, Resources);
×
1341
        false ->
1342
            throw({bad_argument,
×
1343
                   lists:flatten(io_lib:format("Wrong resource number: ~p", [Num]))})
1344
    end.
1345

1346
kick_session(User, Server, Resource, ReasonText) ->
1347
    kick_this_session(User, Server, Resource, prepare_reason(ReasonText)),
×
1348
    ok.
×
1349

1350
kick_this_session(User, Server, Resource, Reason) ->
1351
    ejabberd_sm:route(jid:make(User, Server, Resource),
×
1352
                      {exit, Reason}).
1353

1354
status_num(Host, Status) ->
1355
    length(get_status_list(Host, Status)).
×
1356
status_num(Status) ->
1357
    status_num(<<"all">>, Status).
×
1358
status_list(Host, Status) ->
1359
    Res = get_status_list(Host, Status),
×
1360
    [{U, S, R, num_prio(P), St} || {U, S, R, P, St} <- Res].
×
1361
status_list(Status) ->
1362
    status_list(<<"all">>, Status).
×
1363

1364
status_list_v3(ArgHost, Status) ->
1365
    List = status_list(ArgHost, Status),
×
1366
    [{jid:encode(jid:make(User, Host, Resource)), Priority, StatusText}
×
1367
     || {User, Host, Resource, Priority, StatusText} <- List].
×
1368

1369
status_list_v3(Status) ->
1370
    status_list_v3(<<"all">>, Status).
×
1371

1372

1373
get_status_list(Host, Status_required) ->
1374
    %% Get list of all logged users
1375
    Sessions = ejabberd_sm:dirty_get_my_sessions_list(),
×
1376
    %% Reformat the list
1377
    Sessions2 = [ {Session#session.usr, Session#session.sid, Session#session.priority} || Session <- Sessions],
×
1378
    Fhost = case Host of
×
1379
                <<"all">> ->
1380
                    %% All hosts are requested, so don't filter at all
1381
                    fun(_, _) -> true end;
×
1382
                _ ->
1383
                    %% Filter the list, only Host is interesting
1384
                    fun(A, B) -> A == B end
×
1385
            end,
1386
    Sessions3 = [ {Pid, Server, Priority} || {{_User, Server, _Resource}, {_, Pid}, Priority} <- Sessions2, apply(Fhost, [Server, Host])],
×
1387
    %% For each Pid, get its presence
1388
    Sessions4 = [ {catch get_presence(Pid), Server, Priority} || {Pid, Server, Priority} <- Sessions3],
×
1389
    %% Filter by status
1390
    Fstatus = case Status_required of
×
1391
                  <<"all">> ->
1392
                      fun(_, _) -> true end;
×
1393
                  StatusList when is_list(StatusList) ->
1394
                      fun(A, B) -> lists:member(A, B) end;
×
1395
                  _ ->
1396
                      fun(A, B) -> A == B end
×
1397
              end,
1398
    [{User, Server, Resource, num_prio(Priority), stringize(Status_text)}
×
1399
     || {{User, Resource, Status, Status_text}, Server, Priority} <- Sessions4,
×
1400
        apply(Fstatus, [Status, Status_required])].
×
1401

1402
connected_users_info() ->
1403
    lists:filtermap(
×
1404
      fun({U, S, R}) ->
1405
            case user_session_info(U, S, R) of
×
1406
                offline ->
1407
                    false;
×
1408
                Info ->
1409
                    Jid = jid:encode(jid:make(U, S, R)),
×
1410
                    {true, erlang:insert_element(1, Info, Jid)}
×
1411
            end
1412
      end,
1413
      ejabberd_sm:dirty_get_sessions_list()).
1414

1415
connected_users_vhost(Host) ->
1416
    USRs = ejabberd_sm:get_vh_session_list(Host),
×
1417
    [ jid:encode(jid:make(USR)) || USR <- USRs].
×
1418

1419
%% Make string more print-friendly
1420
stringize(String) ->
1421
    %% Replace newline characters with other code
1422
    ejabberd_regexp:greplace(String, <<"\n">>, <<"\\n">>).
×
1423

1424
get_presence(Pid) ->
1425
    try get_presence2(Pid) of
×
1426
        {_, _, _, _} = Res ->
1427
            Res
×
1428
    catch
1429
        _:_ -> {<<"">>, <<"">>, <<"offline">>, <<"">>}
×
1430
    end.
1431
get_presence2(Pid) ->
1432
    Pres = #presence{from = From} = ejabberd_c2s:get_presence(Pid),
×
1433
    Show = case Pres of
×
1434
               #presence{type = unavailable} -> <<"unavailable">>;
×
1435
               #presence{show = undefined} -> <<"available">>;
×
1436
               #presence{show = S} -> atom_to_binary(S, utf8)
×
1437
           end,
1438
    Status = xmpp:get_text(Pres#presence.status),
×
1439
    {From#jid.user, From#jid.resource, Show, Status}.
×
1440

1441
get_presence(U, S) ->
1442
    Pids = [ejabberd_sm:get_session_pid(U, S, R)
×
1443
            || R <- ejabberd_sm:get_user_resources(U, S)],
×
1444
    OnlinePids = [Pid || Pid <- Pids, Pid=/=none],
×
1445
    case OnlinePids of
×
1446
        [] ->
1447
            {jid:encode({U, S, <<>>}), <<"unavailable">>, <<"">>};
×
1448
        [SessionPid|_] ->
1449
            {_User, Resource, Show, Status} = get_presence(SessionPid),
×
1450
            FullJID = jid:encode({U, S, Resource}),
×
1451
            {FullJID, Show, Status}
×
1452
    end.
1453

1454
set_presence(User, Host, Resource, Type, Show, Status, Priority) when is_binary(Priority) ->
1455
    set_presence(User, Host, Resource, Type, Show, Status, binary_to_integer(Priority));
×
1456

1457
set_presence(User, Host, Resource, Type, Show, Status, Priority) ->
1458
    Pres = #presence{
×
1459
        from = jid:make(User, Host, Resource),
1460
        to = jid:make(User, Host),
1461
        type = misc:binary_to_atom(Type),
1462
        status = xmpp:mk_text(Status),
1463
        show = misc:binary_to_atom(Show),
1464
        priority = Priority,
1465
        sub_els = []},
1466
    case ejabberd_sm:get_session_pid(User, Host, Resource) of
×
1467
        none -> throw({error, "User session not found"});
×
1468
        Ref -> ejabberd_c2s:set_presence(Ref, Pres)
×
1469
    end.
1470

1471
user_sessions_info(User, Host) ->
1472
    lists:filtermap(fun(Resource) ->
24✔
1473
                            case user_session_info(User, Host, Resource) of
×
1474
                                offline -> false;
×
1475
                                Info -> {true, Info}
×
1476
                            end
1477
                    end, ejabberd_sm:get_user_resources(User, Host)).
1478

1479
user_session_info(User, Host, Resource) ->
1480
    CurrentSec = calendar:datetime_to_gregorian_seconds({date(), time()}),
×
1481
    case ejabberd_sm:get_user_info(User, Host, Resource) of
×
1482
        offline ->
1483
            offline;
×
1484
        Info ->
1485
            Now = proplists:get_value(ts, Info),
×
1486
            Pid = proplists:get_value(pid, Info),
×
1487
            {_U, _Resource, Status, StatusText} = get_presence(Pid),
×
1488
            Priority = proplists:get_value(priority, Info),
×
1489
            Conn = proplists:get_value(conn, Info),
×
1490
            {Ip, Port} = proplists:get_value(ip, Info),
×
1491
            IPS = inet_parse:ntoa(Ip),
×
1492
            NodeS = atom_to_list(node(Pid)),
×
1493
            Uptime = CurrentSec - calendar:datetime_to_gregorian_seconds(
×
1494
                                    calendar:now_to_local_time(Now)),
1495
            {atom_to_list(Conn), IPS, Port, num_prio(Priority), NodeS, Uptime, Status, Resource, StatusText}
×
1496
    end.
1497

1498

1499
%%%
1500
%%% Vcard
1501
%%%
1502

1503
set_nickname(User, Host, Nickname) ->
1504
    VCard = xmpp:encode(#vcard_temp{nickname = Nickname}),
×
1505
    case mod_vcard:set_vcard(User, jid:nameprep(Host), VCard) of
×
1506
        {error, badarg} ->
1507
            error;
×
1508
        ok ->
1509
            ok
×
1510
    end.
1511

1512
get_vcard(User, Host, Name) ->
1513
    [Res | _] = get_vcard_content(User, Host, [Name]),
×
1514
    Res.
×
1515

1516
get_vcard(User, Host, Name, Subname) ->
1517
    [Res | _] = get_vcard_content(User, Host, [Name, Subname]),
×
1518
    Res.
×
1519

1520
get_vcard_multi(User, Host, Name, Subname) ->
1521
    get_vcard_content(User, Host, [Name, Subname]).
×
1522

1523
set_vcard(User, Host, Name, SomeContent) ->
1524
    set_vcard_content(User, Host, [Name], SomeContent).
×
1525

1526
set_vcard(User, Host, Name, Subname, SomeContent) ->
1527
    set_vcard_content(User, Host, [Name, Subname], SomeContent).
×
1528

1529
%%
1530
%% Room vcard
1531

1532
is_muc_service(Domain) ->
1533
    try mod_muc_admin:get_room_serverhost(Domain) of
×
1534
        Domain -> false;
×
1535
        Service when is_binary(Service) -> true
×
1536
    catch _:{unregistered_route, _} ->
1537
            throw(error_wrong_hostname)
×
1538
    end.
1539

1540
get_room_vcard(Name, Service) ->
1541
    case mod_muc_admin:get_room_options(Name, Service) of
×
1542
        [] ->
1543
            throw(error_no_vcard_found);
×
1544
        Opts ->
1545
            case lists:keyfind(<<"vcard">>, 1, Opts) of
×
1546
                false ->
1547
                    throw(error_no_vcard_found);
×
1548
                {_, VCardRaw} ->
1549
                    [fxml_stream:parse_element(VCardRaw)]
×
1550
            end
1551
    end.
1552

1553
%%
1554
%% Internal vcard
1555

1556
get_vcard_content(User, Server, Data) ->
1557
    case get_vcard_element(User, Server) of
×
1558
        [El|_] ->
1559
            case get_vcard(Data, El) of
×
1560
                [false] -> throw(error_no_value_found_in_vcard);
×
1561
                ElemList -> ?DEBUG("ELS ~p", [ElemList]), [fxml:get_tag_cdata(Elem) || Elem <- ElemList]
×
1562
            end;
1563
        [] ->
1564
            throw(error_no_vcard_found);
×
1565
        error ->
1566
            throw(database_failure)
×
1567
    end.
1568

1569
get_vcard_element(User, Server) ->
1570
    case is_muc_service(Server) of
×
1571
        true ->
1572
           get_room_vcard(User, Server);
×
1573
        false ->
1574
           mod_vcard:get_vcard(jid:nodeprep(User), jid:nameprep(Server))
×
1575
    end.
1576

1577
get_vcard([<<"TEL">>, TelType], {_, _, _, OldEls}) ->
1578
    {TakenEl, _NewEls} = take_vcard_tel(TelType, OldEls, [], not_found),
×
1579
    [TakenEl];
×
1580

1581
get_vcard([Data1, Data2], A1) ->
1582
    case get_subtag(A1, Data1) of
×
1583
        [false] -> [false];
×
1584
        A2List ->
1585
            lists:flatten([get_vcard([Data2], A2) || A2 <- A2List])
×
1586
    end;
1587

1588
get_vcard([Data], A1) ->
1589
    get_subtag(A1, Data).
×
1590

1591
get_subtag(Xmlelement, Name) ->
1592
    [fxml:get_subtag(Xmlelement, Name)].
×
1593

1594
set_vcard_content(User, Server, Data, SomeContent) ->
1595
    ContentList = case SomeContent of
×
1596
        [Bin | _] when is_binary(Bin) -> SomeContent;
×
1597
        Bin when is_binary(Bin) -> [SomeContent]
×
1598
    end,
1599
    %% Get old vcard
1600
    A4 = case mod_vcard:get_vcard(jid:nodeprep(User), jid:nameprep(Server)) of
×
1601
             [A1] ->
1602
                 {_, _, _, A2} = A1,
×
1603
                 update_vcard_els(Data, ContentList, A2);
×
1604
             [] ->
1605
                 update_vcard_els(Data, ContentList, []);
×
1606
             error ->
1607
                 throw(database_failure)
×
1608
         end,
1609
    %% Build new vcard
1610
    SubEl = {xmlel, <<"vCard">>, [{<<"xmlns">>,<<"vcard-temp">>}], A4},
×
1611
    mod_vcard:set_vcard(User, jid:nameprep(Server), SubEl).
×
1612

1613
take_vcard_tel(TelType, [{xmlel, <<"TEL">>, _, SubEls}=OldEl | OldEls], NewEls, Taken) ->
1614
    {Taken2, NewEls2} = case lists:keymember(TelType, 2, SubEls) of
×
1615
        true -> {fxml:get_subtag(OldEl, <<"NUMBER">>), NewEls};
×
1616
        false -> {Taken, [OldEl | NewEls]}
×
1617
    end,
1618
    take_vcard_tel(TelType, OldEls, NewEls2, Taken2);
×
1619
take_vcard_tel(TelType, [OldEl | OldEls], NewEls, Taken) ->
1620
    take_vcard_tel(TelType, OldEls, [OldEl | NewEls], Taken);
×
1621
take_vcard_tel(_TelType, [], NewEls, Taken) ->
1622
    {Taken, NewEls}.
×
1623

1624
update_vcard_els([<<"TEL">>, TelType], [TelValue], OldEls) ->
1625
    {_, NewEls} = take_vcard_tel(TelType, OldEls, [], not_found),
×
1626
    NewEl = {xmlel,<<"TEL">>,[],
×
1627
             [{xmlel,TelType,[],[]},
1628
              {xmlel,<<"NUMBER">>,[],[{xmlcdata,TelValue}]}]},
1629
    [NewEl | NewEls];
×
1630

1631
update_vcard_els(Data, ContentList, Els1) ->
1632
    Els2 = lists:keysort(2, Els1),
×
1633
    [Data1 | Data2] = Data,
×
1634
    NewEls = case Data2 of
×
1635
                [] ->
1636
                    [{xmlel, Data1, [], [{xmlcdata,Content}]} || Content <- ContentList];
×
1637
                [D2] ->
1638
                    OldEl = case lists:keysearch(Data1, 2, Els2) of
×
1639
                                {value, A} -> A;
×
1640
                                false -> {xmlel, Data1, [], []}
×
1641
                            end,
1642
                    {xmlel, _, _, ContentOld1} = OldEl,
×
1643
                    Content2 = [{xmlel, D2, [], [{xmlcdata,Content}]} || Content <- ContentList],
×
1644
                    ContentOld2 = [A || {_, X, _, _} = A <- ContentOld1, X/=D2],
×
1645
                    ContentOld3 = lists:keysort(2, ContentOld2),
×
1646
                    ContentNew = lists:keymerge(2, Content2, ContentOld3),
×
1647
                    [{xmlel, Data1, [], ContentNew}]
×
1648
            end,
1649
    Els3 = lists:keydelete(Data1, 2, Els2),
×
1650
    lists:keymerge(2, NewEls, Els3).
×
1651

1652

1653
%%%
1654
%%% Roster
1655
%%%
1656

1657
add_rosteritem(LocalUser, LocalServer, User, Server, Nick, Group, Subs) when is_binary(Group) ->
1658
    add_rosteritem(LocalUser, LocalServer, User, Server, Nick, [Group], Subs);
×
1659
add_rosteritem(LocalUser, LocalServer, User, Server, Nick, Groups, Subs) ->
1660
    case {jid:make(LocalUser, LocalServer), jid:make(User, Server)} of
×
1661
        {error, _} ->
1662
            throw({error, "Invalid 'localuser'/'localserver'"});
×
1663
        {_, error} ->
1664
            throw({error, "Invalid 'user'/'server'"});
×
1665
        {Jid, _Jid2} ->
1666
            RosterItem = build_roster_item(User, Server, {add, Nick, Subs, Groups}),
×
1667
            case mod_roster:set_item_and_notify_clients(Jid, RosterItem, true) of
×
1668
                ok -> ok;
×
1669
                _ -> error
×
1670
            end
1671
    end.
1672

1673
subscribe(LU, LS, User, Server, Nick, Group, Subscription, _Xattrs) ->
1674
    case {jid:make(LU, LS), jid:make(User, Server)} of
×
1675
        {error, _} ->
1676
            throw({error, "Invalid 'localuser'/'localserver'"});
×
1677
        {_, error} ->
1678
            throw({error, "Invalid 'user'/'server'"});
×
1679
        {_Jid, _Jid2} ->
1680
            ItemEl = build_roster_item(User, Server, {add, Nick, Subscription, Group}),
×
1681
            mod_roster:set_items(LU, LS, #roster_query{items = [ItemEl]})
×
1682
    end.
1683

1684
delete_rosteritem(LocalUser, LocalServer, User, Server) ->
1685
    case {jid:make(LocalUser, LocalServer), jid:make(User, Server)} of
×
1686
        {error, _} ->
1687
            throw({error, "Invalid 'localuser'/'localserver'"});
×
1688
        {_, error} ->
1689
            throw({error, "Invalid 'user'/'server'"});
×
1690
        {Jid, _Jid2} ->
1691
            RosterItem = build_roster_item(User, Server, remove),
×
1692
            case mod_roster:set_item_and_notify_clients(Jid, RosterItem, true) of
×
1693
                ok -> ok;
×
1694
                _ -> error
×
1695
            end
1696
    end.
1697

1698
%% -----------------------------
1699
%% Get Roster
1700
%% -----------------------------
1701

1702
get_roster(User, Server) ->
1703
    case jid:make(User, Server) of
×
1704
        error ->
1705
            throw({error, "Invalid 'user'/'server'"});
×
1706
        #jid{luser = U, lserver = S} ->
1707
            Items = ejabberd_hooks:run_fold(roster_get, S, [], [{U, S}]),
×
1708
            make_roster_xmlrpc(Items)
×
1709
    end.
1710

1711
make_roster_xmlrpc(Roster) ->
1712
    lists:map(
×
1713
      fun(#roster_item{jid = JID, name = Nick, subscription = Sub, ask = Ask, groups = Groups}) ->
1714
              JIDS = jid:encode(JID),
×
1715
              Subs = atom_to_list(Sub),
×
1716
              Asks = atom_to_list(Ask),
×
1717
              {JIDS, Nick, Subs, Asks, Groups}
×
1718
      end,
1719
      Roster).
1720

1721
get_roster_count(User, Server) ->
1722
    case jid:make(User, Server) of
48✔
1723
        error ->
1724
            throw({error, "Invalid 'user'/'server'"});
×
1725
        #jid{luser = U, lserver = S} ->
1726
            Items = ejabberd_hooks:run_fold(roster_get, S, [], [{U, S}]),
48✔
1727
            length(Items)
48✔
1728
    end.
1729

1730
%%-----------------------------
1731
%% Push Roster from file
1732
%%-----------------------------
1733

1734
push_roster(File, User, Server) ->
1735
    {ok, [Roster]} = file:consult(File),
×
1736
    subscribe_roster({User, Server, <<>>, User}, Roster).
×
1737

1738
push_roster_all(File) ->
1739
    {ok, [Roster]} = file:consult(File),
×
1740
    subscribe_all(Roster).
×
1741

1742
subscribe_all(Roster) ->
1743
    subscribe_all(Roster, Roster).
×
1744
subscribe_all([], _) ->
1745
    ok;
×
1746
subscribe_all([User1 | Users], Roster) ->
1747
    subscribe_roster(User1, Roster),
×
1748
    subscribe_all(Users, Roster).
×
1749

1750
subscribe_roster(_, []) ->
1751
    ok;
×
1752
%% Do not subscribe a user to itself
1753
subscribe_roster({Name, Server, Group, Nick}, [{Name, Server, _, _} | Roster]) ->
1754
    subscribe_roster({Name, Server, Group, Nick}, Roster);
×
1755
%% Subscribe Name2 to Name1
1756
subscribe_roster({Name1, Server1, Group1, Nick1}, [{Name2, Server2, Group2, Nick2} | Roster]) ->
1757
    subscribe(iolist_to_binary(Name1), iolist_to_binary(Server1), iolist_to_binary(Name2), iolist_to_binary(Server2),
×
1758
        iolist_to_binary(Nick2), iolist_to_binary(Group2), <<"both">>, []),
1759
    subscribe_roster({Name1, Server1, Group1, Nick1}, Roster).
×
1760

1761
push_alltoall(S, G) ->
1762
    Users = ejabberd_auth:get_users(S),
×
1763
    Users2 = build_list_users(G, Users, []),
×
1764
    subscribe_all(Users2),
×
1765
    ok.
×
1766

1767
build_list_users(_Group, [], Res) ->
1768
    Res;
×
1769
build_list_users(Group, [{User, Server}|Users], Res) ->
1770
    build_list_users(Group, Users, [{User, Server, Group, User}|Res]).
×
1771

1772
%% @spec(LU, LS, U, S, Action) -> ok
1773
%%       Action = {add, Nick, Subs, Group} | remove
1774
%% @doc Push to the roster of account LU@LS the contact U@S.
1775
%% The specific action to perform is defined in Action.
1776
push_roster_item(LU, LS, U, S, Action) ->
1777
    lists:foreach(fun(R) ->
×
1778
                          push_roster_item(LU, LS, R, U, S, Action)
×
1779
                  end, ejabberd_sm:get_user_resources(LU, LS)).
1780

1781
push_roster_item(LU, LS, R, U, S, Action) ->
1782
    LJID = jid:make(LU, LS, R),
×
1783
    BroadcastEl = build_broadcast(U, S, Action),
×
1784
    ejabberd_sm:route(LJID, BroadcastEl),
×
1785
    Item = build_roster_item(U, S, Action),
×
1786
    ResIQ = build_iq_roster_push(Item),
×
1787
    ejabberd_router:route(
×
1788
      xmpp:set_from_to(ResIQ, jid:remove_resource(LJID), LJID)).
1789

1790
build_roster_item(U, S, {add, Nick, Subs, Groups}) when is_list(Groups) ->
1791
    #roster_item{jid = jid:make(U, S),
×
1792
                 name = Nick,
1793
                 subscription = misc:binary_to_atom(Subs),
1794
                 groups = Groups};
1795
build_roster_item(U, S, {add, Nick, Subs, Group}) ->
1796
    Groups = binary:split(Group,<<";">>, [global, trim]),
×
1797
    #roster_item{jid = jid:make(U, S),
×
1798
                 name = Nick,
1799
                 subscription = misc:binary_to_atom(Subs),
1800
                 groups = Groups};
1801
build_roster_item(U, S, remove) ->
1802
    #roster_item{jid = jid:make(U, S), subscription = remove}.
×
1803

1804
build_iq_roster_push(Item) ->
1805
    #iq{type = set, id = <<"push">>,
×
1806
        sub_els = [#roster_query{items = [Item]}]}.
1807

1808
build_broadcast(U, S, {add, _Nick, Subs, _Group}) ->
1809
    build_broadcast(U, S, list_to_atom(binary_to_list(Subs)));
×
1810
build_broadcast(U, S, remove) ->
1811
    build_broadcast(U, S, none);
×
1812
%% @spec (U::binary(), S::binary(), Subs::atom()) -> any()
1813
%% Subs = both | from | to | none
1814
build_broadcast(U, S, SubsAtom) when is_atom(SubsAtom) ->
1815
    {item, {U, S, <<>>}, SubsAtom}.
×
1816

1817
%%%
1818
%%% Last Activity
1819
%%%
1820

1821
get_last(User, Server) ->
1822
    {Now, Status} = case ejabberd_sm:get_user_resources(User, Server) of
72✔
1823
        [] ->
1824
            case mod_last:get_last_info(User, Server) of
72✔
1825
                not_found ->
1826
                    {erlang:timestamp(), "NOT FOUND"};
×
1827
                {ok, Shift, Status1} ->
1828
                    {{Shift div 1000000, Shift rem 1000000, 0}, Status1}
72✔
1829
            end;
1830
        _ ->
1831
            {erlang:timestamp(), "ONLINE"}
×
1832
    end,
1833
    {xmpp_util:encode_timestamp(Now), Status}.
72✔
1834

1835
set_last(User, Server, Timestamp, Status) ->
1836
    case mod_last:store_last_info(User, Server, Timestamp, Status) of
×
1837
        {ok, _} -> ok;
×
1838
        Error -> Error
×
1839
    end.
1840

1841
%%%
1842
%%% Private Storage
1843
%%%
1844

1845
%% Example usage:
1846
%% $ ejabberdctl private_set badlop localhost "\<aa\ xmlns=\'bb\'\>Cluth\</aa\>"
1847
%% $ ejabberdctl private_get badlop localhost aa bb
1848
%% <aa xmlns='bb'>Cluth</aa>
1849

1850
private_get(Username, Host, Element, Ns) ->
1851
    Els = private_get2(Username, Host, Element, Ns),
×
1852
    binary_to_list(fxml:element_to_binary(xmpp:encode(#private{sub_els = Els}))).
×
1853

1854
private_get2(Username, Host, Element, Ns) ->
1855
    case gen_mod:is_loaded(Host, mod_private) of
2,124✔
1856
        true -> private_get3(Username, Host, Element, Ns);
1,952✔
1857
        false -> []
172✔
1858
    end.
1859

1860
private_get3(Username, Host, Element, Ns) ->
1861
    ElementXml = #xmlel{name = Element, attrs = [{<<"xmlns">>, Ns}]},
1,952✔
1862
    mod_private:get_data(jid:nodeprep(Username), jid:nameprep(Host),
1,952✔
1863
                               [{Ns, ElementXml}]).
1864

1865
private_set(Username, Host, ElementString) ->
1866
    case fxml_stream:parse_element(ElementString) of
×
1867
        {error, Error} ->
1868
            io:format("Error found parsing the element:~n  ~p~nError: ~p~n",
×
1869
                      [ElementString, Error]),
1870
            error;
×
1871
        Xml ->
1872
            private_set2(Username, Host, Xml)
×
1873
    end.
1874

1875
private_set2(Username, Host, Xml) ->
1876
    NS = fxml:get_tag_attr_s(<<"xmlns">>, Xml),
×
1877
    JID = jid:make(Username, Host),
×
1878
    mod_private:set_data(JID, [{NS, Xml}]).
×
1879

1880
%%%
1881
%%% Shared Roster Groups
1882
%%%
1883

1884
srg_create(Group, Host, Label, Description, Display) when is_binary(Display) ->
1885
    DisplayList = case Display of
×
1886
       <<>> -> [];
×
1887
       _ -> ejabberd_regexp:split(Display, <<"\\\\n">>)
×
1888
    end,
1889
    srg_create(Group, Host, Label, Description, DisplayList);
×
1890

1891
srg_create(Group, Host, Label, Description, DisplayList) ->
1892
    {_DispGroups, WrongDispGroups} = filter_groups_existence(Host, DisplayList),
×
1893
    case (WrongDispGroups -- [Group]) /= [] of
×
1894
        true ->
1895
            {wrong_displayed_groups, WrongDispGroups};
×
1896
        false ->
1897
            srg_create2(Group, Host, Label, Description, DisplayList)
×
1898
    end.
1899

1900
srg_create2(Group, Host, Label, Description, DisplayList) ->
1901
    Opts = [{label, Label},
×
1902
            {displayed_groups, DisplayList},
1903
            {description, Description}],
1904
    case mod_shared_roster:create_group(Host, Group, Opts) of
×
1905
        {atomic, _} -> ok;
×
1906
        {error, Err} -> Err
×
1907
    end.
1908

1909
srg_add(Group, Host) ->
1910
    Opts = [{label, <<"">>},
×
1911
            {description, <<"">>},
1912
            {displayed_groups, []}
1913
           ],
1914
    case mod_shared_roster:create_group(Host, Group, Opts) of
×
1915
        {atomic, _} -> ok;
×
1916
        {error, Err} -> Err
×
1917
    end.
1918

1919
srg_delete(Group, Host) ->
1920
    {atomic, _} = mod_shared_roster:delete_group(Host, Group),
×
1921
    ok.
×
1922

1923
srg_list(Host) ->
1924
    lists:sort(mod_shared_roster:list_groups(Host)).
×
1925

1926
srg_get_info(Group, Host) ->
1927
    Opts = case mod_shared_roster:get_group_opts(Host,Group) of
×
1928
        Os when is_list(Os) -> Os;
×
1929
        error -> []
×
1930
    end,
1931
    [{misc:atom_to_binary(Title), to_list(Value)} || {Title, Value} <- Opts].
×
1932

1933
to_list([]) -> [];
×
1934
to_list([H|_]=List) when is_binary(H) -> lists:join(", ", [to_list(E) || E <- List]);
×
1935
to_list(E) when is_atom(E) -> atom_to_list(E);
×
1936
to_list(E) when is_binary(E) -> binary_to_list(E).
×
1937

1938
%% @format-begin
1939

1940
srg_set_info(Group, Host, Key, Value) ->
1941
    Opts =
×
1942
        case mod_shared_roster:get_group_opts(Host, Group) of
1943
            Os when is_list(Os) ->
1944
                Os;
×
1945
            error ->
1946
                []
×
1947
        end,
1948
    Opts2 = srg_set_info(Key, Value, Opts),
×
1949
    case mod_shared_roster:set_group_opts(Host, Group, Opts2) of
×
1950
        {atomic, ok} ->
1951
            ok;
×
1952
        Problem ->
1953
            ?INFO_MSG("Problem: ~n  ~p", [Problem]), %+++
×
1954
            error
×
1955
    end.
1956

1957
srg_set_info(<<"description">>, Value, Opts) ->
1958
    [{description, Value} | proplists:delete(description, Opts)];
×
1959
srg_set_info(<<"label">>, Value, Opts) ->
1960
    [{label, Value} | proplists:delete(label, Opts)];
×
1961
srg_set_info(<<"all_users">>, <<"true">>, Opts) ->
1962
    [{all_users, true} | proplists:delete(all_users, Opts)];
×
1963
srg_set_info(<<"online_users">>, <<"true">>, Opts) ->
1964
    [{online_users, true} | proplists:delete(online_users, Opts)];
×
1965
srg_set_info(<<"all_users">>, _, Opts) ->
1966
    proplists:delete(all_users, Opts);
×
1967
srg_set_info(<<"online_users">>, _, Opts) ->
1968
    proplists:delete(online_users, Opts);
×
1969
srg_set_info(Key, _Value, Opts) ->
1970
    ?ERROR_MSG("Unknown Key in srg_set_info: ~p", [Key]),
×
1971
    Opts.
×
1972

1973
srg_get_displayed(Group, Host) ->
1974
    Opts =
×
1975
        case mod_shared_roster:get_group_opts(Host, Group) of
1976
            Os when is_list(Os) ->
1977
                Os;
×
1978
            error ->
1979
                []
×
1980
        end,
1981
    proplists:get_value(displayed_groups, Opts, []).
×
1982

1983
srg_add_displayed(Group, Host, NewGroup) ->
1984
    Opts =
×
1985
        case mod_shared_roster:get_group_opts(Host, Group) of
1986
            Os when is_list(Os) ->
1987
                Os;
×
1988
            error ->
1989
                []
×
1990
        end,
1991
    {DispGroups, WrongDispGroups} = filter_groups_existence(Host, [NewGroup]),
×
1992
    case WrongDispGroups /= [] of
×
1993
        true ->
1994
            {wrong_displayed_groups, WrongDispGroups};
×
1995
        false ->
1996
            DisplayedOld = proplists:get_value(displayed_groups, Opts, []),
×
1997
            Opts2 =
×
1998
                [{displayed_groups, lists:flatten(DisplayedOld, DispGroups)}
1999
                 | proplists:delete(displayed_groups, Opts)],
2000
            case mod_shared_roster:set_group_opts(Host, Group, Opts2) of
×
2001
                {atomic, ok} ->
2002
                    ok;
×
2003
                Problem ->
2004
                    ?INFO_MSG("Problem: ~n  ~p", [Problem]), %+++
×
2005
                    error
×
2006
            end
2007
    end.
2008

2009
srg_del_displayed(Group, Host, OldGroup) ->
2010
    Opts =
×
2011
        case mod_shared_roster:get_group_opts(Host, Group) of
2012
            Os when is_list(Os) ->
2013
                Os;
×
2014
            error ->
2015
                []
×
2016
        end,
2017
    DisplayedOld = proplists:get_value(displayed_groups, Opts, []),
×
2018
    {DispGroups, OldDispGroups} = lists:partition(fun(G) -> G /= OldGroup end, DisplayedOld),
×
2019
    case OldDispGroups == [] of
×
2020
        true ->
2021
            {inexistent_displayed_groups, OldGroup};
×
2022
        false ->
2023
            Opts2 = [{displayed_groups, DispGroups} | proplists:delete(displayed_groups, Opts)],
×
2024
            case mod_shared_roster:set_group_opts(Host, Group, Opts2) of
×
2025
                {atomic, ok} ->
2026
                    ok;
×
2027
                Problem ->
2028
                    ?INFO_MSG("Problem: ~n  ~p", [Problem]), %+++
×
2029
                    error
×
2030
            end
2031
    end.
2032

2033
filter_groups_existence(Host, Groups) ->
2034
    lists:partition(fun(Group) -> error /= mod_shared_roster:get_group_opts(Host, Group) end,
×
2035
                    Groups).
2036
%% @format-end
2037

2038
srg_get_members(Group, Host) ->
2039
    Members = mod_shared_roster:get_group_explicit_users(Host,Group),
×
2040
    [jid:encode(jid:make(MUser, MServer))
×
2041
     || {MUser, MServer} <- Members].
×
2042

2043
srg_user_add(User, Host, Group, GroupHost) ->
2044
    mod_shared_roster:add_user_to_group(GroupHost, {User, Host}, Group),
×
2045
    ok.
×
2046

2047
srg_user_del(User, Host, Group, GroupHost) ->
2048
    mod_shared_roster:remove_user_from_group(GroupHost, {User, Host}, Group),
×
2049
    ok.
×
2050

2051

2052
%%%
2053
%%% Stanza
2054
%%%
2055

2056
%% @doc Send a message to an XMPP account.
2057
-spec send_message(Type::binary(), From::binary(), To::binary(),
2058
                   Subject::binary(), Body::binary()) -> ok.
2059
send_message(Type, From, To, Subject, Body) ->
2060
    CodecOpts = ejabberd_config:codec_options(),
×
2061
    try xmpp:decode(
×
2062
          #xmlel{name = <<"message">>,
2063
                 attrs = [{<<"to">>, To},
2064
                          {<<"from">>, From},
2065
                          {<<"type">>, Type},
2066
                          {<<"id">>, p1_rand:get_string()}],
2067
                 children =
2068
                     [#xmlel{name = <<"subject">>,
2069
                             children = [{xmlcdata, Subject}]},
2070
                      #xmlel{name = <<"body">>,
2071
                             children = [{xmlcdata, Body}]}]},
2072
          ?NS_CLIENT, CodecOpts) of
2073
        #message{from = JID, subject = SubjectEl, body = BodyEl} = Msg ->
2074
            Msg2 = case {xmpp:get_text(SubjectEl), xmpp:get_text(BodyEl)} of
×
2075
                       {Subject, <<>>} -> Msg;
×
2076
                       {<<>>, Body} -> Msg#message{subject = []};
×
2077
                       _ -> Msg
×
2078
                   end,
2079
            State = #{jid => JID},
×
2080
            ejabberd_hooks:run_fold(user_send_packet, JID#jid.lserver, {Msg2, State}, []),
×
2081
            ejabberd_router:route(Msg2)
×
2082
    catch _:{xmpp_codec, Why} ->
2083
            {error, xmpp:format_error(Why)}
×
2084
    end.
2085

2086
send_stanza(FromString, ToString, Stanza) ->
2087
    try
×
2088
        #xmlel{} = El = fxml_stream:parse_element(Stanza),
×
2089
        From = jid:decode(FromString),
×
2090
        To = jid:decode(ToString),
×
2091
        CodecOpts = ejabberd_config:codec_options(),
×
2092
        Pkt = xmpp:decode(El, ?NS_CLIENT, CodecOpts),
×
2093
        Pkt2 = xmpp:set_from_to(Pkt, From, To),
×
2094
        State = #{jid => From},
×
2095
        ejabberd_hooks:run_fold(user_send_packet, From#jid.lserver,
×
2096
                                {Pkt2, State}, []),
2097
        ejabberd_router:route(Pkt2)
×
2098
    catch _:{xmpp_codec, Why} ->
2099
            io:format("incorrect stanza: ~ts~n", [xmpp:format_error(Why)]),
×
2100
            {error, Why};
×
2101
          _:{badmatch, {error, {Code, Why}}} when is_integer(Code) ->
2102
            io:format("invalid xml: ~p~n", [Why]),
×
2103
            {error, Why};
×
2104
          _:{badmatch, {error, Why}} ->
2105
            io:format("invalid xml: ~p~n", [Why]),
×
2106
            {error, Why};
×
2107
          _:{bad_jid, S} ->
2108
            io:format("malformed JID: ~ts~n", [S]),
×
2109
            {error, "JID malformed"}
×
2110
    end.
2111

2112
-spec send_stanza_c2s(binary(), binary(), binary(), binary()) -> ok | {error, any()}.
2113
send_stanza_c2s(Username, Host, Resource, Stanza) ->
2114
    try
×
2115
        #xmlel{} = El = fxml_stream:parse_element(Stanza),
×
2116
        CodecOpts = ejabberd_config:codec_options(),
×
2117
        Pkt = xmpp:decode(El, ?NS_CLIENT, CodecOpts),
×
2118
        case ejabberd_sm:get_session_pid(Username, Host, Resource) of
×
2119
            Pid when is_pid(Pid) ->
2120
                ejabberd_c2s:send(Pid, Pkt);
×
2121
            _ ->
2122
                {error, no_session}
×
2123
        end
2124
    catch _:{badmatch, {error, Why} = Err} ->
2125
            io:format("invalid xml: ~p~n", [Why]),
×
2126
            Err;
×
2127
          _:{xmpp_codec, Why} ->
2128
            io:format("incorrect stanza: ~ts~n", [xmpp:format_error(Why)]),
×
2129
            {error, Why}
×
2130
    end.
2131

2132
privacy_set(Username, Host, QueryS) ->
2133
    Jid = jid:make(Username, Host),
×
2134
    QueryEl = fxml_stream:parse_element(QueryS),
×
2135
    SubEl = xmpp:decode(QueryEl),
×
2136
    IQ = #iq{type = set, id = <<"push">>, sub_els = [SubEl],
×
2137
             from = Jid, to = Jid},
2138
    Result = mod_privacy:process_iq(IQ),
×
2139
    Result#iq.type == result.
×
2140

2141
%%%
2142
%%% Stats
2143
%%%
2144

2145
stats(Name) ->
2146
    case Name of
×
2147
        <<"uptimeseconds">> -> trunc(element(1, erlang:statistics(wall_clock))/1000);
×
2148
        <<"processes">> -> length(erlang:processes());
×
2149
        <<"registeredusers">> -> lists:foldl(fun(Host, Sum) -> ejabberd_auth:count_users(Host) + Sum end, 0, ejabberd_option:hosts());
×
2150
        <<"onlineusersnode">> -> length(ejabberd_sm:dirty_get_my_sessions_list());
×
2151
        <<"onlineusers">> -> length(ejabberd_sm:dirty_get_sessions_list())
×
2152
    end.
2153

2154
stats(Name, Host) ->
2155
    case Name of
×
2156
        <<"registeredusers">> -> ejabberd_auth:count_users(Host);
×
2157
        <<"onlineusers">> -> length(ejabberd_sm:get_vh_session_list(Host))
×
2158
    end.
2159

2160

2161
user_action(User, Server, Fun, OK) ->
2162
    case ejabberd_auth:user_exists(User, Server) of
8✔
2163
        true ->
2164
            case catch Fun() of
8✔
2165
                OK -> ok;
8✔
2166
                {error, Error} -> throw(Error);
×
2167
                Error ->
2168
                    ?ERROR_MSG("Command returned: ~p", [Error]),
×
2169
                    1
×
2170
            end;
2171
        false ->
2172
            throw({not_found, "unknown_user"})
×
2173
    end.
2174

2175
num_prio(Priority) when is_integer(Priority) ->
2176
    Priority;
×
2177
num_prio(_) ->
2178
    -1.
×
2179

2180
%%%
2181
%%% Web Admin
2182
%%%
2183

2184
%% @format-begin
2185

2186
%%% Main
2187

2188
web_menu_main(Acc, _Lang) ->
2189
    Acc ++ [{<<"stats">>, <<"Statistics">>}].
48✔
2190

2191
web_page_main(_, #request{path = [<<"stats">>]} = R) ->
2192
    Res = ?H1GL(<<"Statistics">>, <<"modules/#mod_stats">>, <<"mod_stats">>)
×
2193
          ++ [make_command(stats_host, R, [], [{only, presentation}]),
2194
              make_command(incoming_s2s_number, R, [], [{only, presentation}]),
2195
              make_command(outgoing_s2s_number, R, [], [{only, presentation}]),
2196
              make_table([<<"stat name">>, {<<"stat value">>, right}],
2197
                         [{?C(<<"Registered Users:">>),
2198
                           make_command(stats,
2199
                                        R,
2200
                                        [{<<"name">>, <<"registeredusers">>}],
2201
                                        [{only, value}])},
2202
                          {?C(<<"Online Users:">>),
2203
                           make_command(stats,
2204
                                        R,
2205
                                        [{<<"name">>, <<"onlineusers">>}],
2206
                                        [{only, value}])},
2207
                          {?C(<<"S2S Connections Incoming:">>),
2208
                           make_command(incoming_s2s_number, R, [], [{only, value}])},
2209
                          {?C(<<"S2S Connections Outgoing:">>),
2210
                           make_command(outgoing_s2s_number, R, [], [{only, value}])}])],
2211
    {stop, Res};
×
2212
web_page_main(Acc, _) ->
2213
    Acc.
×
2214

2215
%%% Host
2216

2217
web_menu_host(Acc, _Host, _Lang) ->
2218
    Acc ++ [{<<"purge">>, <<"Purge">>}, {<<"stats">>, <<"Statistics">>}].
×
2219

2220
web_page_host(_, Host, #request{path = [<<"purge">>]} = R) ->
2221
    Head = [?XC(<<"h1">>, <<"Purge">>)],
×
2222
    Set = [ejabberd_web_admin:make_command(delete_old_users_vhost,
×
2223
                                           R,
2224
                                           [{<<"host">>, Host}],
2225
                                           [])],
2226
    {stop, Head ++ Set};
×
2227
web_page_host(_, Host, #request{path = [<<"stats">>]} = R) ->
2228
    Res = ?H1GL(<<"Statistics">>, <<"modules/#mod_stats">>, <<"mod_stats">>)
×
2229
          ++ [make_command(stats_host, R, [], [{only, presentation}]),
2230
              make_table([<<"stat name">>, {<<"stat value">>, right}],
2231
                         [{?C(<<"Registered Users:">>),
2232
                           make_command(stats_host,
2233
                                        R,
2234
                                        [{<<"host">>, Host}, {<<"name">>, <<"registeredusers">>}],
2235
                                        [{only, value},
2236
                                         {result_links, [{stat, arg_host, 3, <<"users">>}]}])},
2237
                          {?C(<<"Online Users:">>),
2238
                           make_command(stats_host,
2239
                                        R,
2240
                                        [{<<"host">>, Host}, {<<"name">>, <<"onlineusers">>}],
2241
                                        [{only, value},
2242
                                         {result_links,
2243
                                          [{stat, arg_host, 3, <<"online-users">>}]}])}])],
2244
    {stop, Res};
×
2245
web_page_host(Acc, _, _) ->
2246
    Acc.
×
2247

2248
%%% HostUser
2249

2250
web_menu_hostuser(Acc, _Host, _Username, _Lang) ->
2251
    Acc ++ [{<<"auth">>, <<"Authentication">>}, {<<"session">>, <<"Sessions">>}].
×
2252

2253
web_page_hostuser(_, Host, User, #request{path = [<<"auth">>]} = R) ->
2254
    Ban = make_command(ban_account,
×
2255
                       R,
2256
                       [{<<"user">>, User}, {<<"host">>, Host}],
2257
                       [{style, danger}]),
2258
    Unban = make_command(unban_account, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
×
2259
    Res = ?H1GLraw(<<"Authentication">>,
×
2260
                   <<"admin/configuration/authentication/">>,
2261
                   <<"Authentication">>)
2262
          ++ [make_command(register, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
2263
              make_command(check_account, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
2264
              ?X(<<"hr">>),
2265
              make_command(check_password, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
2266
              make_command(check_password_hash, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
2267
              make_command(change_password,
2268
                           R,
2269
                           [{<<"user">>, User}, {<<"host">>, Host}],
2270
                           [{style, danger}]),
2271
              ?X(<<"hr">>),
2272
              make_command(get_ban_details, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
2273
              Ban,
2274
              Unban,
2275
              ?X(<<"hr">>),
2276
              make_command(unregister,
2277
                           R,
2278
                           [{<<"user">>, User}, {<<"host">>, Host}],
2279
                           [{style, danger}])],
2280
    {stop, Res};
×
2281
web_page_hostuser(_, Host, User, #request{path = [<<"session">>]} = R) ->
2282
    Head = [?XC(<<"h1">>, <<"Sessions">>), ?BR],
×
2283
    Set = [make_command(resource_num, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
×
2284
           make_command(set_presence, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
2285
           make_command(kick_user, R, [{<<"user">>, User}, {<<"host">>, Host}], [{style, danger}]),
2286
           make_command(kick_session,
2287
                        R,
2288
                        [{<<"user">>, User}, {<<"host">>, Host}],
2289
                        [{style, danger}])],
2290
    timer:sleep(100), % kicking sessions takes a while, let's delay the get commands
×
2291
    Get = [make_command(user_sessions_info,
×
2292
                        R,
2293
                        [{<<"user">>, User}, {<<"host">>, Host}],
2294
                        [{result_links, [{node, node, 5, <<>>}]}]),
2295
           make_command(user_resources, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
2296
           make_command(get_presence, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
2297
           make_command(num_resources, R, [{<<"user">>, User}, {<<"host">>, Host}], [])],
2298
    {stop, Head ++ Get ++ Set};
×
2299
web_page_hostuser(Acc, _, _, _) ->
2300
    Acc.
×
2301

2302
%%% HostNode
2303

2304
web_menu_hostnode(Acc, _Host, _Username, _Lang) ->
2305
    Acc ++ [{<<"modules">>, <<"Modules">>}].
×
2306

2307
web_page_hostnode(_, Host, Node, #request{path = [<<"modules">>]} = R) ->
2308
    Res = ?H1GLraw(<<"Modules">>, <<"admin/configuration/modules/">>, <<"Modules Options">>)
×
2309
          ++ [ejabberd_cluster:call(Node,
2310
                                    ejabberd_web_admin,
2311
                                    make_command,
2312
                                    [restart_module, R, [{<<"host">>, Host}], []])],
2313
    {stop, Res};
×
2314
web_page_hostnode(Acc, _Host, _Node, _Request) ->
2315
    Acc.
×
2316

2317
%%% Node
2318

2319
web_menu_node(Acc, _Node, _Lang) ->
2320
    Acc ++ [{<<"stats">>, <<"Statistics">>}].
×
2321

2322
web_page_node(_, Node, #request{path = [<<"stats">>]} = R) ->
2323
    UpSecs =
×
2324
        ejabberd_cluster:call(Node,
2325
                              ejabberd_web_admin,
2326
                              make_command,
2327
                              [stats, R, [{<<"name">>, <<"uptimeseconds">>}], [{only, value}]]),
2328
    UpDaysBin =
×
2329
        integer_to_binary(binary_to_integer(fxml:get_tag_cdata(UpSecs))
2330
                          div 86400), % 24*60*60
2331
    UpDays =
×
2332
        #xmlel{name = <<"code">>,
2333
               attrs = [],
2334
               children = [{xmlcdata, UpDaysBin}]},
2335
    Res = ?H1GL(<<"Statistics">>, <<"modules/#mod_stats">>, <<"mod_stats">>)
×
2336
          ++ [make_command(stats, R, [], [{only, presentation}]),
2337
              make_table([<<"stat name">>, {<<"stat value">>, right}],
2338
                         [{?C(<<"Online Users in this node:">>),
2339
                           ejabberd_cluster:call(Node,
2340
                                                 ejabberd_web_admin,
2341
                                                 make_command,
2342
                                                 [stats,
2343
                                                  R,
2344
                                                  [{<<"name">>, <<"onlineusersnode">>}],
2345
                                                  [{only, value}]])},
2346
                          {?C(<<"Uptime Seconds:">>), UpSecs},
2347
                          {?C(<<"Uptime Seconds (rounded to days):">>), UpDays},
2348
                          {?C(<<"Processes:">>),
2349
                           ejabberd_cluster:call(Node,
2350
                                                 ejabberd_web_admin,
2351
                                                 make_command,
2352
                                                 [stats,
2353
                                                  R,
2354
                                                  [{<<"name">>, <<"processes">>}],
2355
                                                  [{only, value}]])}])],
2356
    {stop, Res};
×
2357
web_page_node(Acc, _, _) ->
2358
    Acc.
×
2359
%% @format-end
2360

2361
%%%
2362
%%% Document
2363
%%%
2364

2365
mod_options(_) -> [].
108✔
2366

2367
mod_doc() ->
2368
    #{desc =>
×
2369
          [?T("This module provides additional administrative commands."), "",
2370
           ?T("Details for some commands:"), "",
2371
           ?T("_`ban_account`_ API:"),
2372
           ?T("This command kicks all the connected sessions of the account "
2373
              "from the server. It also changes their password to a randomly "
2374
              "generated one, so they can't login anymore unless a server "
2375
              "administrator changes their password again. It is possible to "
2376
              "define the reason of the ban. The new password also includes "
2377
              "the reason and the date and time of the ban. See an example below."), "",
2378
           ?T("_`push_roster`_ API (and _`push_roster_all`_ API):"),
2379
           ?T("The roster file must be placed, if using Windows, on the "
2380
              "directory where you installed ejabberd: "
2381
              "`C:/Program Files/ejabberd` or similar. If you use other "
2382
              "Operating System, place the file on the same directory where "
2383
              "the .beam files are installed. See below an example roster file."), "",
2384
           ?T("_`srg_create`_ API:"),
2385
           ?T("If you want to put a group Name with blank spaces, use the "
2386
              "characters '\"\'' and '\'\"' to define when the Name starts and "
2387
              "ends. See an example below.")],
2388
      example =>
2389
          [{?T("With this configuration, vCards can only be modified with "
2390
               "mod_admin_extra commands:"),
2391
            ["acl:",
2392
             "  adminextraresource:",
2393
             "    - resource: \"modadminextraf8x,31ad\"",
2394
             "access_rules:",
2395
             "  vcard_set:",
2396
             "    - allow: adminextraresource",
2397
             "modules:",
2398
             "  mod_admin_extra: {}",
2399
             "  mod_vcard:",
2400
             "    access_set: vcard_set"]},
2401
           {?T("Content of roster file for _`push_roster`_ API:"),
2402
            ["[{<<\"bob\">>, <<\"example.org\">>, <<\"workers\">>, <<\"Bob\">>},",
2403
             "{<<\"mart\">>, <<\"example.org\">>, <<\"workers\">>, <<\"Mart\">>},",
2404
             "{<<\"Rich\">>, <<\"example.org\">>, <<\"bosses\">>, <<\"Rich\">>}]."]},
2405
           {?T("With this call, the sessions of the local account which JID is "
2406
              "'boby@example.org' will be kicked, and its password will be set "
2407
              "to something like "
2408
              "'BANNED_ACCOUNT--20080425T21:45:07--2176635--Spammed_rooms'"),
2409
            ["ejabberdctl vhost example.org ban_account boby \"Spammed rooms\""]},
2410
           {?T("Call to _`srg_create`_ API using double-quotes and single-quotes:"),
2411
            ["ejabberdctl srg_create g1 example.org \"\'Group number 1\'\" this_is_g1 g1"]}]}.
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc