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

processone / ejabberd / 978

04 Apr 2025 09:07AM UTC coverage: 33.457% (-0.004%) from 33.461%
978

push

github

prefiks
Relax limits of shared groups names

We want to normalize it, but we don't need to limit it to what nodeprep
allows (like for example ':' that we see in use)

0 of 1 new or added line in 1 file covered. (0.0%)

101 existing lines in 2 files now uncovered.

15143 of 45261 relevant lines covered (33.46%)

628.62 hits per line

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

9.46
/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
         ban_account/3, ban_account_v2/3, get_ban_details/2, unban_account/2,
55

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

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

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

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

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

80
         % Privacy list
81
         privacy_set/3,
82

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

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

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

103
%%%
104
%%% gen_mod
105
%%%
106

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

120
stop(_Host) ->
121
    ok.
3✔
122

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

126
depends(_Host, _Opts) ->
127
    [].
9✔
128

129
%%%
130
%%% Register commands
131
%%%
132

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

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

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

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

258
     #ejabberd_commands{name = ban_account, tags = [accounts],
259
                        desc = "Ban an account: kick sessions and set random password",
260
                        longdesc = "This simply sets a random password.",
261
                        module = ?MODULE, function = ban_account,
262
                        args = [{user, binary}, {host, binary}, {reason, binary}],
263
                        args_example = [<<"attacker">>, <<"myserver.com">>, <<"Spaming other users">>],
264
                        args_desc = ["User name to ban", "Server name",
265
                                     "Reason for banning user"],
266
                        result = {res, rescode},
267
                        result_example = ok},
268
     #ejabberd_commands{name = ban_account, tags = [accounts],
269
                        desc = "Ban an account",
270
                        longdesc = "This command kicks the account sessions, "
271
                        "sets a random password, and stores ban details in the "
272
                        "account private storage. "
273
                        "This command requires _`mod_private`_ to be enabled. "
274
                        "Check also _`get_ban_details`_ API "
275
                        "and _`unban_account`_ API.",
276
                        module = ?MODULE, function = ban_account_v2,
277
                        version = 2,
278
                        note = "improved in 24.06",
279
                        args = [{user, binary}, {host, binary}, {reason, binary}],
280
                        args_example = [<<"attacker">>, <<"myserver.com">>, <<"Spaming other users">>],
281
                        args_desc = ["User name to ban", "Server name",
282
                                     "Reason for banning user"],
283
                        result = {res, rescode},
284
                        result_example = ok},
285
     #ejabberd_commands{name = get_ban_details, tags = [accounts],
286
                        desc = "Get ban details about an account",
287
                        longdesc = "Check _`ban_account`_ API.",
288
                        module = ?MODULE, function = get_ban_details,
289
                        version = 2,
290
                        note = "added in 24.06",
291
                        args = [{user, binary}, {host, binary}],
292
                        args_example = [<<"attacker">>, <<"myserver.com">>],
293
                        args_desc = ["User name to unban", "Server name"],
294
                        result = {ban_details, {list,
295
                                          {detail, {tuple, [{name, string},
296
                                                            {value, string}
297
                                                           ]}}
298
                                         }},
299
                        result_example = [{"reason", "Spamming other users"},
300
                                          {"bandate", "2024-04-22T09:16:47.975312Z"},
301
                                          {"lastdate", "2024-04-22T08:39:12Z"},
302
                                          {"lastreason", "Connection reset by peer"}]},
303
     #ejabberd_commands{name = unban_account, tags = [accounts],
304
                        desc = "Revert the ban from an account: set back the old password",
305
                        longdesc = "Check _`ban_account`_ API.",
306
                        module = ?MODULE, function = unban_account,
307
                        version = 2,
308
                        note = "added in 24.06",
309
                        args = [{user, binary}, {host, binary}],
310
                        args_example = [<<"gooduser">>, <<"myserver.com">>],
311
                        args_desc = ["User name to unban", "Server name"],
312
                        result = {res, rescode},
313
                        result_example = ok},
314

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

449
     #ejabberd_commands{name = connected_users_vhost,
450
                        tags = [session],
451
                        desc = "Get the list of established sessions in a vhost",
452
                        module = ?MODULE, function = connected_users_vhost,
453
                        args_example = [<<"myexample.com">>],
454
                        args_desc = ["Server name"],
455
                        args = [{host, binary}],
456
                        result_example = [<<"user1@myserver.com/tka">>, <<"user2@localhost/tka">>],
457
                        result_desc = "List of sessions full JIDs",
458
                        result = {connected_users_vhost, {list, {sessions, string}}}},
459
     #ejabberd_commands{name = user_sessions_info,
460
                        tags = [session],
461
                        desc = "Get information about all sessions of a user",
462
                        module = ?MODULE, function = user_sessions_info,
463
                        args = [{user, binary}, {host, binary}],
464
                        args_example = [<<"peter">>, <<"myserver.com">>],
465
                        args_desc = ["User name", "Server name"],
466
                        result_example = [{"c2s", "127.0.0.1", 42656,8, "ejabberd@localhost",
467
                                           231, <<"dnd">>, <<"tka">>, <<>>}],
468
                        result = {sessions_info,
469
                                  {list,
470
                                   {session, {tuple,
471
                                              [{connection, string},
472
                                               {ip, string},
473
                                               {port, integer},
474
                                               {priority, integer},
475
                                               {node, string},
476
                                               {uptime, integer},
477
                                               {status, string},
478
                                               {resource, string},
479
                                               {statustext, string}
480
                                              ]}}
481
                                  }}},
482

483
     #ejabberd_commands{name = get_presence, tags = [session],
484
                        desc =
