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

processone / ejabberd / 857

05 Dec 2024 12:03PM UTC coverage: 32.926% (+0.03%) from 32.901%
857

push

github

badlop
Redis: Disable some dialyzer warnings when using old Erlang 20

14604 of 44354 relevant lines covered (32.93%)

619.76 hits per line

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

10.05
/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-2024   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/1, connected_users_info/0,
47
         connected_users_vhost/1, set_presence/7,
48
         get_presence/2, user_sessions_info/2, get_last/2, set_last/4,
49

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

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

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

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

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

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

79
         % Privacy list
80
         privacy_set/3,
81

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

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

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

102
%%%
103
%%% gen_mod
104
%%%
105

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

119
stop(Host) ->
120
    case gen_mod:is_loaded_elsewhere(Host, ?MODULE) of
3✔
121
        false ->
122
            ejabberd_commands:unregister_commands(get_commands_spec());
1✔
123
        true ->
124
            ok
2✔
125
    end.
126

127
reload(_Host, _NewOpts, _OldOpts) ->
128
    ok.
×
129

130
depends(_Host, _Opts) ->
131
    [].
6✔
132

133
%%%
134
%%% Register commands
135
%%%
136

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

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

159
    VcardXEP = "For a full list of vCard fields check [XEP-0054: vcard-temp]"
4✔
160
        "(https://xmpp.org/extensions/xep-0054.html)",
161

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

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

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

423
     #ejabberd_commands{name = connected_users_vhost,
424
                        tags = [session],
425
                        desc = "Get the list of established sessions in a vhost",
426
                        module = ?MODULE, function = connected_users_vhost,
427
                        args_example = [<<"myexample.com">>],
428
                        args_desc = ["Server name"],
429
                        result_example = [<<"user1@myserver.com/tka">>, <<"user2@localhost/tka">>],
430
                        args = [{host, binary}],
431
                        result = {connected_users_vhost, {list, {sessions, string}}}},
432
     #ejabberd_commands{name = user_sessions_info,
433
                        tags = [session],
434
                        desc = "Get information about all sessions of a user",
435
                        module = ?MODULE, function = user_sessions_info,
436
                        args = [{user, binary}, {host, binary}],
437
                        args_example = [<<"peter">>, <<"myserver.com">>],
438
                        args_desc = ["User name", "Server name"],
439
                        result_example = [{"c2s", "127.0.0.1", 42656,8, "ejabberd@localhost",
440
                                           231, <<"dnd">>, <<"tka">>, <<>>}],
441
                        result = {sessions_info,
442
                                  {list,
443
                                   {session, {tuple,
444
                                              [{connection, string},
445
                                               {ip, string},
446
                                               {port, integer},
447
                                               {priority, integer},
448
                                               {node, string},
449
                                               {uptime, integer},
450
                                               {status, string},
451
                                               {resource, string},
452
                                               {statustext, string}
453
                                              ]}}
454
                                  }}},
455

456
     #ejabberd_commands{name = get_presence, tags = [session],
457
                        desc =
458
                            "Retrieve the resource with highest priority, "
459
                            "and its presence (show and status message) "
460
                            "for a given user.",
461
                        longdesc =
462
                            "The `jid` value contains the user JID "
463
                            "with resource.\n\nThe `show` value contains "
464
                            "the user presence flag. It can take "
465
                            "limited values:\n\n - `available`\n - `chat` "
466
                            "(Free for chat)\n - `away`\n - `dnd` (Do "
467
                            "not disturb)\n - `xa` (Not available, "
468
                            "extended away)\n - `unavailable` (Not "
469
                            "connected)\n\n`status` is a free text "
470
                            "defined by the user client.",
471
                        module = ?MODULE, function = get_presence,
472
                        args = [{user, binary}, {host, binary}],
473
                        args_rename = [{server, host}],
474
                        args_example = [<<"peter">>, <<"myexample.com">>],
475
                        args_desc = ["User name", "Server name"],
476
                        result_example = {<<"user1@myserver.com/tka">>, <<"dnd">>, <<"Busy">>},
477
                        result =
478
                            {presence,
479
                             {tuple,
480
                              [{jid, string}, {show, string},
481
                               {status, string}]}}},
482
     #ejabberd_commands{name = set_presence,
483
                        tags = [session],
484
                        desc = "Set presence of a session",
485
                        module = ?MODULE, function = set_presence,
486
                        args = [{user, binary}, {host, binary},
487
                                {resource, binary}, {type, binary},
488
                                {show, binary}, {status, binary},
489
                                {priority, binary}],
490
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"tka1">>,
491
                                        <<"available">>,<<"away">>,<<"BB">>, <<"7">>],
492
                        args_desc = ["User name", "Server name", "Resource",
493
                                        "Type: `available`, `error`, `probe`...",
494
                                        "Show: `away`, `chat`, `dnd`, `xa`.", "Status text",
495
                                        "Priority, provide this value as an integer"],
496
                        result = {res, rescode}},
497
     #ejabberd_commands{name = set_presence,
498
                        tags = [session],
499
                        desc = "Set presence of a session",
500
                        module = ?MODULE, function = set_presence,
501
                        version = 1,
502
                        note = "updated in 24.02",
503
                        args = [{user, binary}, {host, binary},
504
                                {resource, binary}, {type, binary},
505
                                {show, binary}, {status, binary},
506
                                {priority, integer}],
507
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"tka1">>,
508
                                        <<"available">>,<<"away">>,<<"BB">>, 7],
509
                        args_desc = ["User name", "Server name", "Resource",
510
                                        "Type: `available`, `error`, `probe`...",
511
                                        "Show: `away`, `chat`, `dnd`, `xa`.", "Status text",
512
                                        "Priority, provide this value as an integer"],
513
                        result = {res, rescode}},
514

515
     #ejabberd_commands{name = set_nickname, tags = [vcard],
