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

processone / ejabberd / 937

06 Mar 2025 09:06PM UTC coverage: 33.382%. Remained the same
937

push

github

badlop
mod_announce: Improve documentation syntax

14863 of 44524 relevant lines covered (33.38%)

622.26 hits per line

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

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

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

29
-behaviour(gen_mod).
30

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

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

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

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

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

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

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

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

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

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

80
         % Privacy list
81
         privacy_set/3,
82

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

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

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

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

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

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

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

131
depends(_Host, _Opts) ->
132
    [].
9✔
133

134
%%%
135
%%% Register commands
136
%%%
137

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1030

1031
%%%
1032
%%% Adminsys
1033
%%%
1034

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

1046
get_cookie() ->
1047
    atom_to_list(erlang:get_cookie()).
×
1048

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

1073
%%%
1074
%%% Accounts
1075
%%%
1076

1077
set_password(User, Host, Password) ->
1078
    Fun = fun () -> ejabberd_auth:set_password(User, Host, Password) end,
5✔
1079
    user_action(User, Host, Fun, ok).
5✔
1080

1081
check_password(User, Host, Password) ->
1082
    ejabberd_auth:check_password(User, <<>>, Host, Password).
×
1083

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

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

1112
delete_old_users(Days) ->
1113
    %% Get the list of registered users
1114
    Users = ejabberd_auth:get_users(),
1✔
1115

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

1119
delete_old_users_vhost(Host, Days) ->
1120
    %% Get the list of registered users
1121
    Users = ejabberd_auth:get_users(Host),
×
1122

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

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

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

1156
%%
1157
%% Ban account v0
1158

1159
ban_account(User, Host, ReasonText) ->
1160
    Reason = prepare_reason(ReasonText),
×
1161
    kick_sessions(User, Host, Reason),
×
1162
    set_random_password(User, Host, Reason),
×
1163
    ok.
×
1164

1165
kick_sessions(User, Server, Reason) ->
1166
    lists:map(
×
1167
      fun(Resource) ->
1168
              kick_this_session(User, Server, Resource, Reason)
×
1169
      end,
1170
      ejabberd_sm:get_user_resources(User, Server)).
1171

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

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

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

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

1193
%%
1194
%% Ban account v2
1195

1196
ban_account_v2(User, Host, ReasonText) ->
1197
    case gen_mod:is_loaded(Host, mod_private) of
×
1198
        false ->
1199
            mod_private_is_required_but_disabled;
×
1200
        true ->
1201
            case is_banned(User, Host) of
×
1202
                true ->
1203
                    account_was_already_banned;
×
1204
                false ->
1205
                    ban_account_v2_b(User, Host, ReasonText)
×
1206
            end
1207
    end.
1208

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

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

1225
set_random_password_v2(User, Server) ->
1226
    NewPass = p1_rand:get_string(),
×
1227
    ok = ejabberd_auth:set_password(User, Server, NewPass).
×
1228

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

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

1255
%%
1256
%% Get ban details
1257

1258
get_ban_details(User, Host) ->
1259
    case private_get2(User, Host, <<"banned">>, <<"jabber:ejabberd:banned">>) of
1,307✔
1260
        [El] ->
1261
            get_ban_details(User, Host, El);
1,176✔
1262
        [] ->
1263
            []
131✔
1264
    end.
1265

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

1282
is_banned(User, Host) ->
1283
    case lists:keyfind("bandate", 1, get_ban_details(User, Host)) of
×
1284
        {_, BanDate} when BanDate /= <<>> ->
1285
            true;
×
1286
        _ ->
1287
            false
×
1288
    end.
1289

1290
%%
1291
%% Unban account
1292

1293
unban_account(User, Host) ->
1294
    case gen_mod:is_loaded(Host, mod_private) of
×
1295
        false ->
1296
            mod_private_is_required_but_disabled;
×
1297
        true ->
1298
            case is_banned(User, Host) of
×
1299
                false ->
1300
                    account_was_not_banned;
×
1301
                true ->
1302
                    unban_account2(User, Host)
×
1303
            end
1304
    end.
1305

1306
unban_account2(User, Host) ->
1307
    OldPass = get_oldpass(User, Host),
×
1308
    ok = ejabberd_auth:set_password(User, Host, OldPass),
×
1309
    UnBanPrivateXml = build_unban_xmlel(),
×
1310
    private_set2(User, Host, UnBanPrivateXml).
×
1311

1312
get_oldpass(User, Host) ->
1313
    [El] = private_get2(User, Host, <<"banned">>, <<"jabber:ejabberd:banned">>),
×
1314
    Pass = fxml:get_subtag(El, <<"password">>),
×
1315
    get_pass(Pass).
×
1316

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

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

1334
%%%
1335
%%% Sessions
1336
%%%
1337

1338
num_resources(User, Host) ->
1339
    length(ejabberd_sm:get_user_resources(User, Host)).
×
1340

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

1351
kick_session(User, Server, Resource, ReasonText) ->
1352
    kick_this_session(User, Server, Resource, prepare_reason(ReasonText)),
×
1353
    ok.
×
1354

1355
kick_this_session(User, Server, Resource, Reason) ->
1356
    ejabberd_sm:route(jid:make(User, Server, Resource),
×
1357
                      {exit, Reason}).
1358