485
                            "Retrieve the resource with highest priority, "
486
                            "and its presence (show and status message) "
487
                            "for a given user.",
488
                        longdesc =
489
                            "The `jid` value contains the user JID "
490
                            "with resource.\n\nThe `show` value contains "
491
                            "the user presence flag. It can take "
492
                            "limited values:\n\n - `available`\n - `chat` "
493
                            "(Free for chat)\n - `away`\n - `dnd` (Do "
494
                            "not disturb)\n - `xa` (Not available, "
495
                            "extended away)\n - `unavailable` (Not "
496
                            "connected)\n\n`status` is a free text "
497
                            "defined by the user client.",
498
                        module = ?MODULE, function = get_presence,
499
                        args = [{user, binary}, {host, binary}],
500
                        args_rename = [{server, host}],
501
                        args_example = [<<"peter">>, <<"myexample.com">>],
502
                        args_desc = ["User name", "Server name"],
503
                        result_example = {<<"user1@myserver.com/tka">>, <<"dnd">>, <<"Busy">>},
504
                        result =
505
                            {presence,
506
                             {tuple,
507
                              [{jid, string}, {show, string},
508
                               {status, string}]}}},
509
     #ejabberd_commands{name = set_presence,
510
                        tags = [session],
511
                        desc = "Set presence of a session",
512
                        module = ?MODULE, function = set_presence,
513
                        args = [{user, binary}, {host, binary},
514
                                {resource, binary}, {type, binary},
515
                                {show, binary}, {status, binary},
516
                                {priority, binary}],
517
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"tka1">>,
518
                                        <<"available">>,<<"away">>,<<"BB">>, <<"7">>],
519
                        args_desc = ["User name", "Server name", "Resource",
520
                                        "Type: `available`, `error`, `probe`...",
521
                                        "Show: `away`, `chat`, `dnd`, `xa`.", "Status text",
522
                                        "Priority, provide this value as an integer"],
523
                        result = {res, rescode}},
524
     #ejabberd_commands{name = set_presence,
525
                        tags = [session],
526
                        desc = "Set presence of a session",
527
                        module = ?MODULE, function = set_presence,
528
                        version = 1,
529
                        note = "updated in 24.02",
530
                        args = [{user, binary}, {host, binary},
531
                                {resource, binary}, {type, binary},
532
                                {show, binary}, {status, binary},
533
                                {priority, integer}],
534
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"tka1">>,
535
                                        <<"available">>,<<"away">>,<<"BB">>, 7],
536
                        args_desc = ["User name", "Server name", "Resource",
537
                                        "Type: `available`, `error`, `probe`...",
538
                                        "Show: `away`, `chat`, `dnd`, `xa`.", "Status text",
539
                                        "Priority, provide this value as an integer"],
540
                        result = {res, rescode}},
541

542
     #ejabberd_commands{name = set_nickname, tags = [vcard],
543
                        desc = "Set nickname in a user's vCard",
544
                        module = ?MODULE, function = set_nickname,
545
                        args = [{user, binary}, {host, binary}, {nickname, binary}],
546
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"User 1">>],
547
                        args_desc = ["User name", "Server name", "Nickname"],
548
                        result = {res, rescode}},
549
     #ejabberd_commands{name = get_vcard, tags = [vcard],
550
                        desc = "Get content from a vCard field",
551
                        longdesc = Vcard1FieldsString ++ "\n" ++ VcardXEP,
552
                        module = ?MODULE, function = get_vcard,
553
                        args = [{user, binary}, {host, binary}, {name, binary}],
554
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"NICKNAME">>],
555
                        args_desc = ["User name", "Server name", "Field name"],
556
                        result_example = "User 1",
557
                        result_desc = "Field content",
558
                        result = {content, string}},
559
     #ejabberd_commands{name = get_vcard2, tags = [vcard],
560
                        desc = "Get content from a vCard subfield",
561
                        longdesc = Vcard2FieldsString ++ "\n" ++ VcardXEP,
562
                        module = ?MODULE, function = get_vcard,
563
                        args = [{user, binary}, {host, binary}, {name, binary}, {subname, binary}],
564
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"N">>, <<"FAMILY">>],
565
                        args_desc = ["User name", "Server name", "Field name", "Subfield name"],
566
                        result_example = "Schubert",
567
                        result_desc = "Field content",
568
                        result = {content, string}},
569
     #ejabberd_commands{name = get_vcard2_multi, tags = [vcard],
570
                        desc = "Get multiple contents from a vCard field",
571
                        longdesc = Vcard2FieldsString ++ "\n" ++ VcardXEP,
572
                        module = ?MODULE, function = get_vcard_multi,
573
                        args = [{user, binary}, {host, binary}, {name, binary}, {subname, binary}],
574
                        result = {contents, {list, {value, string}}}},
575

576
     #ejabberd_commands{name = set_vcard, tags = [vcard],
577
                        desc = "Set content in a vCard field",
578
                        longdesc = Vcard1FieldsString ++ "\n" ++ VcardXEP,
579
                        module = ?MODULE, function = set_vcard,
580
                        args = [{user, binary}, {host, binary}, {name, binary}, {content, binary}],
581
                        args_example = [<<"user1">>,<<"myserver.com">>, <<"URL">>, <<"www.example.com">>],
582
                        args_desc = ["User name", "Server name", "Field name", "Value"],
583
                        result = {res, rescode}},
584
     #ejabberd_commands{name = set_vcard2, tags = [vcard],
585
                        desc = "Set content in a vCard subfield",
586
                        longdesc = Vcard2FieldsString ++ "\n" ++ VcardXEP,
587
                        module = ?MODULE, function = set_vcard,