516
                        desc = "Set nickname in a user's vCard",
517
                        module = ?MODULE, function = set_nickname,
518
                        args = [{user, binary}, {host, binary}, {nickname, binary}],
519
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"User 1">>],
520
                        args_desc = ["User name", "Server name", "Nickname"],
521
                        result = {res, rescode}},
522
     #ejabberd_commands{name = get_vcard, tags = [vcard],
523
                        desc = "Get content from a vCard field",
524
                        longdesc = Vcard1FieldsString ++ "\n" ++ VcardXEP,
525
                        module = ?MODULE, function = get_vcard,
526
                        args = [{user, binary}, {host, binary}, {name, binary}],
527
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"NICKNAME">>],
528
                        args_desc = ["User name", "Server name", "Field name"],
529
                        result_example = "User 1",
530
                        result_desc = "Field content",
531
                        result = {content, string}},
532
     #ejabberd_commands{name = get_vcard2, tags = [vcard],
533
                        desc = "Get content from a vCard subfield",
534
                        longdesc = Vcard2FieldsString ++ "\n" ++ VcardXEP,
535
                        module = ?MODULE, function = get_vcard,
536
                        args = [{user, binary}, {host, binary}, {name, binary}, {subname, binary}],
537
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"N">>, <<"FAMILY">>],
538
                        args_desc = ["User name", "Server name", "Field name", "Subfield name"],
539
                        result_example = "Schubert",
540
                        result_desc = "Field content",
541
                        result = {content, string}},
542
     #ejabberd_commands{name = get_vcard2_multi, tags = [vcard],
543
                        desc = "Get multiple contents from a vCard field",
544
                        longdesc = Vcard2FieldsString ++ "\n" ++ VcardXEP,
545
                        module = ?MODULE, function = get_vcard_multi,
546
                        args = [{user, binary}, {host, binary}, {name, binary}, {subname, binary}],
547
                        result = {contents, {list, {value, string}}}},
548

549
     #ejabberd_commands{name = set_vcard, tags = [vcard],
550
                        desc = "Set content in a vCard field",
551
                        longdesc = Vcard1FieldsString ++ "\n" ++ VcardXEP,
552
                        module = ?MODULE, function = set_vcard,
553
                        args = [{user, binary}, {host, binary}, {name, binary}, {content, binary}],
554
                        args_example = [<<"user1">>,<<"myserver.com">>, <<"URL">>, <<"www.example.com">>],
555
                        args_desc = ["User name", "Server name", "Field name", "Value"],
556
                        result = {res, rescode}},
557
     #ejabberd_commands{name = set_vcard2, tags = [vcard],
558
                        desc = "Set content in a vCard subfield",
559
                        longdesc = Vcard2FieldsString ++ "\n" ++ VcardXEP,
560
                        module = ?MODULE, function = set_vcard,
561
                        args = [{user, binary}, {host, binary}, {name, binary}, {subname, binary}, {content, binary}],
562
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"TEL">>, <<"NUMBER">>, <<"123456">>],
563
                        args_desc = ["User name", "Server name", "Field name", "Subfield name", "Value"],
564
                        result = {res, rescode}},
565
     #ejabberd_commands{name = set_vcard2_multi, tags = [vcard],
566
                        desc = "Set multiple contents in a vCard subfield",
567
                        longdesc = Vcard2FieldsString ++ "\n" ++ VcardXEP,
568
                        module = ?MODULE, function = set_vcard,
569
                        args = [{user, binary}, {host, binary}, {name, binary}, {subname, binary}, {contents, {list, {value, binary}}}],
570
                        result = {res, rescode}},
571

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

736
     #ejabberd_commands{name = get_last, tags = [last],
737
                        desc = "Get last activity information",
738
                        longdesc = "Timestamp is UTC and "
739
                            "[XEP-0082](https://xmpp.org/extensions/xep-0082.html)"
740
                            " format, for example: "
741
                            "`2017-02-23T22:25:28.063062Z     ONLINE`",
742
                        module = ?MODULE, function = get_last,
743
                        args = [{user, binary}, {host, binary}],
744
                        args_example = [<<"user1">>,<<"myserver.com">>],
745
                        args_desc = ["User name", "Server name"],
746
                        result_example = {<<"2017-06-30T14:32:16.060684Z">>, "ONLINE"},
747
                        result_desc = "Last activity timestamp and status",
748
                        result = {last_activity,
749
                                  {tuple, [{timestamp, string},
750
                                           {status, string}
751
                                          ]}}},
752
     #ejabberd_commands{name = set_last, tags = [last],
753
                        desc = "Set last activity information",
754
                        longdesc = "Timestamp is the seconds since "
755
                        "`1970-01-01 00:00:00 UTC`. For example value see `date +%s`",
756
                        module = ?MODULE, function = set_last,
757
                        args = [{user, binary}, {host, binary}, {timestamp, integer}, {status, binary}],
758
                        args_example = [<<"user1">>,<<"myserver.com">>, 1500045311, <<"GoSleeping">>],
759
                        args_desc = ["User name", "Server name", "Number of seconds since epoch", "Status message"],
760
                        result = {res, rescode}},
761

762
     #ejabberd_commands{name = private_get, tags = [private],
763
                        desc = "Get some information from a user private storage",
764
                        module = ?MODULE, function = private_get,
765
                        args = [{user, binary}, {host, binary}, {element, binary}, {ns, binary}],
766
                        args_example = [<<"user1">>,<<"myserver.com">>,<<"storage">>, <<"storage:rosternotes">>],
767
                        args_desc = ["User name", "Server name", "Element name", "Namespace"],
768
                        result = {res, string}},
769
     #ejabberd_commands{name = private_set, tags = [private],
770
                        desc = "Set to the user private storage",
771
                        module = ?MODULE, function = private_set,
772
                        args = [{user, binary}, {host, binary}, {element, binary}],
