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

processone / ejabberd / 1156

14 Oct 2025 01:13PM UTC coverage: 33.752% (-0.02%) from 33.775%
1156

push

github

prefiks
Fix formating

15563 of 46110 relevant lines covered (33.75%)

638.19 hits per line

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

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

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

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

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

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

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

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

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

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

1027

1028
%%%
1029
%%% Adminsys
1030
%%%
1031

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

1043
get_cookie() ->
1044
    atom_to_list(erlang:get_cookie()).
×
1045

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

1070
%%%
1071
%%% Accounts
1072
%%%
1073

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

1078
check_password(User, Host, Password) ->
1079
    ejabberd_auth:check_password(User, <<>>, Host, Password).
×
1080

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

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

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

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

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

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

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

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

1153
%%
1154
%% Ban account v0
1155

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

1162
kick_sessions(User, Server, Reason) ->
1163
    ejabberd_hooks:run(sm_kick_user, Server, [User, Server]),
×
1164
    lists:map(
×
1165
      fun(Resource) ->
1166
              kick_this_session(User, Server, Resource, Reason)
×
1167
      end,
1168
      ejabberd_sm:get_user_resources(User, Server)).
1169

1170
set_random_password(User, Server, Reason) ->
1171
    NewPass = build_random_password(Reason),
×
1172
    set_password_auth(User, Server, NewPass).
×
1173

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

1181
set_password_auth(User, Server, Password) ->
1182
    ok = ejabberd_auth:set_password(User, Server, Password).
×
1183

1184
prepare_reason([]) ->
1185
    <<"Kicked by administrator">>;
×
1186
prepare_reason([Reason]) ->
1187
    Reason;
×
1188
prepare_reason(Reason) when is_binary(Reason) ->
1189
    Reason.
×
1190

1191
%%
1192
%% Ban account v2
1193

1194
ban_account_v2(User, Host, ReasonText) ->
1195
    IsPrivateEnabled = gen_mod:is_loaded(Host, mod_private),
×
1196
    Exists = ejabberd_auth:user_exists(User, Host),
×
1197
    IsBanned = is_banned(User, Host),
×
1198
    case {IsPrivateEnabled, Exists, IsBanned} of
×
1199
        {true, true, false} ->
1200
            ban_account_v2_b(User, Host, ReasonText);
×
1201
        {false, _, _} ->
1202
            mod_private_is_required_but_disabled;
×
1203
        {_, false, _} ->
1204
            account_does_not_exist;
×
1205
        {_, _, true} ->
1206
            account_was_already_banned;
×
1207
        {_, _, _} ->
1208
            other_error
×
1209
    end.
1210

1211
ban_account_v2_b(User, Host, ReasonText) ->
1212
    Reason = prepare_reason(ReasonText),
×
1213
    Last = get_last(User, Host),
×
1214
    BanDate = xmpp_util:encode_timestamp(erlang:timestamp()),
×
1215
    Hash = get_hash_value(User, Host),
×
1216
    BanPrivateXml = build_ban_xmlel(Reason, Last, BanDate, Hash),
×
1217
    ok = private_set2(User, Host, BanPrivateXml),
×
1218
    kick_sessions(User, Host, Reason),
×
1219
    ok.
×
1220

1221
get_hash_value(User, Host) ->
1222
    Cookie = misc:atom_to_binary(erlang:get_cookie()),
1,235✔
1223
    misc:term_to_base64(crypto:hash(sha256, <<User/binary, Host/binary, Cookie/binary>>)).
1,235✔
1224

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

1235
%%
1236
%% Get ban details
1237

1238
get_ban_details(User, Host) ->
1239
    case private_get2(User, Host, <<"banned">>, <<"jabber:ejabberd:banned">>) of
1,407✔
1240
        [El] ->
1241
            get_ban_details(User, Host, El);
1,235✔
1242
        [] ->
1243
            []
172✔
1244
    end.
1245

1246
get_ban_details(User, Host, El) ->
1247
    Reason = fxml:get_subtag_cdata(El, <<"reason">>),
1,235✔
1248
    LastDate = fxml:get_subtag_cdata(El, <<"lastdate">>),
1,235✔
1249
    LastReason = fxml:get_subtag_cdata(El, <<"lastreason">>),
1,235✔
1250
    BanDate = fxml:get_subtag_cdata(El, <<"bandate">>),
1,235✔
1251
    Hash = fxml:get_subtag_cdata(El, <<"hash">>),
1,235✔
1252
    case Hash == get_hash_value(User, Host) of
1,235✔
1253
        true ->
1254
            [{"reason", Reason},
×
1255
             {"bandate", BanDate},
1256
             {"lastdate", LastDate},
1257
             {"lastreason", LastReason}];
1258
        false ->
1259
            []
1,235✔
1260
    end.
1261

1262
is_banned(User, Host) ->
1263
    case lists:keyfind("bandate", 1, get_ban_details(User, Host)) of
×
1264
        {_, BanDate} when BanDate /= <<>> ->
1265
            true;
×
1266
        _ ->
1267
            false
×
1268
    end.
1269

1270
%%
1271
%% Unban account
1272

1273
unban_account(User, Host) ->
1274
    IsPrivateEnabled = gen_mod:is_loaded(Host, mod_private),
×
1275
    Exists = ejabberd_auth:user_exists(User, Host),
×
1276
    IsBanned = is_banned(User, Host),
×
1277
    case {IsPrivateEnabled, Exists, IsBanned} of
×
1278
        {true, true, true} ->
1279
            unban_account2(User, Host);
×
1280
        {false, _, _} ->
1281
            mod_private_is_required_but_disabled;
×
1282
        {_, false, _} ->
1283
            account_does_not_exist;
×
1284
        {_, _, false} ->
1285
            account_was_not_banned;
×
1286
        {_, _, _} ->
1287
            other_error
×
1288
    end.
1289

1290
unban_account2(User, Host) ->
1291
    mod_private:del_data(jid:nodeprep(User), jid:nameprep(Host), <<"jabber:ejabberd:banned">>),
×
1292
        ok.
×
1293

1294
%%%
1295
%%% Sessions
1296
%%%
1297

1298
num_resources(User, Host) ->
1299
    length(ejabberd_sm:get_user_resources(User, Host)).
×
1300

1301
resource_num(User, Host, Num) ->
1302
    Resources = ejabberd_sm:get_user_resources(User, Host),
×
1303
    case (0<Num) and (Num=<length(Resources)) of
×
1304
        true ->
1305
            lists:nth(Num, Resources);
×
1306
        false ->
1307
            throw({bad_argument,
×
1308
                   lists:flatten(io_lib:format("Wrong resource number: ~p", [Num]))})
1309
    end.
1310

1311
kick_session(User, Server, Resource, ReasonText) ->
1312
    kick_this_session(User, Server, Resource, prepare_reason(ReasonText)),
×
1313
    ok.
×
1314

1315
kick_this_session(User, Server, Resource, Reason) ->
1316
    ejabberd_sm:route(jid:make(User, Server, Resource),
×
1317
                      {exit, Reason}).
1318

1319
status_num(Host, Status) ->
1320
    length(get_status_list(Host, Status)).
×
1321
status_num(Status) ->
1322
    status_num(<<"all">>, Status).
×
1323
status_list(Host, Status) ->
1324
    Res = get_status_list(Host, Status),
×
1325
    [{U, S, R, num_prio(P), St} || {U, S, R, P, St} <- Res].
×
1326
status_list(Status) ->
1327
    status_list(<<"all">>, Status).