588
                        args = [{user, binary}, {host, binary}, {name, binary}, {subname, binary}, {content, binary}],
589
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"TEL">>, <<"NUMBER">>, <<"123456">>],
590
                        args_desc = ["User name", "Server name", "Field name", "Subfield name", "Value"],
591
                        result = {res, rescode}},
592
     #ejabberd_commands{name = set_vcard2_multi, tags = [vcard],
593
                        desc = "Set multiple contents in a vCard subfield",
594
                        longdesc = Vcard2FieldsString ++ "\n" ++ VcardXEP,
595
                        module = ?MODULE, function = set_vcard,
596
                        args = [{user, binary}, {host, binary}, {name, binary}, {subname, binary}, {contents, {list, {value, binary}}}],
597
                        result = {res, rescode}},
598

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

764
     #ejabberd_commands{name = get_last, tags = [last],
765
                        desc = "Get last activity information",
766
                        longdesc = "Timestamp is UTC and "
767
                            "[XEP-0082](https://xmpp.org/extensions/xep-0082.html)"
768
                            " format, for example: "
769
                            "`2017-02-23T22:25:28.063062Z     ONLINE`",
770
                        module = ?MODULE, function = get_last,
771
                        args = [{user, binary}, {host, binary}],
772
                        args_example = [<<"user1">>,<<"myserver.com">>],
773
                        args_desc = ["User name", "Server name"],
774
                        result_example = {<<"2017-06-30T14:32:16.060684Z">>, "ONLINE"},
775
                        result_desc = "Last activity timestamp and status",
776
                        result = {last_activity,
777
                                  {tuple, [{timestamp, string},
778
                                           {status, string}
779
                                          ]}}},
780
     #ejabberd_commands{name = set_last, tags = [last],
781
                        desc = "Set last activity information",
782
                        longdesc = "Timestamp is the seconds since "
783
                        "`1970-01-01 00:00:00 UTC`. For example value see `date +%s`",
784
                        module = ?MODULE, function = set_last,
785
                        args = [{user, binary}, {host, binary}, {timestamp, integer}, {status, binary}],
786
                        args_example = [<<"user1">>,<<"myserver.com">>, 1500045311, <<"GoSleeping">>],
787
                        args_desc = ["User name", "Server name", "Number of seconds since epoch", "Status message"],
788
                        result = {res, rescode}},
789

790
     #ejabberd_commands{name = private_get, tags = [private],
791
                        desc = "Get some information from a user private storage",
792
                        module = ?MODULE, function = private_get,
793
                        args = [{user, binary}, {host, binary}, {element, binary}, {ns, binary}],
794
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"storage">>, <<"storage:rosternotes">>],
795
                        args_desc = ["User name", "Server name", "Element name", "Namespace"],
796
                        result = {res, string}},
797
     #ejabberd_commands{name = private_set, tags = [private],
798
                        desc = "Set to the user private storage",
799
                        module = ?MODULE, function = private_set,
800
                        args = [{user, binary}, {host, binary}, {element, binary}],
801
                        args_example = [<<"user1">>,<<"myserver.com">>,
802
                            <<"<storage xmlns='storage:rosternotes'/>">>],
803
                        args_desc = ["User name", "Server name", "XML storage element"],
804
                        result = {res, rescode}},
805

806
     #ejabberd_commands{name = srg_create, tags = [shared_roster_group],
807
                        desc = "Create a Shared Roster Group",
808
                        longdesc = "If you want to specify several group "
809
                        "identifiers in the Display argument,\n"
810
                        "put `\\ \"` around the argument and\nseparate the "
811
                        "identifiers with `\\ \\ n`\n"
812
                        "For example:\n"
813
                        "  `ejabberdctl srg_create group3 myserver.com "
814
                        "name desc \\\"group1\\\\ngroup2\\\"`",
815
                        note = "changed in 21.07",
816
                        module = ?MODULE, function = srg_create,
817
                        args = [{group, binary}, {host, binary},
818
                                {label, binary}, {description, binary}, {display, binary}],
819
                        args_rename = [{name, label}],
820
                        args_example = [<<"group3">>, <<"myserver.com">>, <<"Group3">>,
821
                                <<"Third group">>, <<"group1\\\\ngroup2">>],
822
                        args_desc = ["Group identifier", "Group server name", "Group name",
823
                                "Group description", "Groups to display"],
824
                        result = {res, rescode}},
825
     #ejabberd_commands{name = srg_create, tags = [shared_roster_group],
826
                        desc = "Create a Shared Roster Group",
827
                        module = ?MODULE, function = srg_create,
828
                        version = 1,
829
                        note = "updated in 24.02",
830
                        args = [{group, binary}, {host, binary},
831
                                {label, binary}, {description, binary}, {display, {list, {group, binary}}}],
832
                        args_rename = [{name, label}],
833
                        args_example = [<<"group3">>, <<"myserver.com">>, <<"Group3">>,
834
                                <<"Third group">>, [<<"group1">>, <<"group2">>]],
835
                        args_desc = ["Group identifier", "Group server name", "Group name",
836
                                "Group description", "List of groups to display"],
837
                        result = {res, rescode}},
838
     #ejabberd_commands{name = srg_add, tags = [shared_roster_group],
839
                        desc = "Add/Create a Shared Roster Group (without details)",
840
                        module = ?MODULE, function = srg_add,
841
                        note = "added in 24.06",
842
                        args = [{group, binary}, {host, binary}],
843
                        args_example = [<<"group3">>, <<"myserver.com">>],
844
                        args_desc = ["Group identifier", "Group server name"],
845
                        result = {res, rescode}},
846
     #ejabberd_commands{name = srg_delete, tags = [shared_roster_group],