773
                        args_example = [<<"user1">>,<<"myserver.com">>,
774
                            <<"<storage xmlns='storage:rosternotes'/>">>],
775
                        args_desc = ["User name", "Server name", "XML storage element"],
776
                        result = {res, rescode}},
777

778
     #ejabberd_commands{name = srg_create, tags = [shared_roster_group],
779
                        desc = "Create a Shared Roster Group",
780
                        longdesc = "If you want to specify several group "
781
                        "identifiers in the Display argument,\n"
782
                        "put `\\ \"` around the argument and\nseparate the "
783
                        "identifiers with `\\ \\ n`\n"
784
                        "For example:\n"
785
                        "  `ejabberdctl srg_create group3 myserver.com "
786
                        "name desc \\\"group1\\\\ngroup2\\\"`",
787
                        note = "changed in 21.07",
788
                        module = ?MODULE, function = srg_create,
789
                        args = [{group, binary}, {host, binary},
790
                                {label, binary}, {description, binary}, {display, binary}],
791
                        args_rename = [{name, label}],
792
                        args_example = [<<"group3">>, <<"myserver.com">>, <<"Group3">>,
793
                                <<"Third group">>, <<"group1\\\\ngroup2">>],
794
                        args_desc = ["Group identifier", "Group server name", "Group name",
795
                                "Group description", "Groups to display"],
796
                        result = {res, rescode}},
797
     #ejabberd_commands{name = srg_create, tags = [shared_roster_group],
798
                        desc = "Create a Shared Roster Group",
799
                        module = ?MODULE, function = srg_create,
800
                        version = 1,
801
                        note = "updated in 24.02",
802
                        args = [{group, binary}, {host, binary},
803
                                {label, binary}, {description, binary}, {display, {list, {group, binary}}}],
804
                        args_rename = [{name, label}],
805
                        args_example = [<<"group3">>, <<"myserver.com">>, <<"Group3">>,
806
                                <<"Third group">>, [<<"group1">>, <<"group2">>]],
807
                        args_desc = ["Group identifier", "Group server name", "Group name",
808
                                "Group description", "List of groups to display"],
809
                        result = {res, rescode}},
810
     #ejabberd_commands{name = srg_add, tags = [shared_roster_group],
811
                        desc = "Add/Create a Shared Roster Group (without details)",
812
                        module = ?MODULE, function = srg_add,
813
                        note = "added in 24.06",
814
                        args = [{group, binary}, {host, binary}],
815
                        args_example = [<<"group3">>, <<"myserver.com">>],
816
                        args_desc = ["Group identifier", "Group server name"],
817
                        result = {res, rescode}},
818
     #ejabberd_commands{name = srg_delete, tags = [shared_roster_group],
819
                        desc = "Delete a Shared Roster Group",
820
                        module = ?MODULE, function = srg_delete,
821
                        args = [{group, binary}, {host, binary}],
822
                        args_example = [<<"group3">>, <<"myserver.com">>],
823
                        args_desc = ["Group identifier", "Group server name"],
824
                        result = {res, rescode}},
825
     #ejabberd_commands{name = srg_list, tags = [shared_roster_group],
826
                        desc = "List the Shared Roster Groups in Host",
827
                        module = ?MODULE, function = srg_list,
828
                        args = [{host, binary}],
829
                        args_example = [<<"myserver.com">>],
830
                        args_desc = ["Server name"],
831
                        result_example = [<<"group1">>, <<"group2">>],
832
                        result_desc = "List of group identifiers",
833
                        result = {groups, {list, {id, string}}}},
834
     #ejabberd_commands{name = srg_get_info, tags = [shared_roster_group],
835
                        desc = "Get info of a Shared Roster Group",
836
                        module = ?MODULE, function = srg_get_info,
837
                        args = [{group, binary}, {host, binary}],
838
                        args_example = [<<"group3">>, <<"myserver.com">>],
839
                        args_desc = ["Group identifier", "Group server name"],
840
                        result_example = [{<<"name">>, "Group 3"}, {<<"displayed_groups">>, "group1"}],
841
                        result_desc = "List of group information, as key and value",
842
                        result = {informations, {list, {information, {tuple, [{key, string}, {value, string}]}}}}},
843
     #ejabberd_commands{name = srg_set_info, tags = [shared_roster_group],
844
                        desc = "Set info of a Shared Roster Group",
845
                        module = ?MODULE, function = srg_set_info,
846
                        note = "added in 24.06",
847
                        args = [{group, binary}, {host, binary}, {key, binary}, {value, binary}],
848
                        args_example = [<<"group3">>, <<"myserver.com">>, <<"label">>, <<"Family">>],
849
                        args_desc = ["Group identifier", "Group server name",
850
                                     "Information key: label, description",
851
                                     "Information value"],
852
                        result = {res, rescode}},
853

854
     #ejabberd_commands{name = srg_get_displayed, tags = [shared_roster_group],
855
                        desc = "Get displayed groups of a Shared Roster Group",
856
                        module = ?MODULE, function = srg_get_displayed,
857
                        note = "added in 24.06",
858
                        args = [{group, binary}, {host, binary}],
859
                        args_example = [<<"group3">>, <<"myserver.com">>],
860
                        args_desc = ["Group identifier", "Group server name"],
861
                        result_example = [<<"group1">>, <<"group2">>],
862
                        result_desc = "List of groups to display",
863
                        result = {display, {list, {group, binary}}}},
864
     #ejabberd_commands{name = srg_add_displayed, tags = [shared_roster_group],
865
                        desc = "Add a group to displayed_groups of a Shared Roster Group",
866
                        module = ?MODULE, function = srg_add_displayed,
867
                        note = "added in 24.06",
868
                        args = [{group, binary}, {host, binary},
869
                                {add, binary}],
870
                        args_example = [<<"group3">>, <<"myserver.com">>, <<"group1">>],