1359
status_num(Host, Status) ->
1360
    length(get_status_list(Host, Status)).
×
1361
status_num(Status) ->
1362
    status_num(<<"all">>, Status).
×
1363
status_list(Host, Status) ->
1364
    Res = get_status_list(Host, Status),
×
1365
    [{U, S, R, num_prio(P), St} || {U, S, R, P, St} <- Res].
×
1366
status_list(Status) ->
1367
    status_list(<<"all">>, Status).
×
1368

1369
status_list_v3(ArgHost, Status) ->
1370
    List = status_list(ArgHost, Status),
×
1371
    [{jid:encode(jid:make(User, Host, Resource)), Priority, StatusText}
×
1372
     || {User, Host, Resource, Priority, StatusText} <- List].
×
1373

1374
status_list_v3(Status) ->
1375
    status_list_v3(<<"all">>, Status).
×
1376

1377

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

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

1418
connected_users_vhost(Host) ->
1419
    USRs = ejabberd_sm:get_vh_session_list(Host),
×
1420
    [ jid:encode(jid:make(USR)) || USR <- USRs].
×
1421

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

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

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

1457
set_presence(User, Host, Resource, Type, Show, Status, Priority) when is_binary(Priority) ->
1458
    set_presence(User, Host, Resource, Type, Show, Status, binary_to_integer(Priority));
×
1459

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

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

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

1501

1502
%%%
1503
%%% Vcard
1504
%%%
1505

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

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

1519
get_vcard(User, Host, Name, Subname) ->
1520
    [Res | _] = get_vcard_content(User, Host, [Name, Subname]),
×
1521
    Res.
×
1522

1523
get_vcard_multi(User, Host, Name, Subname) ->
1524
    get_vcard_content(User, Host, [Name, Subname]).
×
1525

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

1529
set_vcard(User, Host, Name, Subname, SomeContent) ->
1530
    set_vcard_content(User, Host, [Name, Subname], SomeContent).
×
1531

1532
%%
1533
%% Room vcard
1534

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

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

1556
%%
1557
%% Internal vcard
1558

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

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

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

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

1591
get_vcard([Data], A1) ->
1592
    get_subtag(A1, Data).
×
1593

1594
get_subtag(Xmlelement, Name) ->
1595
    [fxml:get_subtag(Xmlelement, Name)].
×
1596

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

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

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

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

1655

1656
%%%
1657
%%% Roster
1658
%%%
1659

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

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

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

1701
%% -----------------------------
1702
%% Get Roster
1703
%% -----------------------------
1704

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

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

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

1733
%%-----------------------------
1734
%% Push Roster from file
1735
%%-----------------------------
1736

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

1741
push_roster_all(File) ->
1742
    {ok, [Roster]} = file:consult(File),
×
1743
    subscribe_all(Roster).
×
1744

1745
subscribe_all(Roster) ->
1746
    subscribe_all(Roster, Roster).
×
1747
subscribe_all([], _) ->
1748
    ok;
×
1749
subscribe_all([User1 | Users], Roster) ->
1750
    subscribe_roster(User1, Roster),
×
1751
    subscribe_all(Users, Roster).
×
1752

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

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

1770
build_list_users(_Group, [], Res) ->
1771
    Res;
×
1772
build_list_users(Group, [{User, Server}|Users], Res) ->
1773
    build_list_users(Group, Users, [{User, Server, Group, User}|Res]).
×
1774

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

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

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

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

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

1820
%%%
1821
%%% Last Activity
1822
%%%
1823

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

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

1844
%%%
1845
%%% Private Storage
1846
%%%
1847

1848
%% Example usage:
1849
%% $ ejabberdctl private_set badlop localhost "\<aa\ xmlns=\'bb\'\>Cluth\</aa\>"
1850
%% $ ejabberdctl private_get badlop localhost aa bb
1851
%% <aa xmlns='bb'>Cluth</aa>
1852

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

1857
private_get2(Username, Host, Element, Ns) ->
1858
    case gen_mod:is_loaded(Host, mod_private) of
1,307✔
1859
        true -> private_get3(Username, Host, Element, Ns);
1,176✔
1860
        false -> []
131✔
1861
    end.
1862

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

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

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

1883
%%%
1884
%%% Shared Roster Groups
1885
%%%
1886

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

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

1903
srg_create2(Group, Host, Label, Description, DisplayList) ->
1904
    Opts = [{label, Label},
×
1905
            {displayed_groups, DisplayList},
1906
            {description, Description}],
1907
    {atomic, _} = mod_shared_roster:create_group(Host, Group, Opts),
×
1908
    ok.
×
1909

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

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

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

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

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

1937
%% @format-begin
1938

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

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

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

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

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

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

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

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

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

2050

2051
%%%
2052
%%% Stanza
2053
%%%
2054

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

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

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

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

2140
%%%
2141
%%% Stats
2142
%%%
2143

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

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

2159

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

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

2179
%%%
2180
%%% Web Admin
2181
%%%
2182

2183
%% @format-begin
2184

2185
%%% Main
2186

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

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

2214
%%% Host
2215

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

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

2247
%%% HostUser
2248

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

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

2301
%%% HostNode
2302

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

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

2316
%%% Node
2317

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

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

2360
%%%
2361
%%% Document
2362
%%%
2363

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

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