847
                        desc = "Delete a Shared Roster Group",
848
                        module = ?MODULE, function = srg_delete,
849
                        args = [{group, binary}, {host, binary}],
850
                        args_example = [<<"group3">>, <<"myserver.com">>],
851
                        args_desc = ["Group identifier", "Group server name"],
852
                        result = {res, rescode}},
853
     #ejabberd_commands{name = srg_list, tags = [shared_roster_group],
854
                        desc = "List the Shared Roster Groups in Host",
855
                        module = ?MODULE, function = srg_list,
856
                        args = [{host, binary}],
857
                        args_example = [<<"myserver.com">>],
858
                        args_desc = ["Server name"],
859
                        result_example = [<<"group1">>, <<"group2">>],
860
                        result_desc = "List of group identifiers",
861
                        result = {groups, {list, {id, string}}}},
862
     #ejabberd_commands{name = srg_get_info, tags = [shared_roster_group],
863
                        desc = "Get info of a Shared Roster Group",
864
                        module = ?MODULE, function = srg_get_info,
865
                        args = [{group, binary}, {host, binary}],
866
                        args_example = [<<"group3">>, <<"myserver.com">>],
867
                        args_desc = ["Group identifier", "Group server name"],
868
                        result_example = [{<<"name">>, "Group 3"}, {<<"displayed_groups">>, "group1"}],
869
                        result_desc = "List of group information, as key and value",
870
                        result = {informations, {list, {information, {tuple, [{key, string}, {value, string}]}}}}},
871
     #ejabberd_commands{name = srg_set_info, tags = [shared_roster_group],
872
                        desc = "Set info of a Shared Roster Group",
873
                        module = ?MODULE, function = srg_set_info,
874
                        note = "added in 24.06",
875
                        args = [{group, binary}, {host, binary}, {key, binary}, {value, binary}],
876
                        args_example = [<<"group3">>, <<"myserver.com">>, <<"label">>, <<"Family">>],
877
                        args_desc = ["Group identifier", "Group server name",
878
                                     "Information key: label, description",
879
                                     "Information value"],
880
                        result = {res, rescode}},
881

882
     #ejabberd_commands{name = srg_get_displayed, tags = [shared_roster_group],
883
                        desc = "Get displayed groups of a Shared Roster Group",
884
                        module = ?MODULE, function = srg_get_displayed,
885
                        note = "added in 24.06",
886
                        args = [{group, binary}, {host, binary}],
887
                        args_example = [<<"group3">>, <<"myserver.com">>],
888
                        args_desc = ["Group identifier", "Group server name"],
889
                        result_example = [<<"group1">>, <<"group2">>],
890
                        result_desc = "List of groups to display",
891
                        result = {display, {list, {group, binary}}}},
892
     #ejabberd_commands{name = srg_add_displayed, tags = [shared_roster_group],
893
                        desc = "Add a group to displayed_groups of a Shared Roster Group",
894
                        module = ?MODULE, function = srg_add_displayed,
895
                        note = "added in 24.06",
896
                        args = [{group, binary}, {host, binary},
897
                                {add, binary}],
898
                        args_example = [<<"group3">>, <<"myserver.com">>, <<"group1">>],
899
                        args_desc = ["Group identifier", "Group server name",
900
                                "Group to add to displayed_groups"],
901
                        result = {res, rescode}},
902
     #ejabberd_commands{name = srg_del_displayed, tags = [shared_roster_group],
903
                        desc = "Delete a group from displayed_groups of a Shared Roster Group",
904
                        module = ?MODULE, function = srg_del_displayed,
905
                        note = "added in 24.06",
906
                        args = [{group, binary}, {host, binary},
907
                                {del, binary}],
908
                        args_example = [<<"group3">>, <<"myserver.com">>, <<"group1">>],
909
                        args_desc = ["Group identifier", "Group server name",
910
                                "Group to delete from displayed_groups"],
911
                        result = {res, rescode}},
912

913
     #ejabberd_commands{name = srg_get_members, tags = [shared_roster_group],
914
                        desc = "Get members of a Shared Roster Group",
915
                        module = ?MODULE, function = srg_get_members,
916
                        args = [{group, binary}, {host, binary}],
917
                        args_example = [<<"group3">>, <<"myserver.com">>],
918
                        args_desc = ["Group identifier", "Group server name"],
919
                        result_example = [<<"user1@localhost">>, <<"user2@localhost">>],
920
                        result_desc = "List of group identifiers",
921
                        result = {members, {list, {member, string}}}},
922
     #ejabberd_commands{name = srg_user_add, tags = [shared_roster_group],
923
                        desc = "Add the JID user@host to the Shared Roster Group",
924
                        module = ?MODULE, function = srg_user_add,
925
                        args = [{user, binary}, {host, binary}, {group, binary}, {grouphost, binary}],
926
                        args_example = [<<"user1">>, <<"myserver.com">>, <<"group3">>, <<"myserver.com">>],
927
                        args_desc = ["Username", "User server name", "Group identifier", "Group server name"],
928
                        result = {res, rescode}},
929
     #ejabberd_commands{name = srg_user_del, tags = [shared_roster_group],
930
                        desc = "Delete this JID user@host from the Shared Roster Group",
931
                        module = ?MODULE, function = srg_user_del,
932
                        args = [{user, binary}, {host, binary}, {group, binary}, {grouphost, binary}],
933
                        args_example = [<<"user1">>, <<"myserver.com">>, <<"group3">>, <<"myserver.com">>],
934
                        args_desc = ["Username", "User server name", "Group identifier", "Group server name"],
935
                        result = {res, rescode}},
936