871
                        args_desc = ["Group identifier", "Group server name",
872
                                "Group to add to displayed_groups"],
873
                        result = {res, rescode}},
874
     #ejabberd_commands{name = srg_del_displayed, tags = [shared_roster_group],
875
                        desc = "Delete a group from displayed_groups of a Shared Roster Group",
876
                        module = ?MODULE, function = srg_del_displayed,
877
                        note = "added in 24.06",
878
                        args = [{group, binary}, {host, binary},
879
                                {del, binary}],
880
                        args_example = [<<"group3">>, <<"myserver.com">>, <<"group1">>],
881
                        args_desc = ["Group identifier", "Group server name",
882
                                "Group to delete from displayed_groups"],
883
                        result = {res, rescode}},
884

885
     #ejabberd_commands{name = srg_get_members, tags = [shared_roster_group],
886
                        desc = "Get members of a Shared Roster Group",
887
                        module = ?MODULE, function = srg_get_members,
888
                        args = [{group, binary}, {host, binary}],
889
                        args_example = [<<"group3">>, <<"myserver.com">>],
890
                        args_desc = ["Group identifier", "Group server name"],
891
                        result_example = [<<"user1@localhost">>, <<"user2@localhost">>],
892
                        result_desc = "List of group identifiers",
893
                        result = {members, {list, {member, string}}}},
894
     #ejabberd_commands{name = srg_user_add, tags = [shared_roster_group],
895
                        desc = "Add the JID user@host to the Shared Roster Group",
896
                        module = ?MODULE, function = srg_user_add,
897
                        args = [{user, binary}, {host, binary}, {group, binary}, {grouphost, binary}],
898
                        args_example = [<<"user1">>, <<"myserver.com">>, <<"group3">>, <<"myserver.com">>],
899
                        args_desc = ["Username", "User server name", "Group identifier", "Group server name"],
900
                        result = {res, rescode}},
901
     #ejabberd_commands{name = srg_user_del, tags = [shared_roster_group],
902
                        desc = "Delete this JID user@host from the Shared Roster Group",
903
                        module = ?MODULE, function = srg_user_del,
904
                        args = [{user, binary}, {host, binary}, {group, binary}, {grouphost, binary}],
905
                        args_example = [<<"user1">>, <<"myserver.com">>, <<"group3">>, <<"myserver.com">>],
906
                        args_desc = ["Username", "User server name", "Group identifier", "Group server name"],
907
                        result = {res, rescode}},
908

909
     #ejabberd_commands{name = get_offline_count,
910
                        tags = [offline],
911
                        desc = "Get the number of unread offline messages",
912
                        policy = user,
913
                        module = mod_offline, function = count_offline_messages,
914
                        args = [],
915
                        args_rename = [{server, host}],
916
                        result_example = 5,
917
                        result_desc = "Number",
918
                        result = {value, integer}},
919
     #ejabberd_commands{name = get_offline_messages,
920
                        tags = [internal, offline],
921
                        desc = "Get the offline messages",
922
                        policy = user,
923
                        module = mod_offline, function = get_offline_messages,
924
                        args = [],
925
                        result = {queue, {list, {messages, {tuple, [{time, string},
926
                                                                    {from, string},
927
                                                                    {to, string},
928
                                                                    {packet, string}
929
                                                                   ]}}}}},
930

931
     #ejabberd_commands{name = send_message, tags = [stanza],
932
                        desc = "Send a message to a local or remote bare of full JID",
933
                        longdesc = "When sending a groupchat message to a MUC room, "
934
                        "`from` must be the full JID of a room occupant, "
935
                        "or the bare JID of a MUC service admin, "
936
                        "or the bare JID of a MUC/Sub subscribed user.",
937
                        module = ?MODULE, function = send_message,
938
                        args = [{type, binary}, {from, binary}, {to, binary},
939
                                {subject, binary}, {body, binary}],
940
                        args_example = [<<"headline">>, <<"admin@localhost">>, <<"user1@localhost">>,
941
                                <<"Restart">>, <<"In 5 minutes">>],
942
                        args_desc = ["Message type: `normal`, `chat`, `headline`, `groupchat`", "Sender JID",
943
                                "Receiver JID", "Subject, or empty string", "Body"],
944
                        result = {res, rescode}},
945
     #ejabberd_commands{name = send_stanza_c2s, tags = [stanza],
946
                        desc = "Send a stanza from an existing C2S session",
947
                        longdesc = "`user`@`host`/`resource` must be an existing C2S session."
948
                        " As an alternative, use _`send_stanza`_ API instead.",
949
                        module = ?MODULE, function = send_stanza_c2s,
950
                        args = [{user, binary}, {host, binary}, {resource, binary}, {stanza, binary}],
951
                        args_example = [<<"admin">>, <<"myserver.com">>, <<"bot">>,
952
                                <<"<message to='user1@localhost'><ext attr='value'/></message>">>],
953
                        args_desc = ["Username", "Server name", "Resource", "Stanza"],
954
                        result = {res, rescode}},
955
     #ejabberd_commands{name = send_stanza, tags = [stanza],
956
                        desc = "Send a stanza; provide From JID and valid To JID",
957
                        module = ?MODULE, function = send_stanza,
958
                        args = [{from, binary}, {to, binary}, {stanza, binary}],
959
                        args_example = [<<"admin@localhost">>, <<"user1@localhost">>,
960
                                <<"<message><ext attr='value'/></message>">>],
961
                        args_desc = ["Sender JID", "Destination JID", "Stanza"],
962
                        result = {res, rescode}},
963
     #ejabberd_commands{name = privacy_set, tags = [stanza],
964
                        desc = "Send a IQ set privacy stanza for a local account",
965
                        module = ?MODULE, function = privacy_set,
966
                        args = [{user, binary}, {host, binary}, {xmlquery, binary}],