×
1328

1329
status_list_v3(ArgHost, Status) ->
1330
    List = status_list(ArgHost, Status),
×
1331
    [{jid:encode(jid:make(User, Host, Resource)), Priority, StatusText}
×
1332
     || {User, Host, Resource, Priority, StatusText} <- List].
×
1333

1334
status_list_v3(Status) ->
1335
    status_list_v3(<<"all">>, Status).
×
1336

1337

1338
get_status_list(Host, Status_required) ->
1339
    %% Get list of all logged users
1340
    Sessions = ejabberd_sm:dirty_get_my_sessions_list(),
×
1341
    %% Reformat the list
1342
    Sessions2 = [ {Session#session.usr, Session#session.sid, Session#session.priority} || Session <- Sessions],
×
1343
    Fhost = case Host of
×
1344
                <<"all">> ->
1345
                    %% All hosts are requested, so don't filter at all
1346
                    fun(_, _) -> true end;
×
1347
                _ ->
1348
                    %% Filter the list, only Host is interesting
1349
                    fun(A, B) -> A == B end
×
1350
            end,
1351
    Sessions3 = [ {Pid, Server, Priority} || {{_User, Server, _Resource}, {_, Pid}, Priority} <- Sessions2, apply(Fhost, [Server, Host])],
×
1352
    %% For each Pid, get its presence
1353
    Sessions4 = [ {catch get_presence(Pid), Server, Priority} || {Pid, Server, Priority} <- Sessions3],
×
1354
    %% Filter by status
1355
    Fstatus = case Status_required of
×
1356
                  <<"all">> ->
1357
                      fun(_, _) -> true end;
×
1358
                  _ ->
1359
                      fun(A, B) -> A == B end
×
1360
              end,
1361
    [{User, Server, Resource, num_prio(Priority), stringize(Status_text)}
×
1362
     || {{User, Resource, Status, Status_text}, Server, Priority} <- Sessions4,
×
1363
        apply(Fstatus, [Status, Status_required])].
×
1364

1365
connected_users_info() ->
1366
    lists:filtermap(
×
1367
      fun({U, S, R}) ->
1368
            case user_session_info(U, S, R) of
×
1369
                offline ->
1370
                    false;
×
1371
                Info ->
1372
                    Jid = jid:encode(jid:make(U, S, R)),
×
1373
                    {true, erlang:insert_element(1, Info, Jid)}
×
1374
            end
1375
      end,
1376
      ejabberd_sm:dirty_get_sessions_list()).
1377

1378
connected_users_vhost(Host) ->
1379
    USRs = ejabberd_sm:get_vh_session_list(Host),
×
1380
    [ jid:encode(jid:make(USR)) || USR <- USRs].
×
1381

1382
%% Make string more print-friendly
1383
stringize(String) ->
1384
    %% Replace newline characters with other code
1385
    ejabberd_regexp:greplace(String, <<"\n">>, <<"\\n">>).
×
1386

1387
get_presence(Pid) ->
1388
    try get_presence2(Pid) of
×
1389
        {_, _, _, _} = Res ->
1390
            Res
×
1391
    catch
1392
        _:_ -> {<<"">>, <<"">>, <<"offline">>, <<"">>}
×
1393
    end.
1394
get_presence2(Pid) ->
1395
    Pres = #presence{from = From} = ejabberd_c2s:get_presence(Pid),
×
1396
    Show = case Pres of
×
1397
               #presence{type = unavailable} -> <<"unavailable">>;
×
1398
               #presence{show = undefined} -> <<"available">>;
×
1399
               #presence{show = S} -> atom_to_binary(S, utf8)
×
1400
           end,
1401
    Status = xmpp:get_text(Pres#presence.status),
×
1402
    {From#jid.user, From#jid.resource, Show, Status}.
×
1403

1404
get_presence(U, S) ->
1405
    Pids = [ejabberd_sm:get_session_pid(U, S, R)
×
1406
            || R <- ejabberd_sm:get_user_resources(U, S)],
×
1407
    OnlinePids = [Pid || Pid <- Pids, Pid=/=none],
×
1408
    case OnlinePids of
×
1409
        [] ->
1410
            {jid:encode({U, S, <<>>}), <<"unavailable">>, <<"">>};
×
1411
        [SessionPid|_] ->
1412
            {_User, Resource, Show, Status} = get_presence(SessionPid),
×
1413
            FullJID = jid:encode({U, S, Resource}),
×
1414
            {FullJID, Show, Status}
×
1415
    end.
1416

1417
set_presence(User, Host, Resource, Type, Show, Status, Priority) when is_binary(Priority) ->
1418
    set_presence(User, Host, Resource, Type, Show, Status, binary_to_integer(Priority));
×
1419

1420
set_presence(User, Host, Resource, Type, Show, Status, Priority) ->
1421
    Pres = #presence{
×
1422
        from = jid:make(User, Host, Resource),
1423
        to = jid:make(User, Host),
1424
        type = misc:binary_to_atom(Type),
1425
        status = xmpp:mk_text(Status),
1426
        show = misc:binary_to_atom(Show),
1427
        priority = Priority,
1428
        sub_els = []},
1429
    case ejabberd_sm:get_session_pid(User, Host, Resource) of
×
1430
        none -> throw({error, "User session not found"});
×
1431
        Ref -> ejabberd_c2s:set_presence(Ref, Pres)
×
1432
    end.
1433

1434
user_sessions_info(User, Host) ->
1435
    lists:filtermap(fun(Resource) ->
15✔
1436
                            case user_session_info(User, Host, Resource) of
×
1437
                                offline -> false;
×
1438
                                Info -> {true, Info}
×
1439
                            end
1440
                    end, ejabberd_sm:get_user_resources(User, Host)).
1441

1442
user_session_info(User, Host, Resource) ->
1443
    CurrentSec = calendar:datetime_to_gregorian_seconds({date(), time()}),
×
1444
    case ejabberd_sm:get_user_info(User, Host, Resource) of
×
1445
        offline ->
1446
            offline;
×
1447
        Info ->
1448
            Now = proplists:get_value(ts, Info),
×
1449
            Pid = proplists:get_value(pid, Info),
×
1450
            {_U, _Resource, Status, StatusText} = get_presence(Pid),
×
1451
            Priority = proplists:get_value(priority, Info),
×
1452
            Conn = proplists:get_value(conn, Info),
×
1453
            {Ip, Port} = proplists:get_value(ip, Info),
×
1454
            IPS = inet_parse:ntoa(Ip),
×
1455
            NodeS = atom_to_list(node(Pid)),
×
1456
            Uptime = CurrentSec - calendar:datetime_to_gregorian_seconds(
×
1457
                                    calendar:now_to_local_time(Now)),
1458
            {atom_to_list(Conn), IPS, Port, num_prio(Priority), NodeS, Uptime, Status, Resource, StatusText}
×
1459
    end.
1460

1461

1462
%%%
1463
%%% Vcard
1464
%%%
1465

1466
set_nickname(User, Host, Nickname) ->
1467
    VCard = xmpp:encode(#vcard_temp{nickname = Nickname}),
×
1468
    case mod_vcard:set_vcard(User, jid:nameprep(Host), VCard) of
×
1469
        {error, badarg} ->
1470
            error;
×
1471
        ok ->
1472
            ok
×
1473
    end.
1474

1475
get_vcard(User, Host, Name) ->
1476
    [Res | _] = get_vcard_content(User, Host, [Name]),
×
1477
    Res.
×
1478

1479
get_vcard(User, Host, Name, Subname) ->
1480
    [Res | _] = get_vcard_content(User, Host, [Name, Subname]),
×
1481
    Res.
×
1482

1483
get_vcard_multi(User, Host, Name, Subname) ->
1484
    get_vcard_content(User, Host, [Name, Subname]).
×
1485

1486
set_vcard(User, Host, Name, SomeContent) ->
1487
    set_vcard_content(User, Host, [Name], SomeContent).
×
1488

1489
set_vcard(User, Host, Name, Subname, SomeContent) ->
1490
    set_vcard_content(User, Host, [Name, Subname], SomeContent).
×
1491

1492
%%
1493
%% Room vcard
1494

1495
is_muc_service(Domain) ->
1496
    try mod_muc_admin:get_room_serverhost(Domain) of
×
1497
        Domain -> false;
×
1498
        Service when is_binary(Service) -> true
×
1499
    catch _:{unregistered_route, _} ->
1500
            throw(error_wrong_hostname)
×
1501
    end.
1502

1503
get_room_vcard(Name, Service) ->
1504
    case mod_muc_admin:get_room_options(Name, Service) of
×
1505
        [] ->
1506
            throw(error_no_vcard_found);
×
1507
        Opts ->
1508
            case lists:keyfind(<<"vcard">>, 1, Opts) of
×
1509
                false ->
1510
                    throw(error_no_vcard_found);
×
1511
                {_, VCardRaw} ->
1512
                    [fxml_stream:parse_element(VCardRaw)]
×
1513
            end
1514
    end.
1515

1516
%%
1517
%% Internal vcard
1518

1519
get_vcard_content(User, Server, Data) ->
1520
    case get_vcard_element(User, Server) of
×
1521
        [El|_] ->
1522
            case get_vcard(Data, El) of
×
1523
                [false] -> throw(error_no_value_found_in_vcard);
×
1524
                ElemList -> ?DEBUG("ELS ~p", [ElemList]), [fxml:get_tag_cdata(Elem) || Elem <- ElemList]
×
1525
            end;
1526
        [] ->
1527
            throw(error_no_vcard_found);
×
1528
        error ->
1529
            throw(database_failure)
×
1530
    end.
1531

1532
get_vcard_element(User, Server) ->
1533
    case is_muc_service(Server) of
×
1534
        true ->
1535
           get_room_vcard(User, Server);
×
1536
        false ->
1537
           mod_vcard:get_vcard(jid:nodeprep(User), jid:nameprep(Server))
×
1538
    end.
1539

1540
get_vcard([<<"TEL">>, TelType], {_, _, _, OldEls}) ->
1541
    {TakenEl, _NewEls} = take_vcard_tel(TelType, OldEls, [], not_found),
×
1542
    [TakenEl];
×
1543

1544
get_vcard([Data1, Data2], A1) ->
1545
    case get_subtag(A1, Data1) of
×
1546
        [false] -> [false];
×
1547
        A2List ->
1548
            lists:flatten([get_vcard([Data2], A2) || A2 <- A2List])
×
1549
    end;
1550

1551
get_vcard([Data], A1) ->
1552
    get_subtag(A1, Data).
×
1553

1554
get_subtag(Xmlelement, Name) ->
1555
    [fxml:get_subtag(Xmlelement, Name)].
×
1556

1557
set_vcard_content(User, Server, Data, SomeContent) ->
1558
    ContentList = case SomeContent of
×
1559
        [Bin | _] when is_binary(Bin) -> SomeContent;
×
1560
        Bin when is_binary(Bin) -> [SomeContent]
×
1561
    end,
1562
    %% Get old vcard
1563
    A4 = case mod_vcard:get_vcard(jid:nodeprep(User), jid:nameprep(Server)) of
×
1564
             [A1] ->
1565
                 {_, _, _, A2} = A1,
×
1566
                 update_vcard_els(Data, ContentList, A2);
×
1567
             [] ->
1568
                 update_vcard_els(Data, ContentList, []);
×
1569
             error ->
1570
                 throw(database_failure)
×
1571
         end,
1572
    %% Build new vcard
1573
    SubEl = {xmlel, <<"vCard">>, [{<<"xmlns">>,<<"vcard-temp">>}], A4},
×
1574
    mod_vcard:set_vcard(User, jid:nameprep(Server), SubEl).
×
1575

1576
take_vcard_tel(TelType, [{xmlel, <<"TEL">>, _, SubEls}=OldEl | OldEls], NewEls, Taken) ->
1577
    {Taken2, NewEls2} = case lists:keymember(TelType, 2, SubEls) of
×
1578
        true -> {fxml:get_subtag(OldEl, <<"NUMBER">>), NewEls};
×
1579
        false -> {Taken, [OldEl | NewEls]}
×
1580
    end,
1581
    take_vcard_tel(TelType, OldEls, NewEls2, Taken2);
×
1582
take_vcard_tel(TelType, [OldEl | OldEls], NewEls, Taken) ->
1583
    take_vcard_tel(TelType, OldEls, [OldEl | NewEls], Taken);
×
1584
take_vcard_tel(_TelType, [], NewEls, Taken) ->
1585
    {Taken, NewEls}.
×
1586

1587
update_vcard_els([<<"TEL">>, TelType], [TelValue], OldEls) ->
1588
    {_, NewEls} = take_vcard_tel(TelType, OldEls, [], not_found),
×
1589
    NewEl = {xmlel,<<"TEL">>,[],
×
1590
             [{xmlel,TelType,[],[]},
1591
              {xmlel,<<"NUMBER">>,[],[{xmlcdata,TelValue}]}]},
1592
    [NewEl | NewEls];
×
1593

1594
update_vcard_els(Data, ContentList, Els1) ->
1595
    Els2 = lists:keysort(2, Els1),
×
1596
    [Data1 | Data2] = Data,
×
1597
    NewEls = case Data2 of
×
1598
                [] ->
1599
                    [{xmlel, Data1, [], [{xmlcdata,Content}]} || Content <- ContentList];
×
1600
                [D2] ->
1601
                    OldEl = case lists:keysearch(Data1, 2, Els2) of
×
1602
                                {value, A} -> A;
×
1603
                                false -> {xmlel, Data1, [], []}
×
1604
                            end,
1605
                    {xmlel, _, _, ContentOld1} = OldEl,
×
1606
                    Content2 = [{xmlel, D2, [], [{xmlcdata,Content}]} || Content <- ContentList],
×
1607
                    ContentOld2 = [A || {_, X, _, _} = A <- ContentOld1, X/=D2],
×
1608
                    ContentOld3 = lists:keysort(2, ContentOld2),
×
1609
                    ContentNew = lists:keymerge(2, Content2, ContentOld3),
×
1610
                    [{xmlel, Data1, [], ContentNew}]
×
1611
            end,
1612
    Els3 = lists:keydelete(Data1, 2, Els2),
×
1613
    lists:keymerge(2, NewEls, Els3).
×
1614

1615

1616
%%%
1617
%%% Roster
1618
%%%
1619

1620
add_rosteritem(LocalUser, LocalServer, User, Server, Nick, Group, Subs) when is_binary(Group) ->
1621
    add_rosteritem(LocalUser, LocalServer, User, Server, Nick, [Group], Subs);
×
1622
add_rosteritem(LocalUser, LocalServer, User, Server, Nick, Groups, Subs) ->
1623
    case {jid:make(LocalUser, LocalServer), jid:make(User, Server)} of
×
1624
        {error, _} ->
1625
            throw({error, "Invalid 'localuser'/'localserver'"});
×
1626
        {_, error} ->
1627
            throw({error, "Invalid 'user'/'server'"});
×
1628
        {Jid, _Jid2} ->
1629
            RosterItem = build_roster_item(User, Server, {add, Nick, Subs, Groups}),
×
1630
            case mod_roster:set_item_and_notify_clients(Jid, RosterItem, true) of
×
1631
                ok -> ok;
×
1632
                _ -> error
×
1633
            end
1634
    end.
1635

1636
subscribe(LU, LS, User, Server, Nick, Group, Subscription, _Xattrs) ->
1637
    case {jid:make(LU, LS), jid:make(User, Server)} of
×
1638
        {error, _} ->
1639
            throw({error, "Invalid 'localuser'/'localserver'"});
×
1640
        {_, error} ->
1641
            throw({error, "Invalid 'user'/'server'"});
×
1642
        {_Jid, _Jid2} ->
1643
            ItemEl = build_roster_item(User, Server, {add, Nick, Subscription, Group}),
×
1644
            mod_roster:set_items(LU, LS, #roster_query{items = [ItemEl]})
×
1645
    end.
1646

1647
delete_rosteritem(LocalUser, LocalServer, User, Server) ->
1648
    case {jid:make(LocalUser, LocalServer), jid:make(User, Server)} of
×
1649
        {error, _} ->
1650
            throw({error, "Invalid 'localuser'/'localserver'"});
×
1651
        {_, error} ->
1652
            throw({error, "Invalid 'user'/'server'"});
×
1653
        {Jid, _Jid2} ->
1654
            RosterItem = build_roster_item(User, Server, remove),
×
1655
            case mod_roster:set_item_and_notify_clients(Jid, RosterItem, true) of
×
1656
                ok -> ok;
×
1657
                _ -> error
×
1658
            end
1659
    end.
1660

1661
%% -----------------------------
1662
%% Get Roster
1663
%% -----------------------------
1664

1665
get_roster(User, Server) ->
1666
    case jid:make(User, Server) of
×
1667
        error ->
1668
            throw({error, "Invalid 'user'/'server'"});
×
1669
        #jid{luser = U, lserver = S} ->
1670
            Items = ejabberd_hooks:run_fold(roster_get, S, [], [{U, S}]),
×
1671
            make_roster_xmlrpc(Items)
×
1672
    end.
1673

1674
make_roster_xmlrpc(Roster) ->
1675
    lists:map(
×
1676
      fun(#roster_item{jid = JID, name = Nick, subscription = Sub, ask = Ask, groups = Groups}) ->
1677
              JIDS = jid:encode(JID),
×
1678
              Subs = atom_to_list(Sub),
×
1679
              Asks = atom_to_list(Ask),
×
1680
              {JIDS, Nick, Subs, Asks, Groups}
×
1681
      end,
1682
      Roster).
1683

1684
get_roster_count(User, Server) ->
1685
    case jid:make(User, Server) of
30✔
1686
        error ->
1687
            throw({error, "Invalid 'user'/'server'"});
×
1688
        #jid{luser = U, lserver = S} ->
1689
            Items = ejabberd_hooks:run_fold(roster_get, S, [], [{U, S}]),
30✔
1690
            length(Items)
30✔
1691
    end.
1692

1693
%%-----------------------------
1694
%% Push Roster from file
1695
%%-----------------------------
1696

1697
push_roster(File, User, Server) ->
1698
    {ok, [Roster]} = file:consult(File),
×
1699
    subscribe_roster({User, Server, <<>>, User}, Roster).
×
1700

1701
push_roster_all(File) ->
1702
    {ok, [Roster]} = file:consult(File),
×
1703
    subscribe_all(Roster).
×
1704

1705
subscribe_all(Roster) ->
1706
    subscribe_all(Roster, Roster).
×
1707
subscribe_all([], _) ->
1708
    ok;
×
1709
subscribe_all([User1 | Users], Roster) ->
1710
    subscribe_roster(User1, Roster),
×
1711
    subscribe_all(Users, Roster).
×
1712

1713
subscribe_roster(_, []) ->
1714
    ok;
×
1715
%% Do not subscribe a user to itself
1716
subscribe_roster({Name, Server, Group, Nick}, [{Name, Server, _, _} | Roster]) ->
1717
    subscribe_roster({Name, Server, Group, Nick}, Roster);
×
1718
%% Subscribe Name2 to Name1
1719
subscribe_roster({Name1, Server1, Group1, Nick1}, [{Name2, Server2, Group2, Nick2} | Roster]) ->
1720
    subscribe(iolist_to_binary(Name1), iolist_to_binary(Server1), iolist_to_binary(Name2), iolist_to_binary(Server2),
×
1721
        iolist_to_binary(Nick2), iolist_to_binary(Group2), <<"both">>, []),
1722
    subscribe_roster({Name1, Server1, Group1, Nick1}, Roster).
×
1723

1724
push_alltoall(S, G) ->
1725
    Users = ejabberd_auth:get_users(S),
×
1726
    Users2 = build_list_users(G, Users, []),
×
1727
    subscribe_all(Users2),
×
1728
    ok.
×
1729

1730
build_list_users(_Group, [], Res) ->
1731
    Res;
×
1732
build_list_users(Group, [{User, Server}|Users], Res) ->
1733
    build_list_users(Group, Users, [{User, Server, Group, User}|Res]).
×
1734

1735
%% @spec(LU, LS, U, S, Action) -> ok
1736
%%       Action = {add, Nick, Subs, Group} | remove
1737
%% @doc Push to the roster of account LU@LS the contact U@S.
1738
%% The specific action to perform is defined in Action.
1739
push_roster_item(LU, LS, U, S, Action) ->
1740
    lists:foreach(fun(R) ->
×
1741
                          push_roster_item(LU, LS, R, U, S, Action)
×
1742
                  end, ejabberd_sm:get_user_resources(LU, LS)).
1743

1744
push_roster_item(LU, LS, R, U, S, Action) ->
1745
    LJID = jid:make(LU, LS, R),
×
1746
    BroadcastEl = build_broadcast(U, S, Action),
×
1747
    ejabberd_sm:route(LJID, BroadcastEl),
×
1748
    Item = build_roster_item(U, S, Action),
×
1749
    ResIQ = build_iq_roster_push(Item),
×
1750
    ejabberd_router:route(
×
1751
      xmpp:set_from_to(ResIQ, jid:remove_resource(LJID), LJID)).
1752

1753
build_roster_item(U, S, {add, Nick, Subs, Groups}) when is_list(Groups) ->
1754
    #roster_item{jid = jid:make(U, S),
×
1755
                 name = Nick,
1756
                 subscription = misc:binary_to_atom(Subs),
1757
                 groups = Groups};
1758
build_roster_item(U, S, {add, Nick, Subs, Group}) ->
1759
    Groups = binary:split(Group,<<";">>, [global, trim]),
×
1760
    #roster_item{jid = jid:make(U, S),
×
1761
                 name = Nick,
1762
                 subscription = misc:binary_to_atom(Subs),
1763
                 groups = Groups};
1764
build_roster_item(U, S, remove) ->
1765
    #roster_item{jid = jid:make(U, S), subscription = remove}.
×
1766

1767
build_iq_roster_push(Item) ->
1768
    #iq{type = set, id = <<"push">>,
×
1769
        sub_els = [#roster_query{items = [Item]}]}.
1770

1771
build_broadcast(U, S, {add, _Nick, Subs, _Group}) ->
1772
    build_broadcast(U, S, list_to_atom(binary_to_list(Subs)));
×
1773
build_broadcast(U, S, remove) ->
1774
    build_broadcast(U, S, none);
×
1775
%% @spec (U::binary(), S::binary(), Subs::atom()) -> any()
1776
%% Subs = both | from | to | none
1777
build_broadcast(U, S, SubsAtom) when is_atom(SubsAtom) ->
1778
    {item, {U, S, <<>>}, SubsAtom}.
×
1779

1780
%%%
1781
%%% Last Activity
1782
%%%
1783

1784
get_last(User, Server) ->
1785
    {Now, Status} = case ejabberd_sm:get_user_resources(User, Server) of
45✔
1786
        [] ->
1787
            case mod_last:get_last_info(User, Server) of
45✔
1788
                not_found ->
1789
                    {erlang:timestamp(), "NOT FOUND"};
×
1790
                {ok, Shift, Status1} ->
1791
                    {{Shift div 1000000, Shift rem 1000000, 0}, Status1}
45✔
1792
            end;
1793
        _ ->
1794
            {erlang:timestamp(), "ONLINE"}
×
1795
    end,
1796
    {xmpp_util:encode_timestamp(Now), Status}.
45✔
1797

1798
set_last(User, Server, Timestamp, Status) ->
1799
    case mod_last:store_last_info(User, Server, Timestamp, Status) of
×
1800
        {ok, _} -> ok;
×
1801
        Error -> Error
×
1802
    end.
1803

1804
%%%
1805
%%% Private Storage
1806
%%%
1807

1808
%% Example usage:
1809
%% $ ejabberdctl private_set badlop localhost "\<aa\ xmlns=\'bb\'\>Cluth\</aa\>"
1810
%% $ ejabberdctl private_get badlop localhost aa bb
1811
%% <aa xmlns='bb'>Cluth</aa>
1812

1813
private_get(Username, Host, Element, Ns) ->
1814
    Els = private_get2(Username, Host, Element, Ns),
×
1815
    binary_to_list(fxml:element_to_binary(xmpp:encode(#private{sub_els = Els}))).
×
1816

1817
private_get2(Username, Host, Element, Ns) ->
1818
    case gen_mod:is_loaded(Host, mod_private) of
1,407✔
1819
        true -> private_get3(Username, Host, Element, Ns);
1,235✔
1820
        false -> []
172✔
1821
    end.
1822

1823
private_get3(Username, Host, Element, Ns) ->
1824
    ElementXml = #xmlel{name = Element, attrs = [{<<"xmlns">>, Ns}]},
1,235✔
1825
    mod_private:get_data(jid:nodeprep(Username), jid:nameprep(Host),
1,235✔
1826
                               [{Ns, ElementXml}]).
1827

1828
private_set(Username, Host, ElementString) ->
1829
    case fxml_stream:parse_element(ElementString) of
×
1830
        {error, Error} ->
1831
            io:format("Error found parsing the element:~n  ~p~nError: ~p~n",
×
1832
                      [ElementString, Error]),
1833
            error;
×
1834
        Xml ->
1835
            private_set2(Username, Host, Xml)
×
1836
    end.
1837

1838
private_set2(Username, Host, Xml) ->
1839
    NS = fxml:get_tag_attr_s(<<"xmlns">>, Xml),
×
1840
    JID = jid:make(Username, Host),
×
1841
    mod_private:set_data(JID, [{NS, Xml}]).
×
1842

1843
%%%
1844
%%% Shared Roster Groups
1845
%%%
1846

1847
srg_create(Group, Host, Label, Description, Display) when is_binary(Display) ->
1848
    DisplayList = case Display of
×
1849
       <<>> -> [];
×
1850
       _ -> ejabberd_regexp:split(Display, <<"\\\\n">>)
×
1851
    end,
1852
    srg_create(Group, Host, Label, Description, DisplayList);
×
1853

1854
srg_create(Group, Host, Label, Description, DisplayList) ->
1855
    {_DispGroups, WrongDispGroups} = filter_groups_existence(Host, DisplayList),
×
1856
    case (WrongDispGroups -- [Group]) /= [] of
×
1857
        true ->
1858
            {wrong_displayed_groups, WrongDispGroups};
×
1859
        false ->
1860
            srg_create2(Group, Host, Label, Description, DisplayList)
×
1861
    end.
1862

1863
srg_create2(Group, Host, Label, Description, DisplayList) ->
1864
    Opts = [{label, Label},
×
1865
            {displayed_groups, DisplayList},
1866
            {description, Description}],
1867
    case mod_shared_roster:create_group(Host, Group, Opts) of
×
1868
        {atomic, _} -> ok;
×
1869
        {error, Err} -> Err
×
1870
    end.
1871

1872
srg_add(Group, Host) ->
1873
    Opts = [{label, <<"">>},
×
1874
            {description, <<"">>},
1875
            {displayed_groups, []}
1876
           ],
1877
    case mod_shared_roster:create_group(Host, Group, Opts) of
×
1878
        {atomic, _} -> ok;
×
1879
        {error, Err} -> Err
×
1880
    end.
1881

1882
srg_delete(Group, Host) ->
1883
    {atomic, _} = mod_shared_roster:delete_group(Host, Group),
×
1884
    ok.
×
1885

1886
srg_list(Host) ->
1887
    lists:sort(mod_shared_roster:list_groups(Host)).
×
1888

1889
srg_get_info(Group, Host) ->
1890
    Opts = case mod_shared_roster:get_group_opts(Host,Group) of
×
1891
        Os when is_list(Os) -> Os;
×
1892
        error -> []
×
1893
    end,
1894
    [{misc:atom_to_binary(Title), to_list(Value)} || {Title, Value} <- Opts].
×
1895

1896
to_list([]) -> [];
×
1897
to_list([H|_]=List) when is_binary(H) -> lists:join(", ", [to_list(E) || E <- List]);
×
1898
to_list(E) when is_atom(E) -> atom_to_list(E);
×
1899
to_list(E) when is_binary(E) -> binary_to_list(E).
×
1900

1901
%% @format-begin
1902

1903
srg_set_info(Group, Host, Key, Value) ->
1904
    Opts =
×
1905
        case mod_shared_roster:get_group_opts(Host, Group) of
1906
            Os when is_list(Os) ->
1907
                Os;
×
1908
            error ->
1909
                []
×
1910
        end,
1911
    Opts2 = srg_set_info(Key, Value, Opts),
×
1912
    case mod_shared_roster:set_group_opts(Host, Group, Opts2) of
×
1913
        {atomic, ok} ->
1914
            ok;
×
1915
        Problem ->
1916
            ?INFO_MSG("Problem: ~n  ~p", [Problem]), %+++
×
1917
            error
×
1918
    end.
1919

1920
srg_set_info(<<"description">>, Value, Opts) ->
1921
    [{description, Value} | proplists:delete(description, Opts)];
×
1922
srg_set_info(<<"label">>, Value, Opts) ->
1923
    [{label, Value} | proplists:delete(label, Opts)];
×
1924
srg_set_info(<<"all_users">>, <<"true">>, Opts) ->
1925
    [{all_users, true} | proplists:delete(all_users, Opts)];
×
1926
srg_set_info(<<"online_users">>, <<"true">>, Opts) ->
1927
    [{online_users, true} | proplists:delete(online_users, Opts)];
×
1928
srg_set_info(<<"all_users">>, _, Opts) ->
1929
    proplists:delete(all_users, Opts);
×
1930
srg_set_info(<<"online_users">>, _, Opts) ->
1931
    proplists:delete(online_users, Opts);
×
1932
srg_set_info(Key, _Value, Opts) ->
1933
    ?ERROR_MSG("Unknown Key in srg_set_info: ~p", [Key]),
×
1934
    Opts.
×
1935

1936
srg_get_displayed(Group, Host) ->
1937
    Opts =
×
1938
        case mod_shared_roster:get_group_opts(Host, Group) of
1939
            Os when is_list(Os) ->
1940
                Os;
×
1941
            error ->
1942
                []
×
1943
        end,
1944
    proplists:get_value(displayed_groups, Opts, []).
×
1945

1946
srg_add_displayed(Group, Host, NewGroup) ->
1947
    Opts =
×
1948
        case mod_shared_roster:get_group_opts(Host, Group) of
1949
            Os when is_list(Os) ->
1950
                Os;
×
1951
            error ->
1952
                []
×
1953
        end,
1954
    {DispGroups, WrongDispGroups} = filter_groups_existence(Host, [NewGroup]),
×
1955
    case WrongDispGroups /= [] of
×
1956
        true ->
1957
            {wrong_displayed_groups, WrongDispGroups};
×
1958
        false ->
1959
            DisplayedOld = proplists:get_value(displayed_groups, Opts, []),
×
1960
            Opts2 =
×
1961
                [{displayed_groups, lists:flatten(DisplayedOld, DispGroups)}
1962
                 | proplists:delete(displayed_groups, Opts)],
1963
            case mod_shared_roster:set_group_opts(Host, Group, Opts2) of
×
1964
                {atomic, ok} ->
1965
                    ok;
×
1966
                Problem ->
1967
                    ?INFO_MSG("Problem: ~n  ~p", [Problem]), %+++
×
1968
                    error
×
1969
            end
1970
    end.
1971

1972
srg_del_displayed(Group, Host, OldGroup) ->
1973
    Opts =
×
1974
        case mod_shared_roster:get_group_opts(Host, Group) of
1975
            Os when is_list(Os) ->
1976
                Os;
×
1977
            error ->
1978
                []
×
1979
        end,
1980
    DisplayedOld = proplists:get_value(displayed_groups, Opts, []),
×
1981
    {DispGroups, OldDispGroups} = lists:partition(fun(G) -> G /= OldGroup end, DisplayedOld),
×
1982
    case OldDispGroups == [] of
×
1983
        true ->
1984
            {inexistent_displayed_groups, OldGroup};
×
1985
        false ->
1986
            Opts2 = [{displayed_groups, DispGroups} | proplists:delete(displayed_groups, Opts)],
×
1987
            case mod_shared_roster:set_group_opts(Host, Group, Opts2) of
×
1988
                {atomic, ok} ->
1989
                    ok;
×
1990
                Problem ->
1991
                    ?INFO_MSG("Problem: ~n  ~p", [Problem]), %+++
×
1992
                    error
×
1993
            end
1994
    end.
1995

1996
filter_groups_existence(Host, Groups) ->
1997
    lists:partition(fun(Group) -> error /= mod_shared_roster:get_group_opts(Host, Group) end,
×
1998
                    Groups).
1999
%% @format-end
2000

2001
srg_get_members(Group, Host) ->
2002
    Members = mod_shared_roster:get_group_explicit_users(Host,Group),
×
2003
    [jid:encode(jid:make(MUser, MServer))
×
2004
     || {MUser, MServer} <- Members].
×
2005

2006
srg_user_add(User, Host, Group, GroupHost) ->
2007
    mod_shared_roster:add_user_to_group(GroupHost, {User, Host}, Group),
×
2008
    ok.
×
2009

2010
srg_user_del(User, Host, Group, GroupHost) ->
2011
    mod_shared_roster:remove_user_from_group(GroupHost, {User, Host}, Group),
×
2012
    ok.
×
2013

2014

2015
%%%
2016
%%% Stanza
2017
%%%
2018

2019
%% @doc Send a message to an XMPP account.
2020
-spec send_message(Type::binary(), From::binary(), To::binary(),
2021
                   Subject::binary(), Body::binary()) -> ok.
2022
send_message(Type, From, To, Subject, Body) ->
2023
    CodecOpts = ejabberd_config:codec_options(),
×
2024
    try xmpp:decode(
×
2025
          #xmlel{name = <<"message">>,
2026
                 attrs = [{<<"to">>, To},
2027
                          {<<"from">>, From},
2028
                          {<<"type">>, Type},
2029
                          {<<"id">>, p1_rand:get_string()}],
2030
                 children =
2031
                     [#xmlel{name = <<"subject">>,
2032
                             children = [{xmlcdata, Subject}]},
2033
                      #xmlel{name = <<"body">>,
2034
                             children = [{xmlcdata, Body}]}]},
2035
          ?NS_CLIENT, CodecOpts) of
2036
        #message{from = JID, subject = SubjectEl, body = BodyEl} = Msg ->
2037
            Msg2 = case {xmpp:get_text(SubjectEl), xmpp:get_text(BodyEl)} of
×
2038
                       {Subject, <<>>} -> Msg;
×
2039
                       {<<>>, Body} -> Msg#message{subject = []};
×
2040
                       _ -> Msg
×
2041
                   end,
2042
            State = #{jid => JID},
×
2043
            ejabberd_hooks:run_fold(user_send_packet, JID#jid.lserver, {Msg2, State}, []),
×
2044
            ejabberd_router:route(Msg2)
×
2045
    catch _:{xmpp_codec, Why} ->
2046
            {error, xmpp:format_error(Why)}
×
2047
    end.
2048

2049
send_stanza(FromString, ToString, Stanza) ->
2050
    try
×
2051
        #xmlel{} = El = fxml_stream:parse_element(Stanza),
×
2052
        From = jid:decode(FromString),
×
2053
        To = jid:decode(ToString),
×
2054
        CodecOpts = ejabberd_config:codec_options(),
×
2055
        Pkt = xmpp:decode(El, ?NS_CLIENT, CodecOpts),
×
2056
        Pkt2 = xmpp:set_from_to(Pkt, From, To),
×
2057
        State = #{jid => From},
×
2058
        ejabberd_hooks:run_fold(user_send_packet, From#jid.lserver,
×
2059
                                {Pkt2, State}, []),
2060
        ejabberd_router:route(Pkt2)
×
2061
    catch _:{xmpp_codec, Why} ->
2062
            io:format("incorrect stanza: ~ts~n", [xmpp:format_error(Why)]),
×
2063
            {error, Why};
×
2064
          _:{badmatch, {error, {Code, Why}}} when is_integer(Code) ->
2065
            io:format("invalid xml: ~p~n", [Why]),
×
2066
            {error, Why};
×
2067
          _:{badmatch, {error, Why}} ->
2068
            io:format("invalid xml: ~p~n", [Why]),
×
2069
            {error, Why};
×
2070
          _:{bad_jid, S} ->
2071
            io:format("malformed JID: ~ts~n", [S]),
×
2072
            {error, "JID malformed"}
×
2073
    end.
2074

2075
-spec send_stanza_c2s(binary(), binary(), binary(), binary()) -> ok | {error, any()}.
2076
send_stanza_c2s(Username, Host, Resource, Stanza) ->
2077
    try
×
2078
        #xmlel{} = El = fxml_stream:parse_element(Stanza),
×
2079
        CodecOpts = ejabberd_config:codec_options(),
×
2080
        Pkt = xmpp:decode(El, ?NS_CLIENT, CodecOpts),
×
2081
        case ejabberd_sm:get_session_pid(Username, Host, Resource) of
×
2082
            Pid when is_pid(Pid) ->
2083
                ejabberd_c2s:send(Pid, Pkt);
×
2084
            _ ->
2085
                {error, no_session}
×
2086
        end
2087
    catch _:{badmatch, {error, Why} = Err} ->
2088
            io:format("invalid xml: ~p~n", [Why]),
×
2089
            Err;
×
2090
          _:{xmpp_codec, Why} ->
2091
            io:format("incorrect stanza: ~ts~n", [xmpp:format_error(Why)]),
×
2092
            {error, Why}
×
2093
    end.
2094

2095
privacy_set(Username, Host, QueryS) ->
2096
    Jid = jid:make(Username, Host),
×
2097
    QueryEl = fxml_stream:parse_element(QueryS),
×
2098
    SubEl = xmpp:decode(QueryEl),
×
2099
    IQ = #iq{type = set, id = <<"push">>, sub_els = [SubEl],
×
2100
             from = Jid, to = Jid},
2101
    Result = mod_privacy:process_iq(IQ),
×
2102
    Result#iq.type == result.
×
2103

2104
%%%
2105
%%% Stats
2106
%%%
2107

2108
stats(Name) ->
2109
    case Name of
×
2110
        <<"uptimeseconds">> -> trunc(element(1, erlang:statistics(wall_clock))/1000);
×
2111
        <<"processes">> -> length(erlang:processes());
×
2112
        <<"registeredusers">> -> lists:foldl(fun(Host, Sum) -> ejabberd_auth:count_users(Host) + Sum end, 0, ejabberd_option:hosts());
×
2113
        <<"onlineusersnode">> -> length(ejabberd_sm:dirty_get_my_sessions_list());
×
2114
        <<"onlineusers">> -> length(ejabberd_sm:dirty_get_sessions_list())
×
2115
    end.
2116

2117
stats(Name, Host) ->
2118
    case Name of
×
2119
        <<"registeredusers">> -> ejabberd_auth:count_users(Host);
×
2120
        <<"onlineusers">> -> length(ejabberd_sm:get_vh_session_list(Host))
×
2121
    end.
2122

2123

2124
user_action(User, Server, Fun, OK) ->
2125
    case ejabberd_auth:user_exists(User, Server) of
5✔
2126
        true ->
2127
            case catch Fun() of
5✔
2128
                OK -> ok;
5✔
2129
                {error, Error} -> throw(Error);
×
2130
                Error ->
2131
                    ?ERROR_MSG("Command returned: ~p", [Error]),
×
2132
                    1
×
2133
            end;
2134
        false ->
2135
            throw({not_found, "unknown_user"})
×
2136
    end.
2137

2138
num_prio(Priority) when is_integer(Priority) ->
2139
    Priority;
×
2140
num_prio(_) ->
2141
    -1.
×
2142

2143
%%%
2144
%%% Web Admin
2145
%%%
2146

2147
%% @format-begin
2148

2149
%%% Main
2150

2151
web_menu_main(Acc, _Lang) ->
2152
    Acc ++ [{<<"stats">>, <<"Statistics">>}].
30✔
2153

2154
web_page_main(_, #request{path = [<<"stats">>]} = R) ->
2155
    Res = ?H1GL(<<"Statistics">>, <<"modules/#mod_stats">>, <<"mod_stats">>)
×
2156
          ++ [make_command(stats_host, R, [], [{only, presentation}]),
2157
              make_command(incoming_s2s_number, R, [], [{only, presentation}]),
2158
              make_command(outgoing_s2s_number, R, [], [{only, presentation}]),
2159
              make_table([<<"stat name">>, {<<"stat value">>, right}],
2160
                         [{?C(<<"Registered Users:">>),
2161
                           make_command(stats,
2162
                                        R,
2163
                                        [{<<"name">>, <<"registeredusers">>}],
2164
                                        [{only, value}])},
2165
                          {?C(<<"Online Users:">>),
2166
                           make_command(stats,
2167
                                        R,
2168
                                        [{<<"name">>, <<"onlineusers">>}],
2169
                                        [{only, value}])},
2170
                          {?C(<<"S2S Connections Incoming:">>),
2171
                           make_command(incoming_s2s_number, R, [], [{only, value}])},
2172
                          {?C(<<"S2S Connections Outgoing:">>),
2173
                           make_command(outgoing_s2s_number, R, [], [{only, value}])}])],
2174
    {stop, Res};
×
2175
web_page_main(Acc, _) ->
2176
    Acc.
×
2177

2178
%%% Host
2179

2180
web_menu_host(Acc, _Host, _Lang) ->
2181
    Acc ++ [{<<"purge">>, <<"Purge">>}, {<<"stats">>, <<"Statistics">>}].
×
2182

2183
web_page_host(_, Host, #request{path = [<<"purge">>]} = R) ->
2184
    Head = [?XC(<<"h1">>, <<"Purge">>)],
×
2185
    Set = [ejabberd_web_admin:make_command(delete_old_users_vhost,
×
2186
                                           R,
2187
                                           [{<<"host">>, Host}],
2188
                                           [])],
2189
    {stop, Head ++ Set};
×
2190
web_page_host(_, Host, #request{path = [<<"stats">>]} = R) ->
2191
    Res = ?H1GL(<<"Statistics">>, <<"modules/#mod_stats">>, <<"mod_stats">>)
×
2192
          ++ [make_command(stats_host, R, [], [{only, presentation}]),
2193
              make_table([<<"stat name">>, {<<"stat value">>, right}],
2194
                         [{?C(<<"Registered Users:">>),
2195
                           make_command(stats_host,
2196
                                        R,
2197
                                        [{<<"host">>, Host}, {<<"name">>, <<"registeredusers">>}],
2198
                                        [{only, value},
2199
                                         {result_links, [{stat, arg_host, 3, <<"users">>}]}])},
2200
                          {?C(<<"Online Users:">>),
2201
                           make_command(stats_host,
2202
                                        R,
2203
                                        [{<<"host">>, Host}, {<<"name">>, <<"onlineusers">>}],
2204
                                        [{only, value},
2205
                                         {result_links,
2206
                                          [{stat, arg_host, 3, <<"online-users">>}]}])}])],
2207
    {stop, Res};
×
2208
web_page_host(Acc, _, _) ->
2209
    Acc.
×
2210

2211
%%% HostUser
2212

2213
web_menu_hostuser(Acc, _Host, _Username, _Lang) ->
2214
    Acc ++ [{<<"auth">>, <<"Authentication">>}, {<<"session">>, <<"Sessions">>}].
×
2215

2216
web_page_hostuser(_, Host, User, #request{path = [<<"auth">>]} = R) ->
2217
    Ban = make_command(ban_account,
×
2218
                       R,
2219
                       [{<<"user">>, User}, {<<"host">>, Host}],
2220
                       [{style, danger}]),
2221
    Unban = make_command(unban_account, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
×
2222
    Res = ?H1GLraw(<<"Authentication">>,
×
2223
                   <<"admin/configuration/authentication/">>,
2224
                   <<"Authentication">>)
2225
          ++ [make_command(register, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
2226
              make_command(check_account, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
2227
              ?X(<<"hr">>),
2228
              make_command(check_password, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
2229
              make_command(check_password_hash, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
2230
              make_command(change_password,
2231
                           R,
2232
                           [{<<"user">>, User}, {<<"host">>, Host}],
2233
                           [{style, danger}]),
2234
              ?X(<<"hr">>),
2235
              make_command(get_ban_details, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
2236
              Ban,
2237
              Unban,
2238
              ?X(<<"hr">>),
2239
              make_command(unregister,
2240
                           R,
2241
                           [{<<"user">>, User}, {<<"host">>, Host}],
2242
                           [{style, danger}])],
2243
    {stop, Res};
×
2244
web_page_hostuser(_, Host, User, #request{path = [<<"session">>]} = R) ->
2245
    Head = [?XC(<<"h1">>, <<"Sessions">>), ?BR],
×
2246
    Set = [make_command(resource_num, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
×
2247
           make_command(set_presence, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
2248
           make_command(kick_user, R, [{<<"user">>, User}, {<<"host">>, Host}], [{style, danger}]),
2249
           make_command(kick_session,
2250
                        R,
2251
                        [{<<"user">>, User}, {<<"host">>, Host}],
2252
                        [{style, danger}])],
2253
    timer:sleep(100), % kicking sessions takes a while, let's delay the get commands
×
2254
    Get = [make_command(user_sessions_info,
×
2255
                        R,
2256
                        [{<<"user">>, User}, {<<"host">>, Host}],
2257
                        [{result_links, [{node, node, 5, <<>>}]}]),
2258
           make_command(user_resources, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
2259
           make_command(get_presence, R, [{<<"user">>, User}, {<<"host">>, Host}], []),
2260
           make_command(num_resources, R, [{<<"user">>, User}, {<<"host">>, Host}], [])],
2261
    {stop, Head ++ Get ++ Set};
×
2262
web_page_hostuser(Acc, _, _, _) ->
2263
    Acc.
×
2264

2265
%%% HostNode
2266

2267
web_menu_hostnode(Acc, _Host, _Username, _Lang) ->
2268
    Acc ++ [{<<"modules">>, <<"Modules">>}].
×
2269

2270
web_page_hostnode(_, Host, Node, #request{path = [<<"modules">>]} = R) ->
2271
    Res = ?H1GLraw(<<"Modules">>, <<"admin/configuration/modules/">>, <<"Modules Options">>)
×
2272
          ++ [ejabberd_cluster:call(Node,
2273
                                    ejabberd_web_admin,
2274
                                    make_command,
2275
                                    [restart_module, R, [{<<"host">>, Host}], []])],
2276
    {stop, Res};
×
2277
web_page_hostnode(Acc, _Host, _Node, _Request) ->
2278
    Acc.
×
2279

2280
%%% Node
2281

2282
web_menu_node(Acc, _Node, _Lang) ->
2283
    Acc ++ [{<<"stats">>, <<"Statistics">>}].
×
2284

2285
web_page_node(_, Node, #request{path = [<<"stats">>]} = R) ->
2286
    UpSecs =
×
2287
        ejabberd_cluster:call(Node,
2288
                              ejabberd_web_admin,
2289
                              make_command,
2290
                              [stats, R, [{<<"name">>, <<"uptimeseconds">>}], [{only, value}]]),
2291
    UpDaysBin =
×
2292
        integer_to_binary(binary_to_integer(fxml:get_tag_cdata(UpSecs))
2293
                          div 86400), % 24*60*60
2294
    UpDays =
×
2295
        #xmlel{name = <<"code">>,
2296
               attrs = [],
2297
               children = [{xmlcdata, UpDaysBin}]},
2298
    Res = ?H1GL(<<"Statistics">>, <<"modules/#mod_stats">>, <<"mod_stats">>)
×
2299
          ++ [make_command(stats, R, [], [{only, presentation}]),
2300
              make_table([<<"stat name">>, {<<"stat value">>, right}],
2301
                         [{?C(<<"Online Users in this node:">>),
2302
                           ejabberd_cluster:call(Node,
2303
                                                 ejabberd_web_admin,
2304
                                                 make_command,
2305
                                                 [stats,
2306
                                                  R,
2307
                                                  [{<<"name">>, <<"onlineusersnode">>}],
2308
                                                  [{only, value}]])},
2309
                          {?C(<<"Uptime Seconds:">>), UpSecs},
2310
                          {?C(<<"Uptime Seconds (rounded to days):">>), UpDays},
2311
                          {?C(<<"Processes:">>),
2312
                           ejabberd_cluster:call(Node,
2313
                                                 ejabberd_web_admin,
2314
                                                 make_command,
2315
                                                 [stats,
2316
                                                  R,
2317
                                                  [{<<"name">>, <<"processes">>}],
2318
                                                  [{only, value}]])}])],
2319
    {stop, Res};
×
2320
web_page_node(Acc, _, _) ->
2321
    Acc.
×
2322
%% @format-end
2323

2324
%%%
2325
%%% Document
2326
%%%
2327

2328
mod_options(_) -> [].
9✔
2329

2330
mod_doc() ->
2331
    #{desc =>
×
2332
          [?T("This module provides additional administrative commands."), "",
2333
           ?T("Details for some commands:"), "",
2334
           ?T("_`ban_account`_ API:"),
2335
           ?T("This command kicks all the connected sessions of the account "
2336
              "from the server. It also changes their password to a randomly "
2337
              "generated one, so they can't login anymore unless a server "
2338
              "administrator changes their password again. It is possible to "
2339
              "define the reason of the ban. The new password also includes "
2340
              "the reason and the date and time of the ban. See an example below."), "",
2341
           ?T("_`push_roster`_ API (and _`push_roster_all`_ API):"),
2342
           ?T("The roster file must be placed, if using Windows, on the "
2343
              "directory where you installed ejabberd: "
2344
              "`C:/Program Files/ejabberd` or similar. If you use other "
2345
              "Operating System, place the file on the same directory where "
2346
              "the .beam files are installed. See below an example roster file."), "",
2347
           ?T("_`srg_create`_ API:"),
2348
           ?T("If you want to put a group Name with blank spaces, use the "
2349
              "characters '\"\'' and '\'\"' to define when the Name starts and "
2350
              "ends. See an example below.")],
2351
      example =>
2352
          [{?T("With this configuration, vCards can only be modified with "
2353
               "mod_admin_extra commands:"),
2354
            ["acl:",
2355
             "  adminextraresource:",
2356
             "    - resource: \"modadminextraf8x,31ad\"",
2357
             "access_rules:",
2358
             "  vcard_set:",
2359
             "    - allow: adminextraresource",
2360
             "modules:",
2361
             "  mod_admin_extra: {}",
2362
             "  mod_vcard:",
2363
             "    access_set: vcard_set"]},
2364
           {?T("Content of roster file for _`push_roster`_ API:"),
2365
            ["[{<<\"bob\">>, <<\"example.org\">>, <<\"workers\">>, <<\"Bob\">>},",
2366
             "{<<\"mart\">>, <<\"example.org\">>, <<\"workers\">>, <<\"Mart\">>},",
2367
             "{<<\"Rich\">>, <<\"example.org\">>, <<\"bosses\">>, <<\"Rich\">>}]."]},
2368
           {?T("With this call, the sessions of the local account which JID is "
2369
              "'boby@example.org' will be kicked, and its password will be set "
2370
              "to something like "
2371
              "'BANNED_ACCOUNT--20080425T21:45:07--2176635--Spammed_rooms'"),
2372
            ["ejabberdctl vhost example.org ban_account boby \"Spammed rooms\""]},
2373
           {?T("Call to _`srg_create`_ API using double-quotes and single-quotes:"),
2374
            ["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