937
     #ejabberd_commands{name = get_offline_count,
938
                        tags = [offline],
939
                        desc = "Get the number of unread offline messages",
940
                        policy = user,
941
                        module = mod_offline, function = count_offline_messages,
942
                        args = [],
943
                        args_rename = [{server, host}],
944
                        result_example = 5,
945
                        result_desc = "Number",
946
                        result = {value, integer}},
947
     #ejabberd_commands{name = get_offline_messages,
948
                        tags = [internal, offline],
949
                        desc = "Get the offline messages",
950
                        policy = user,
951
                        module = mod_offline, function = get_offline_messages,
952
                        args = [],
953
                        result = {queue, {list, {messages, {tuple, [{time, string},
954
                                                                    {from, string},
955
                                                                    {to, string},
956
                                                                    {packet, string}
957
                                                                   ]}}}}},
958

959
     #ejabberd_commands{name = send_message, tags = [stanza],
960
                        desc = "Send a message to a local or remote bare of full JID",
961
                        longdesc = "When sending a groupchat message to a MUC room, "
962
                        "`from` must be the full JID of a room occupant, "
963
                        "or the bare JID of a MUC service admin, "
964
                        "or the bare JID of a MUC/Sub subscribed user.",
965
                        module = ?MODULE, function = send_message,
966
                        args = [{type, binary}, {from, binary}, {to, binary},
967
                                {subject, binary}, {body, binary}],
968
                        args_example = [<<"headline">>, <<"admin@localhost">>, <<"user1@localhost">>,
969
                                <<"Restart">>, <<"In 5 minutes">>],
970
                        args_desc = ["Message type: `normal`, `chat`, `headline`, `groupchat`", "Sender JID",
971
                                "Receiver JID", "Subject, or empty string", "Body"],
972
                        result = {res, rescode}},
973
     #ejabberd_commands{name = send_stanza_c2s, tags = [stanza],
974
                        desc = "Send a stanza from an existing C2S session",
975
                        longdesc = "`user`@`host`/`resource` must be an existing C2S session."
976
                        " As an alternative, use _`send_stanza`_ API instead.",
977
                        module = ?MODULE, function = send_stanza_c2s,
978
                        args = [{user, binary}, {host, binary}, {resource, binary}, {stanza, binary}],
979
                        args_example = [<<"admin">>, <<"myserver.com">>, <<"bot">>,
980
                                <<"<message to='user1@localhost'><ext attr='value'/></message>">>],
981
                        args_desc = ["Username", "Server name", "Resource", "Stanza"],
982
                        result = {res, rescode}},
983
     #ejabberd_commands{name = send_stanza, tags = [stanza],
984
                        desc = "Send a stanza; provide From JID and valid To JID",
985
                        module = ?MODULE, function = send_stanza,
986
                        args = [{from, binary}, {to, binary}, {stanza, binary}],
987
                        args_example = [<<"admin@localhost">>, <<"user1@localhost">>,
988
                                <<"<message><ext attr='value'/></message>">>],
989
                        args_desc = ["Sender JID", "Destination JID", "Stanza"],
990
                        result = {res, rescode}},
991
     #ejabberd_commands{name = privacy_set, tags = [stanza],
992
                        desc = "Send a IQ set privacy stanza for a local account",
993
                        module = ?MODULE, function = privacy_set,
994
                        args = [{user, binary}, {host, binary}, {xmlquery, binary}],
995
                        args_example = [<<"user1">>, <<"myserver.com">>,
996
                                <<"<query xmlns='jabber:iq:privacy'>...">>],
997
                        args_desc = ["Username", "Server name", "Query XML element"],
998
                        result = {res, rescode}},
999

1000
     #ejabberd_commands{name = stats, tags = [statistics],
1001
                        desc = "Get some statistical value for the whole ejabberd server",
1002
                        longdesc = "Allowed statistics `name` are: `registeredusers`, "
1003
                            "`onlineusers`, `onlineusersnode`, `uptimeseconds`, `processes`.",
1004
                        policy = admin,
1005
                        module = ?MODULE, function = stats,
1006
                        args = [{name, binary}],
1007
                        args_example = [<<"registeredusers">>],
1008
                        args_desc = ["Statistic name"],
1009
                        result_example = 6,
1010
                        result_desc = "Integer statistic value",
1011
                        result = {stat, integer}},
1012
     #ejabberd_commands{name = stats_host, tags = [statistics],
1013
                        desc = "Get some statistical value for this host",
1014
                        longdesc = "Allowed statistics `name` are: `registeredusers`, `onlineusers`.",
1015
                        policy = admin,
1016
                        module = ?MODULE, function = stats,
1017
                        args = [{name, binary}, {host, binary}],
1018
                        args_example = [<<"registeredusers">>, <<"example.com">>],
1019
                        args_desc = ["Statistic name", "Server JID"],
1020
                        result_example = 6,
1021
                        result_desc = "Integer statistic value",
1022
                        result = {stat, integer}}
1023
    ].
1024

1025

1026
%%%
1027
%%% Adminsys
1028
%%%
1029

1030
compile(File) ->
1031
    Ebin = filename:join(code:lib_dir(ejabberd), "ebin"),
×
1032
    case ext_mod:compile_erlang_file(Ebin, File) of
×
1033
        {ok, Module} ->
1034
            code:purge(Module),
×
1035
            code:load_file(Module),
×
1036
            ok;
×
1037
        _ ->
1038
            error
×
1039
    end.
1040

1041
get_cookie() ->
1042
    atom_to_list(erlang:get_cookie()).
×
1043

1044
restart_module(Host, Module) when is_binary(Module) ->
1045
    restart_module(Host, misc:binary_to_atom(Module));