967
                        args_example = [<<"user1">>, <<"myserver.com">>,
968
                                <<"<query xmlns='jabber:iq:privacy'>...">>],
969
                        args_desc = ["Username", "Server name", "Query XML element"],
970
                        result = {res, rescode}},
971

972
     #ejabberd_commands{name = stats, tags = [statistics],
973
                        desc = "Get some statistical value for the whole ejabberd server",
974
                        longdesc = "Allowed statistics `name` are: `registeredusers`, "
975
                            "`onlineusers`, `onlineusersnode`, `uptimeseconds`, `processes`.",
976
                        policy = admin,
977
                        module = ?MODULE, function = stats,
978
                        args = [{name, binary}],
979
                        args_example = [<<"registeredusers">>],
980
                        args_desc = ["Statistic name"],
981
                        result_example = 6,
982
                        result_desc = "Integer statistic value",
983
                        result = {stat, integer}},
984
     #ejabberd_commands{name = stats_host, tags = [statistics],
985
                        desc = "Get some statistical value for this host",
986
                        longdesc = "Allowed statistics `name` are: `registeredusers`, `onlineusers`.",
987
                        policy = admin,
988
                        module = ?MODULE, function = stats,
989
                        args = [{name, binary}, {host, binary}],
990
                        args_example = [<<"registeredusers">>, <<"example.com">>],
991
                        args_desc = ["Statistic name", "Server JID"],
992
                        result_example = 6,
993
                        result_desc = "Integer statistic value",
994
                        result = {stat, integer}}
995
    ].
996

997

998
%%%
999
%%% Adminsys
1000
%%%
1001

1002
compile(File) ->
1003
    Ebin = filename:join(code:lib_dir(ejabberd), "ebin"),
×
1004
    case ext_mod:compile_erlang_file(Ebin, File) of
×
1005
        {ok, Module} ->
1006
            code:purge(Module),
×
1007
            code:load_file(Module),
×
1008
            ok;
×
1009
        _ ->
1010
            error
×
1011
    end.
1012

1013
get_cookie() ->
1014
    atom_to_list(erlang:get_cookie()).
×
1015

1016
restart_module(Host, Module) when is_binary(Module) ->
1017
    restart_module(Host, misc:binary_to_atom(Module));
×
1018
restart_module(Host, Module) when is_atom(Module) ->
1019
    case gen_mod:is_loaded(Host, Module) of
×
1020
        false ->
1021
            % not a running module, force code reload anyway
1022
            code:purge(Module),
×
1023
            code:delete(Module),
×
1024
            code:load_file(Module),
×
1025
            1;
×
1026
        true ->
1027
            gen_mod:stop_module(Host, Module),
×
1028
            case code:soft_purge(Module) of
×
1029
                true ->
1030
                    code:delete(Module),
×
1031
                    code:load_file(Module),
×
1032
                    gen_mod:start_module(Host, Module),
×
1033
                    0;
×
1034
                false ->
1035
                    gen_mod:start_module(Host, Module),
×
1036
                    2
×
1037
            end
1038
    end.
1039

1040
%%%
1041
%%% Accounts
1042
%%%
1043

1044
set_password(User, Host, Password) ->
1045
    Fun = fun () -> ejabberd_auth:set_password(User, Host, Password) end,
5✔
1046
    user_action(User, Host, Fun, ok).
5✔
1047

1048
check_password(User, Host, Password) ->
1049
    ejabberd_auth:check_password(User, <<>>, Host, Password).
×
1050

1051
%% Copied some code from ejabberd_commands.erln
1052
check_password_hash(User, Host, PasswordHash, HashMethod) ->
1053
    AccountPass = ejabberd_auth:get_password_s(User, Host),
×
1054
    Methods = lists:map(fun(A) -> atom_to_binary(A, latin1) end,
×
1055
                   proplists:get_value(hashs, crypto:supports())),
1056
    MethodAllowed = lists:member(HashMethod, Methods),
×
1057
    AccountPassHash = case {AccountPass, MethodAllowed} of
×
1058
                          {A, _} when is_tuple(A) -> scrammed;
×
1059
                          {_, true} -> get_hash(AccountPass, HashMethod);
×
1060
                          {_, false} ->
1061
                              ?ERROR_MSG("Check_password_hash called "
×
1062
                                         "with hash method: ~p", [HashMethod]),
×
1063
                              undefined
×
1064
                      end,
1065
    case AccountPassHash of
×
1066
        scrammed ->
1067
            ?ERROR_MSG("Passwords are scrammed, and check_password_hash cannot work.", []),
×
1068
            throw(passwords_scrammed_command_cannot_work);
×
1069
        undefined -> throw(unkown_hash_method);
×
1070
        PasswordHash -> ok;
×
1071
        _ -> false
×
1072
    end.
1073

1074
get_hash(AccountPass, Method) ->
1075
    iolist_to_binary([io_lib:format("~2.16.0B", [X])
×
1076
          || X <- binary_to_list(
×
1077
              crypto:hash(binary_to_atom(Method, latin1), AccountPass))]).
1078

1079
delete_old_users(Days) ->
1080
    %% Get the list of registered users
1081
    Users = ejabberd_auth:get_users(),
1✔
1082

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

1086
delete_old_users_vhost(Host, Days) ->
1087
    %% Get the list of registered users
1088
    Users = ejabberd_auth:get_users(Host),
×
1089

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

1093
delete_old_users(Days, Users) ->
1094
    SecOlder = Days*24*60*60,
1✔
1095
    TimeStamp_now = erlang:system_time(second),
1✔
1096
    TimeStamp_oldest = TimeStamp_now - SecOlder,
1✔
1097
    F = fun({LUser, LServer}) ->
1✔
1098
            case catch delete_or_not(LUser, LServer, TimeStamp_oldest) of
6✔
1099
                true ->
1100
                    ejabberd_auth:remove_user(LUser, LServer),
×
1101
                    true;
×
1102
                _ ->