×
1046
restart_module(Host, Module) when is_atom(Module) ->
1047
    case gen_mod:is_loaded(Host, Module) of
×
1048
        false ->
1049
            % not a running module, force code reload anyway
1050
            code:purge(Module),
×
1051
            code:delete(Module),
×
1052
            code:load_file(Module),
×
1053
            1;
×
1054
        true ->
1055
            gen_mod:stop_module(Host, Module),
×
1056
            case code:soft_purge(Module) of
×
1057
                true ->
1058
                    code:delete(Module),
×
1059
                    code:load_file(Module),
×
1060
                    gen_mod:start_module(Host, Module),
×
1061
                    0;
×
1062
                false ->
1063
                    gen_mod:start_module(Host, Module),
×
1064
                    2
×
1065
            end
1066
    end.
1067

1068
%%%
1069
%%% Accounts
1070
%%%
1071

1072
set_password(User, Host, Password) ->
1073
    Fun = fun () -> ejabberd_auth:set_password(User, Host, Password) end,
5✔
1074
    user_action(User, Host, Fun, ok).
5✔
1075

1076
check_password(User, Host, Password) ->
1077
    ejabberd_auth:check_password(User, <<>>, Host, Password).
×
1078

1079
%% Copied some code from ejabberd_commands.erln
1080
check_password_hash(User, Host, PasswordHash, HashMethod) ->
1081
    AccountPass = ejabberd_auth:get_password_s(User, Host),
×
1082
    Methods = lists:map(fun(A) -> atom_to_binary(A, latin1) end,
×
1083
                   proplists:get_value(hashs, crypto:supports())),
1084
    MethodAllowed = lists:member(HashMethod, Methods),
×
1085
    AccountPassHash = case {AccountPass, MethodAllowed} of
×
1086
                          {A, _} when is_tuple(A) -> scrammed;
×
1087
                          {_, true} -> get_hash(AccountPass, HashMethod);
×
1088
                          {_, false} ->
1089
                              ?ERROR_MSG("Check_password_hash called "
×
1090
                                         "with hash method: ~p", [HashMethod]),
×
1091
                              undefined
×
1092
                      end,
1093
    case AccountPassHash of
×
1094
        scrammed ->
1095
            ?ERROR_MSG("Passwords are scrammed, and check_password_hash cannot work.", []),
×
1096
            throw(passwords_scrammed_command_cannot_work);
×
1097
        undefined -> throw(unkown_hash_method);
×
1098
        PasswordHash -> ok;
×
1099
        _ -> false
×
1100
    end.
1101

1102
get_hash(AccountPass, Method) ->
1103
    iolist_to_binary([io_lib:format("~2.16.0B", [X])
×
1104
          || X <- binary_to_list(
×
1105
              crypto:hash(binary_to_atom(Method, latin1), AccountPass))]).
1106

1107
delete_old_users(Days) ->
1108
    %% Get the list of registered users
1109
    Users = ejabberd_auth:get_users(),
1✔
1110

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

1114
delete_old_users_vhost(Host, Days) ->
1115
    %% Get the list of registered users
1116
    Users = ejabberd_auth:get_users(Host),
×
1117

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

1121
delete_old_users(Days, Users) ->
1122
    SecOlder = Days*24*60*60,
1✔
1123
    TimeStamp_now = erlang:system_time(second),
1✔
1124
    TimeStamp_oldest = TimeStamp_now - SecOlder,
1✔
1125
    F = fun({LUser, LServer}) ->
1✔
1126
            case catch delete_or_not(LUser, LServer, TimeStamp_oldest) of
6✔
1127
                true ->
1128
                    ejabberd_auth:remove_user(LUser, LServer),
×
1129
                    true;
×
1130
                _ ->
1131
                    false
6✔
1132
            end
1133
        end,
1134
    Users_removed = lists:filter(F, Users),
1✔
1135
    {removed, length(Users_removed), Users_removed}.
1✔
1136

1137
delete_or_not(LUser, LServer, TimeStamp_oldest) ->
1138
    deny = acl:match_rule(LServer, protect_old_users, jid:make(LUser, LServer)),
6✔
1139
    [] = ejabberd_sm:get_user_resources(LUser, LServer),
6✔
1140
    case mod_last:get_last_info(LUser, LServer) of
4✔
1141
        {ok, TimeStamp, _Status} ->
1142
            if TimeStamp_oldest < TimeStamp ->
×
1143
                    false;
×
1144
                true ->
1145
                    true
×
1146
            end;
1147
        not_found ->
1148
            true
×
1149
    end.
1150

1151
%%
1152
%% Ban account v0
1153

1154
ban_account(User, Host, ReasonText) ->
1155
    Reason = prepare_reason(ReasonText),
×
1156
    kick_sessions(User, Host, Reason),
×
1157
    set_random_password(User, Host, Reason),
×
1158
    ok.
×
1159

1160
kick_sessions(User, Server, Reason) ->
1161
    lists:map(
×
1162
      fun(Resource) ->
1163
              kick_this_session(User, Server, Resource, Reason)
×
1164
      end,
1165
      ejabberd_sm:get_user_resources(User, Server)).
1166

1167
set_random_password(User, Server, Reason) ->
1168
    NewPass = build_random_password(Reason),
×
1169
    set_password_auth(User, Server, NewPass).
×
1170

1171
build_random_password(Reason) ->
1172
    {{Year, Month, Day}, {Hour, Minute, Second}} = calendar:universal_time(),
×
1173
    Date = str:format("~4..0B~2..0B~2..0BT~2..0B:~2..0B:~2..0B",
×
1174
                      [Year, Month, Day, Hour, Minute, Second]),