1103
                    false
6✔
1104
            end
1105
        end,
1106
    Users_removed = lists:filter(F, Users),
1✔
1107
    {removed, length(Users_removed), Users_removed}.
1✔
1108

1109
delete_or_not(LUser, LServer, TimeStamp_oldest) ->
1110
    deny = acl:match_rule(LServer, protect_old_users, jid:make(LUser, LServer)),
6✔
1111
    [] = ejabberd_sm:get_user_resources(LUser, LServer),
6✔
1112
    case mod_last:get_last_info(LUser, LServer) of
4✔
1113
        {ok, TimeStamp, _Status} ->
1114
            if TimeStamp_oldest < TimeStamp ->
×
1115
                    false;
×
1116
                true ->
1117
                    true
×
1118
            end;
1119
        not_found ->
1120
            true
×
1121
    end.
1122

1123
%%
1124
%% Ban account v0
1125

1126
ban_account(User, Host, ReasonText) ->
1127
    Reason = prepare_reason(ReasonText),
×
1128
    kick_sessions(User, Host, Reason),
×
1129
    set_random_password(User, Host, Reason),
×
1130
    ok.
×
1131

1132
kick_sessions(User, Server, Reason) ->
1133
    lists:map(
×
1134
      fun(Resource) ->
1135
              kick_this_session(User, Server, Resource, Reason)
×
1136
      end,
1137
      ejabberd_sm:get_user_resources(User, Server)).
1138

1139
set_random_password(User, Server, Reason) ->
1140
    NewPass = build_random_password(Reason),
×
1141
    set_password_auth(User, Server, NewPass).
×
1142

1143
build_random_password(Reason) ->
1144
    {{Year, Month, Day}, {Hour, Minute, Second}} = calendar:universal_time(),
×
1145
    Date = str:format("~4..0B~2..0B~2..0BT~2..0B:~2..0B:~2..0B",
×
1146
                      [Year, Month, Day, Hour, Minute, Second]),
1147
    RandomString = p1_rand:get_string(),
×
1148
    <<"BANNED_ACCOUNT--", Date/binary, "--", RandomString/binary, "--", Reason/binary>>.
×
1149

1150
set_password_auth(User, Server, Password) ->
1151
    ok = ejabberd_auth:set_password(User, Server, Password).
×
1152

1153
prepare_reason([]) ->
1154
    <<"Kicked by administrator">>;
×
1155
prepare_reason([Reason]) ->
1156
    Reason;
×
1157
prepare_reason(Reason) when is_binary(Reason) ->
1158
    Reason.
×
1159

1160
%%
1161
%% Ban account v2
1162

1163
ban_account_v2(User, Host, ReasonText) ->
1164
    case gen_mod:is_loaded(Host, mod_private) of
×
1165
        false ->
1166
            mod_private_is_required_but_disabled;
×
1167
        true ->
1168
            case is_banned(User, Host) of
×
1169
                true ->
1170
                    account_was_already_banned;
×
1171
                false ->
1172
                    ban_account_v2_b(User, Host, ReasonText)
×
1173
            end
1174
    end.
1175

1176
ban_account_v2_b(User, Host, ReasonText) ->
1177
    Reason = prepare_reason(ReasonText),
×
1178
    Pass = ejabberd_auth:get_password_s(User, Host),
×
1179
    Last = get_last(User, Host),
×
1180
    BanDate = xmpp_util:encode_timestamp(erlang:timestamp()),
×
1181
    Hash = get_hash_value(User, Host),
×
1182
    BanPrivateXml = build_ban_xmlel(Reason, Pass, Last, BanDate, Hash),
×
1183
    ok = private_set2(User, Host, BanPrivateXml),
×
1184
    ok = set_random_password_v2(User, Host),
×
1185
    kick_sessions(User, Host, Reason),
×
1186
    ok.
×
1187

1188
get_hash_value(User, Host) ->
1189
    Cookie = misc:atom_to_binary(erlang:get_cookie()),
1,176✔
1190
    misc:term_to_base64(crypto:hash(sha256, <<User/binary, Host/binary, Cookie/binary>>)).
1,176✔
1191

1192
set_random_password_v2(User, Server) ->
1193
    NewPass = p1_rand:get_string(),
×
1194
    ok = ejabberd_auth:set_password(User, Server, NewPass).
×
1195

1196
build_ban_xmlel(Reason, Pass, {LastDate, LastReason}, BanDate, Hash) ->
1197
    PassEls = build_pass_els(Pass),
×
1198
    #xmlel{name = <<"banned">>,
×
1199
           attrs = [{<<"xmlns">>, <<"jabber:ejabberd:banned">>}],
1200
           children = [#xmlel{name = <<"reason">>, attrs = [], children = [{xmlcdata, Reason}]},
1201
                       #xmlel{name = <<"password">>, attrs = [], children = PassEls},
1202
                       #xmlel{name = <<"lastdate">>, attrs = [], children = [{xmlcdata, LastDate}]},
1203
                       #xmlel{name = <<"lastreason">>, attrs = [], children = [{xmlcdata, LastReason}]},
1204
                       #xmlel{name = <<"bandate">>, attrs = [], children = [{xmlcdata, BanDate}]},
1205
                       #xmlel{name = <<"hash">>, attrs = [], children = [{xmlcdata, Hash}]}
1206
                       ]}.
1207

1208
build_pass_els(Pass) when is_binary(Pass) ->
1209
    [{xmlcdata, Pass}];
×
1210
build_pass_els(#scram{storedkey = StoredKey,
1211
                      serverkey = ServerKey,
1212
                      salt = Salt,
1213
                      hash = Hash,
1214
                      iterationcount = IterationCount}) ->