1175
    RandomString = p1_rand:get_string(),
×
1176
    <<"BANNED_ACCOUNT--", Date/binary, "--", RandomString/binary, "--", Reason/binary>>.
×
1177

1178
set_password_auth(User, Server, Password) ->
1179
    ok = ejabberd_auth:set_password(User, Server, Password).
×
1180

1181
prepare_reason([]) ->
1182
    <<"Kicked by administrator">>;
×
1183
prepare_reason([Reason]) ->
1184
    Reason;
×
1185
prepare_reason(Reason) when is_binary(Reason) ->
1186
    Reason.
×
1187

1188
%%
1189
%% Ban account v2
1190

1191
ban_account_v2(User, Host, ReasonText) ->
1192
    case gen_mod:is_loaded(Host, mod_private) of
×
1193
        false ->
1194
            mod_private_is_required_but_disabled;
×
1195
        true ->
1196
            case is_banned(User, Host) of
×
1197
                true ->
1198
                    account_was_already_banned;
×
1199
                false ->
1200
                    ban_account_v2_b(User, Host, ReasonText)
×
1201
            end
1202
    end.
1203

1204
ban_account_v2_b(User, Host, ReasonText) ->
1205
    Reason = prepare_reason(ReasonText),
×
1206
    Pass = ejabberd_auth:get_password_s(User, Host),
×
1207
    Last = get_last(User, Host),
×
1208
    BanDate = xmpp_util:encode_timestamp(erlang:timestamp()),
×
1209
    Hash = get_hash_value(User, Host),
×
1210
    BanPrivateXml = build_ban_xmlel(Reason, Pass, Last, BanDate, Hash),
×
1211
    ok = private_set2(User, Host, BanPrivateXml),
×
1212
    ok = set_random_password_v2(User, Host),
×
1213
    kick_sessions(User, Host, Reason),
×
1214
    ok.
×
1215

1216
get_hash_value(User, Host) ->
1217
    Cookie = misc:atom_to_binary(erlang:get_cookie()),
1,186✔
1218
    misc:term_to_base64(crypto:hash(sha256, <<User/binary, Host/binary, Cookie/binary>>)).
1,186✔
1219

1220
set_random_password_v2(User, Server) ->
1221
    NewPass = p1_rand:get_string(),
×
1222
    ok = ejabberd_auth:set_password(User, Server, NewPass).
×
1223

1224
build_ban_xmlel(Reason, Pass, {LastDate, LastReason}, BanDate, Hash) ->
1225
    PassEls = build_pass_els(Pass),
×
1226
    #xmlel{name = <<"banned">>,
×
1227
           attrs = [{<<"xmlns">>, <<"jabber:ejabberd:banned">>}],
1228
           children = [#xmlel{name = <<"reason">>, attrs = [], children = [{xmlcdata, Reason}]},
1229
                       #xmlel{name = <<"password">>, attrs = [], children = PassEls},
1230
                       #xmlel{name = <<"lastdate">>, attrs = [], children = [{xmlcdata, LastDate}]},
1231
                       #xmlel{name = <<"lastreason">>, attrs = [], children = [{xmlcdata, LastReason}]},
1232
                       #xmlel{name = <<"bandate">>, attrs = [], children = [{xmlcdata, BanDate}]},
1233
                       #xmlel{name = <<"hash">>, attrs = [], children = [{xmlcdata, Hash}]}
1234
                       ]}.
1235

1236
build_pass_els(Pass) when is_binary(Pass) ->
1237
    [{xmlcdata, Pass}];
×
1238
build_pass_els(#scram{storedkey = StoredKey,
1239
                      serverkey = ServerKey,
1240
                      salt = Salt,
1241
                      hash = Hash,
1242
                      iterationcount = IterationCount}) ->
1243
    [#xmlel{name = <<"storedkey">>, attrs = [], children = [{xmlcdata, StoredKey}]},
×
1244
     #xmlel{name = <<"serverkey">>, attrs = [], children = [{xmlcdata, ServerKey}]},
1245
     #xmlel{name = <<"salt">>, attrs = [], children = [{xmlcdata, Salt}]},
1246
     #xmlel{name = <<"hash">>, attrs = [], children = [{xmlcdata, misc:atom_to_binary(Hash)}]},
1247
     #xmlel{name = <<"iterationcount">>, attrs = [], children = [{xmlcdata, integer_to_binary(IterationCount)}]}
1248
    ].
1249

1250
%%
1251
%% Get ban details
1252

1253
get_ban_details(User, Host) ->
1254
    case private_get2(User, Host, <<"banned">>, <<"jabber:ejabberd:banned">>) of
1,356✔
1255
        [El] ->
1256
            get_ban_details(User, Host, El);
1,186✔
1257
        [] ->
1258
            []
170✔
1259
    end.
1260

1261
get_ban_details(User, Host, El) ->
1262
    Reason = fxml:get_subtag_cdata(El, <<"reason">>),
1,186✔
1263
    LastDate = fxml:get_subtag_cdata(El, <<"lastdate">>),
1,186✔
1264
    LastReason = fxml:get_subtag_cdata(El, <<"lastreason">>),
1,186✔
1265
    BanDate = fxml:get_subtag_cdata(El, <<"bandate">>),
1,186✔
1266
    Hash = fxml:get_subtag_cdata(El, <<"hash">>),
1,186✔
1267
    case Hash == get_hash_value(User, Host) of
1,186✔
1268
        true ->
1269
            [{"reason", Reason},
×
1270
             {"bandate", BanDate},
1271
             {"lastdate", LastDate},
1272
             {"lastreason", LastReason}];
1273
        false ->
1274
            []
1,186✔
1275
    end.
1276

1277
is_banned(User, Host) ->
1278
    case lists:keyfind("bandate", 1, get_ban_details(User, Host)) of
×
1279
        {_, BanDate} when BanDate /= <<>> ->
1280
            true;
×
1281
        _ ->
1282
            false
×
1283
    end.
1284

1285
%%
1286
%% Unban account
1287

1288
unban_account(User, Host) ->
1289
    case gen_mod:is_loaded(Host, mod_private) of
×
1290
        false ->
1291
            mod_private_is_required_but_disabled;
×
1292
        true ->
1293
            case is_banned(User, Host) of
×
1294
                false ->
1295
                    account_was_not_banned;
×
1296
                true ->
1297
                    unban_account2(User, Host)
×
1298
            end
1299
    end.
1300

1301
unban_account2(User, Host) ->
1302
    OldPass = get_oldpass(User, Host),
×
1303
    ok = ejabberd_auth:set_password(User, Host, OldPass),
×
1304
    UnBanPrivateXml = build_unban_xmlel(),
×
1305
    private_set2(User, Host, UnBanPrivateXml).
×
1306

1307
get_oldpass(User, Host) ->
1308
    [El] = private_get2(User, Host, <<"banned">>, <<"jabber:ejabberd:banned">>),
×
1309
    Pass = fxml:get_subtag(El, <<"password">>),
×
1310
    get_pass(Pass).
×
1311

1312
get_pass(#xmlel{children = [{xmlcdata, Pass}]}) ->
1313
    Pass;
×
1314
get_pass(#xmlel{children = ScramEls} = Pass) when is_list(ScramEls) ->
1315
    StoredKey = fxml:get_subtag_cdata(Pass, <<"storedkey">>),
×
1316
    ServerKey = fxml:get_subtag_cdata(Pass, <<"serverkey">>),
×
1317
    Salt = fxml:get_subtag_cdata(Pass, <<"salt">>),
×
1318
    Hash = fxml:get_subtag_cdata(Pass, <<"hash">>),
×
1319
    IterationCount = fxml:get_subtag_cdata(Pass, <<"iterationcount">>),
×
1320
    #scram{storedkey = StoredKey,
×
1321
           serverkey = ServerKey,
1322
           salt = Salt,
1323
           hash = binary_to_existing_atom(Hash, latin1),
1324
           iterationcount = binary_to_integer(IterationCount)}.
1325

1326
build_unban_xmlel() ->
1327
    #xmlel{name = <<"banned">>, attrs = [{<<"xmlns">>, <<"jabber:ejabberd:banned">>}]}.
×
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
                  _ ->
1394
                      fun(A, B) -> A == B end
×
1395
              end,
1396
    [{User, Server, Resource, num_prio(Priority), stringize(Status_text)}
×
1397
     || {{User, Resource, Status, Status_text}, Server, Priority} <- Sessions4,
×
1398
        apply(Fstatus, [Status, Status_required])].
×
1399

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

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

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

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

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

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

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

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

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

1496

1497
%%%
1498
%%% Vcard
1499
%%%
1500

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

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

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

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

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

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

1527
%%
1528
%% Room vcard
1529

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

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

1551
%%
1552
%% Internal vcard
1553

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

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

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

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

1586
get_vcard([Data], A1) ->
1587
    get_subtag(A1, Data).
×
1588

1589
get_subtag(Xmlelement, Name) ->
1590
    [fxml:get_subtag(Xmlelement, Name)].
×
1591

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

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

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

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

1650

1651
%%%
1652
%%% Roster
1653
%%%
1654

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

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

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

1696
%% -----------------------------
1697
%% Get Roster
1698
%% -----------------------------
1699

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

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

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

1728
%%-----------------------------
1729
%% Push Roster from file
1730
%%-----------------------------
1731

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

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

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

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

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

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

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

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

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

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

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

1815
%%%
1816
%%% Last Activity
1817
%%%
1818

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

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

1839
%%%
1840
%%% Private Storage
1841
%%%
1842

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

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

1852
private_get2(Username, Host, Element, Ns) ->
1853
    case gen_mod:is_loaded(Host, mod_private) of
1,356✔
1854
        true -> private_get3(Username, Host, Element, Ns);
1,186✔
1855
        false -> []
170✔
1856
    end.
1857

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

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

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

1878
%%%
1879
%%% Shared Roster Groups
1880
%%%
1881

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

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

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

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

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

1921
srg_list(Host) ->
1922
    lists:sort(mod_shared_roster:list_groups(Host)).
×
1923

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

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

1936
%% @format-begin
1937

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

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

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

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

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

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

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

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

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

2049

2050
%%%
2051
%%% Stanza
2052
%%%
2053

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

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

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

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

2139
%%%
2140
%%% Stats
2141
%%%
2142

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

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

2158

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

2173
num_prio(Priority) when is_integer(Priority) ->
UNCOV
2174
    Priority;
×
2175
num_prio(_) ->
UNCOV
2176
    -1.
×
2177

2178
%%%
2179
%%% Web Admin
2180
%%%
2181

2182
%% @format-begin
2183

2184
%%% Main
2185

2186
web_menu_main(Acc, _Lang) ->
2187
    Acc ++ [{<<"stats">>, <<"Statistics">>}].
30✔
2188

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

2213
%%% Host
2214

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

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

2246
%%% HostUser
2247

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

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

2300
%%% HostNode
2301

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

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

2315
%%% Node
2316

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

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

2359
%%%
2360
%%% Document
2361
%%%
2362

2363
mod_options(_) -> [].
9✔
2364

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

© 2026 Coveralls, Inc