1215
    [#xmlel{name = <<"storedkey">>, attrs = [], children = [{xmlcdata, StoredKey}]},
×
1216
     #xmlel{name = <<"serverkey">>, attrs = [], children = [{xmlcdata, ServerKey}]},
1217
     #xmlel{name = <<"salt">>, attrs = [], children = [{xmlcdata, Salt}]},
1218
     #xmlel{name = <<"hash">>, attrs = [], children = [{xmlcdata, misc:atom_to_binary(Hash)}]},
1219
     #xmlel{name = <<"iterationcount">>, attrs = [], children = [{xmlcdata, integer_to_binary(IterationCount)}]}
1220
    ].
1221

1222
%%
1223
%% Get ban details
1224

1225
get_ban_details(User, Host) ->
1226
    case private_get2(User, Host, <<"banned">>, <<"jabber:ejabberd:banned">>) of
1,306✔
1227
        [El] ->
1228
            get_ban_details(User, Host, El);
1,176✔
1229
        [] ->
1230
            []
130✔
1231
    end.
1232

1233
get_ban_details(User, Host, El) ->
1234
    Reason = fxml:get_subtag_cdata(El, <<"reason">>),
1,176✔
1235
    LastDate = fxml:get_subtag_cdata(El, <<"lastdate">>),
1,176✔
1236
    LastReason = fxml:get_subtag_cdata(El, <<"lastreason">>),
1,176✔
1237
    BanDate = fxml:get_subtag_cdata(El, <<"bandate">>),
1,176✔
1238
    Hash = fxml:get_subtag_cdata(El, <<"hash">>),
1,176✔
1239
    case Hash == get_hash_value(User, Host) of
1,176✔
1240
        true ->
1241
            [{"reason", Reason},
×
1242
             {"bandate", BanDate},
1243
             {"lastdate", LastDate},
1244
             {"lastreason", LastReason}];
1245
        false ->
1246
            []
1,176✔
1247
    end.
1248

1249
is_banned(User, Host) ->
1250
    case lists:keyfind("bandate", 1, get_ban_details(User, Host)) of
×
1251
        {_, BanDate} when BanDate /= <<>> ->
1252
            true;
×
1253
        _ ->
1254
            false
×
1255
    end.
1256

1257
%%
1258
%% Unban account
1259

1260
unban_account(User, Host) ->
1261
    case gen_mod:is_loaded(Host, mod_private) of
×
1262
        false ->
1263
            mod_private_is_required_but_disabled;
×
1264
        true ->
1265
            case is_banned(User, Host) of
×
1266
                false ->
1267
                    account_was_not_banned;
×
1268
                true ->
1269
                    unban_account2(User, Host)
×
1270
            end
1271
    end.
1272

1273
unban_account2(User, Host) ->
1274
    OldPass = get_oldpass(User, Host),
×
1275
    ok = ejabberd_auth:set_password(User, Host, OldPass),
×
1276
    UnBanPrivateXml = build_unban_xmlel(),
×
1277
    private_set2(User, Host, UnBanPrivateXml).
×
1278

1279
get_oldpass(User, Host) ->
1280
    [El] = private_get2(User, Host, <<"banned">>, <<"jabber:ejabberd:banned">>),
×
1281
    Pass = fxml:get_subtag(El, <<"password">>),
×
1282
    get_pass(Pass).
×
1283

1284
get_pass(#xmlel{children = [{xmlcdata, Pass}]}) ->
1285
    Pass;
×
1286
get_pass(#xmlel{children = ScramEls} = Pass) when is_list(ScramEls) ->
1287
    StoredKey = fxml:get_subtag_cdata(Pass, <<"storedkey">>),
×
1288
    ServerKey = fxml:get_subtag_cdata(Pass, <<"serverkey">>),
×
1289
    Salt = fxml:get_subtag_cdata(Pass, <<"salt">>),
×
1290
    Hash = fxml:get_subtag_cdata(Pass, <<"hash">>),
×
1291
    IterationCount = fxml:get_subtag_cdata(Pass, <<"iterationcount">>),
×
1292
    #scram{storedkey = StoredKey,
×
1293
           serverkey = ServerKey,
1294
           salt = Salt,
1295
           hash = binary_to_existing_atom(Hash, latin1),
1296
           iterationcount = binary_to_integer(IterationCount)}.
1297

1298
build_unban_xmlel() ->
1299
    #xmlel{name = <<"banned">>, attrs = [{<<"xmlns">>, <<"jabber:ejabberd:banned">>}]}.
×
1300

1301
%%%
1302
%%% Sessions
1303
%%%
1304

1305
num_resources(User, Host) ->
1306
    length(ejabberd_sm:get_user_resources(User, Host)).
×
1307

1308
resource_num(User, Host, Num) ->
1309
    Resources = ejabberd_sm:get_user_resources(User, Host),
×
1310
    case (0<Num) and (Num=<length(Resources)) of
×
1311
        true ->
1312
            lists:nth(Num, Resources);
×
1313
        false ->
1314
            throw({bad_argument,
×
1315
                   lists:flatten(io_lib:format("Wrong resource number: ~p", [Num]))})
1316
    end.
1317

1318
kick_session(User, Server, Resource, ReasonText) ->
1319
    kick_this_session(User, Server, Resource, prepare_reason(ReasonText)),
×
1320
    ok.
×
1321

1322
kick_this_session(User, Server, Resource, Reason) ->
1323
    ejabberd_sm:route(jid:make(User, Server, Resource),
×
1324
                      {exit, Reason}).
1325

1326
status_num(Host, Status) ->
1327
    length(get_status_list(Host, Status)).
×
1328
status_num(Status) ->
1329
    status_num(<<"all">>, Status).
×
1330
status_list(Host, Status) ->
1331
    Res = get_status_list(Host, Status),
×
1332
    [{U, S, R, num_prio(P), St} || {U, S, R, P, St} <- Res].
×
1333
status_list(Status) ->
1334
    status_list(<<"all">>, Status).
×
1335

1336

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

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

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

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

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

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

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

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

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

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

1460

1461
%%%
1462
%%% Vcard
1463
%%%
1464

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

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

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

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

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

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

1491
%%
1492
%% Room vcard
1493

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

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

1515
%%
1516
%% Internal vcard
1517

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

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

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

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

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

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

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

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

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

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

1614

1615
%%%
1616
%%% Roster
1617
%%%
1618

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

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

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

1660
%% -----------------------------
1661
%% Get Roster
1662
%% -----------------------------
1663

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1779
%%%
1780
%%% Last Activity
1781
%%%
1782

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

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

1803
%%%
1804
%%% Private Storage
1805
%%%
1806

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

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

1816
private_get2(Username, Host, Element, Ns) ->
1817
    case gen_mod:is_loaded(Host, mod_private) of
1,306✔
1818
        true -> private_get3(Username, Host, Element, Ns);
1,176✔
1819
        false -> []
130✔
1820
    end.
1821

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

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

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

1842
%%%
1843
%%% Shared Roster Groups
1844
%%%
1845

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

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

1862
srg_create2(Group, Host, Label, Description, DisplayList) ->
1863
    Opts = [{label, Label},
×
1864
            {displayed_groups, DisplayList},
1865
            {description, Description}],
1866
    {atomic, _} = mod_shared_roster:create_group(Host, Group, Opts),
×
1867
    ok.
×
1868

1869
srg_add(Group, Host) ->
1870
    Opts = [{label, <<"">>},
×
1871
            {description, <<"">>},
1872
            {displayed_groups, []}
1873
           ],
1874
    {atomic, _} = mod_shared_roster:create_group(Host, Group, Opts),
×
1875
    ok.
×
1876

1877
srg_delete(Group, Host) ->
1878
    {atomic, _} = mod_shared_roster:delete_group(Host, Group),
×
1879
    ok.
×
1880

1881
srg_list(Host) ->
1882
    lists:sort(mod_shared_roster:list_groups(Host)).
×
1883

1884
srg_get_info(Group, Host) ->
1885
    Opts = case mod_shared_roster:get_group_opts(Host,Group) of
×
1886
        Os when is_list(Os) -> Os;
×
1887
        error -> []
×
1888
    end,
1889
    [{misc:atom_to_binary(Title), to_list(Value)} || {Title, Value} <- Opts].
×
1890

1891
to_list([]) -> [];
×
1892
to_list([H|_]=List) when is_binary(H) -> lists:join(", ", [to_list(E) || E <- List]);
×
1893
to_list(E) when is_atom(E) -> atom_to_list(E);
×
1894
to_list(E) when is_binary(E) -> binary_to_list(E).
×
1895

1896
%% @format-begin
1897

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

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

1931
srg_get_displayed(Group, Host) ->
1932
    Opts =
×
1933
        case mod_shared_roster:get_group_opts(Host, Group) of
1934
            Os when is_list(Os) ->
1935
                Os;
×
1936
            error ->
1937
                []
×
1938
        end,
1939
    proplists:get_value(displayed_groups, Opts, []).
×
1940

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

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

1991
filter_groups_existence(Host, Groups) ->
1992
    lists:partition(fun(Group) -> error /= mod_shared_roster:get_group_opts(Host, Group) end,
×
1993
                    Groups).
1994
%% @format-end
1995

1996
srg_get_members(Group, Host) ->
1997
    Members = mod_shared_roster:get_group_explicit_users(Host,Group),
×
1998
    [jid:encode(jid:make(MUser, MServer))
×
1999
     || {MUser, MServer} <- Members].
×
2000

2001
srg_user_add(User, Host, Group, GroupHost) ->
2002
    mod_shared_roster:add_user_to_group(GroupHost, {User, Host}, Group),
×
2003
    ok.
×
2004

2005
srg_user_del(User, Host, Group, GroupHost) ->
2006
    mod_shared_roster:remove_user_from_group(GroupHost, {User, Host}, Group),
×
2007
    ok.
×
2008

2009

2010
%%%
2011
%%% Stanza
2012
%%%
2013

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

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

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

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

2099
%%%
2100
%%% Stats
2101
%%%
2102

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

2112
stats(Name, Host) ->
2113
    case Name of
×
2114
        <<"registeredusers">> -> ejabberd_auth:count_users(Host);
×
2115
        <<"onlineusers">> -> length(ejabberd_sm:get_vh_session_list(Host))
×
2116
    end.
2117

2118

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

2133
num_prio(Priority) when is_integer(Priority) ->
2134
    Priority;
×
2135
num_prio(_) ->
2136
    -1.
×
2137

2138
%%%
2139
%%% Web Admin
2140
%%%
2141

2142
%% @format-begin
2143

2144
%%% Main
2145

2146
web_menu_main(Acc, _Lang) ->
2147
    Acc ++ [{<<"stats">>, <<"Statistics">>}].
30✔
2148

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

2173
%%% Host
2174

2175
web_menu_host(Acc, _Host, _Lang) ->
2176
    Acc ++ [{<<"purge">>, <<"Purge">>}, {<<"stats">>, <<"Statistics">>}].
×
2177

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

2206
%%% HostUser
2207

2208
web_menu_hostuser(Acc, _Host, _Username, _Lang) ->
2209
    Acc ++ [{<<"auth">>, <<"Authentication">>}, {<<"session">>, <<"Sessions">>}].
×
2210

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

2260
%%% HostNode
2261

2262
web_menu_hostnode(Acc, _Host, _Username, _Lang) ->
2263
    Acc ++ [{<<"modules">>, <<"Modules">>}].
×
2264

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

2275
%%% Node
2276

2277
web_menu_node(Acc, _Node, _Lang) ->
2278
    Acc ++ [{<<"stats">>, <<"Statistics">>}].
×
2279

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

2319
%%%
2320
%%% Document
2321
%%%
2322

2323
mod_options(_) -> [].
6✔
2324

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