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

processone / ejabberd / 1227

02 Dec 2025 11:38AM UTC coverage: 33.6% (+0.06%) from 33.536%
1227

push

github

prefiks
Add db serialization to mod_muc_sql

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

10614 existing lines in 161 files now uncovered.

15526 of 46208 relevant lines covered (33.6%)

1072.13 hits per line

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

61.38
/src/node_flat.erl
1
%%%----------------------------------------------------------------------
2
%%% File    : node_flat.erl
3
%%% Author  : Christophe Romain <christophe.romain@process-one.net>
4
%%% Purpose : Standard PubSub node plugin
5
%%% Created :  1 Dec 2007 by Christophe Romain <christophe.romain@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
%%% @doc The module <strong>{@module}</strong> is the default PubSub plugin.
27
%%% <p>It is used as a default for all unknown PubSub node type.  It can serve
28
%%% as a developer basis and reference to build its own custom pubsub node
29
%%% types.</p>
30
%%% <p>PubSub plugin nodes are using the {@link gen_node} behaviour.</p>
31

32
-module(node_flat).
33
-behaviour(gen_pubsub_node).
34
-author('christophe.romain@process-one.net').
35

36
-include("pubsub.hrl").
37
-include_lib("xmpp/include/xmpp.hrl").
38

39
-export([init/3, terminate/2, options/0, features/0,
40
    create_node_permission/6, create_node/2, delete_node/1,
41
    purge_node/2, subscribe_node/8, unsubscribe_node/4,
42
    publish_item/7, delete_item/4,
43
    remove_extra_items/2, remove_extra_items/3, remove_expired_items/2,
44
    get_entity_affiliations/2, get_node_affiliations/1,
45
    get_affiliation/2, set_affiliation/3,
46
    get_entity_subscriptions/2, get_node_subscriptions/1,
47
    get_subscriptions/2, set_subscriptions/4,
48
    get_pending_nodes/2, get_states/1, get_state/2,
49
    set_state/1, get_items/7, get_items/3, get_item/7,
50
    get_last_items/3, get_only_item/2,
51
    get_item/2, set_item/1, get_item_name/3, node_to_path/1,
52
    path_to_node/1, can_fetch_item/2, is_subscribed/1, transform/1]).
53

54
init(_Host, _ServerHost, _Opts) ->
55
    %pubsub_subscription:init(Host, ServerHost, Opts),
UNCOV
56
    ejabberd_mnesia:create(?MODULE, pubsub_state,
4✔
57
        [{disc_copies, [node()]}, {index, [nodeidx]},
58
            {type, ordered_set},
59
            {attributes, record_info(fields, pubsub_state)}]),
UNCOV
60
    ejabberd_mnesia:create(?MODULE, pubsub_item,
4✔
61
        [{disc_only_copies, [node()]}, {index, [nodeidx]},
62
            {attributes, record_info(fields, pubsub_item)}]),
UNCOV
63
    ejabberd_mnesia:create(?MODULE, pubsub_orphan,
4✔
64
        [{disc_copies, [node()]},
65
            {attributes, record_info(fields, pubsub_orphan)}]),
UNCOV
66
    ItemsFields = record_info(fields, pubsub_item),
4✔
UNCOV
67
    case mnesia:table_info(pubsub_item, attributes) of
4✔
UNCOV
68
        ItemsFields -> ok;
4✔
69
        _ -> mnesia:transform_table(pubsub_item, ignore, ItemsFields)
×
70
    end,
UNCOV
71
    ok.
4✔
72

73
terminate(_Host, _ServerHost) ->
UNCOV
74
    ok.
4✔
75

76
options() ->
UNCOV
77
    [{deliver_payloads, true},
2,212✔
78
        {notify_config, false},
79
        {notify_delete, false},
80
        {notify_retract, true},
81
        {purge_offline, false},
82
        {persist_items, true},
83
        {max_items, ?MAXITEMS},
84
        {subscribe, true},
85
        {access_model, open},
86
        {roster_groups_allowed, []},
87
        {publish_model, publishers},
88
        {notification_type, headline},
89
        {max_payload_size, ?MAX_PAYLOAD_SIZE},
90
        {send_last_published_item, on_sub_and_presence},
91
        {deliver_notifications, true},
92
        {presence_based_delivery, false},
93
        {itemreply, none}].
94

95
features() ->
UNCOV
96
    [<<"create-nodes">>,
7,300✔
97
        <<"auto-create">>,
98
        <<"access-authorize">>,
99
        <<"delete-nodes">>,
100
        <<"delete-items">>,
101
        <<"get-pending">>,
102
        <<"instant-nodes">>,
103
        <<"manage-subscriptions">>,
104
        <<"modify-affiliations">>,
105
        <<"outcast-affiliation">>,
106
        <<"persistent-items">>,
107
        <<"multi-items">>,
108
        <<"publish">>,
109
        <<"publish-only-affiliation">>,
110
        <<"publish-options">>,
111
        <<"purge-nodes">>,
112
        <<"retract-items">>,
113
        <<"retrieve-affiliations">>,
114
        <<"retrieve-items">>,
115
        <<"retrieve-subscriptions">>,
116
        <<"subscribe">>,
117
        %%<<"subscription-options">>,
118
        <<"subscription-notifications">>].
119

120
%% @doc Checks if the current user has the permission to create the requested node
121
%% <p>In flat node, any unused node name is allowed. The access parameter is also
122
%% checked. This parameter depends on the value of the
123
%% <tt>access_createnode</tt> ACL value in ejabberd config file.</p>
124
create_node_permission(Host, ServerHost, _Node, _ParentNode, Owner, Access) ->
UNCOV
125
    LOwner = jid:tolower(Owner),
244✔
UNCOV
126
    Allowed = case LOwner of
244✔
127
        {<<"">>, Host, <<"">>} ->
128
            true; % pubsub service always allowed
×
129
        _ ->
UNCOV
130
            acl:match_rule(ServerHost, Access, LOwner) =:= allow
244✔
131
    end,
UNCOV
132
    {result, Allowed}.
244✔
133

134
create_node(Nidx, Owner) ->
UNCOV
135
    OwnerKey = jid:tolower(jid:remove_resource(Owner)),
68✔
UNCOV
136
    set_state(#pubsub_state{stateid = {OwnerKey, Nidx},
68✔
137
            nodeidx = Nidx, affiliation = owner}),
UNCOV
138
    {result, {default, broadcast}}.
68✔
139

140
delete_node(Nodes) ->
UNCOV
141
    Tr = fun (#pubsub_state{stateid = {J, _}, subscriptions = Ss}) ->
68✔
UNCOV
142
            lists:map(fun (S) -> {J, S} end, Ss)
100✔
143
    end,
UNCOV
144
    Reply = lists:map(fun (#pubsub_node{id = Nidx} = PubsubNode) ->
68✔
UNCOV
145
                    {result, States} = get_states(Nidx),
68✔
UNCOV
146
                    lists:foreach(fun (State) ->
68✔
UNCOV
147
                                del_items(Nidx, State#pubsub_state.items),
100✔
UNCOV
148
                                del_state(State#pubsub_state{items = []})
100✔
149
                        end, States),
UNCOV
150
                    del_orphan_items(Nidx),
68✔
UNCOV
151
                    {PubsubNode, lists:flatmap(Tr, States)}
68✔
152
            end, Nodes),
UNCOV
153
    {result, {default, broadcast, Reply}}.
68✔
154

155
%% @doc <p>Accepts or rejects subcription requests on a PubSub node.</p>
156
%% <p>The mechanism works as follow:
157
%% <ul>
158
%% <li>The main PubSub module prepares the subscription and passes the
159
%% result of the preparation as a record.</li>
160
%% <li>This function gets the prepared record and several other parameters and
161
%% can decide to:<ul>
162
%%  <li>reject the subscription;</li>
163
%%  <li>allow it as is, letting the main module perform the database
164
%%  persistence;</li>
165
%%  <li>allow it, modifying the record. The main module will store the
166
%%  modified record;</li>
167
%%  <li>allow it, but perform the needed persistence operations.</li></ul>
168
%% </li></ul></p>
169
%% <p>The selected behaviour depends on the return parameter:
170
%%  <ul>
171
%%   <li><tt>{error, Reason}</tt>: an IQ error result will be returned. No
172
%%   subscription will actually be performed.</li>
173
%%   <li><tt>true</tt>: Subscribe operation is allowed, based on the
174
%%   unmodified record passed in parameter <tt>SubscribeResult</tt>. If this
175
%%   parameter contains an error, no subscription will be performed.</li>
176
%%   <li><tt>{true, PubsubState}</tt>: Subscribe operation is allowed, but
177
%%   the {@link mod_pubsub:pubsubState()} record returned replaces the value
178
%%   passed in parameter <tt>SubscribeResult</tt>.</li>
179
%%   <li><tt>{true, done}</tt>: Subscribe operation is allowed, but the
180
%%   {@link mod_pubsub:pubsubState()} will be considered as already stored and
181
%%   no further persistence operation will be performed. This case is used,
182
%%   when the plugin module is doing the persistence by itself or when it want
183
%%   to completely disable persistence.</li></ul>
184
%% </p>
185
%% <p>In the default plugin module, the record is unchanged.</p>
186
subscribe_node(Nidx, Sender, Subscriber, AccessModel,
187
            SendLast, PresenceSubscription, RosterGroup, _Options) ->
UNCOV
188
    SubKey = jid:tolower(Subscriber),
38✔
UNCOV
189
    GenKey = jid:remove_resource(SubKey),
38✔
UNCOV
190
    Authorized = jid:tolower(jid:remove_resource(Sender)) == GenKey,
38✔
UNCOV
191
    GenState = get_state(Nidx, GenKey),
38✔
UNCOV
192
    SubState = case SubKey of
38✔
193
        GenKey -> GenState;
×
UNCOV
194
        _ -> get_state(Nidx, SubKey)
38✔
195
    end,
UNCOV
196
    Affiliation = GenState#pubsub_state.affiliation,
38✔
UNCOV
197
    Subscriptions = SubState#pubsub_state.subscriptions,
38✔
UNCOV
198
    Whitelisted = lists:member(Affiliation, [member, publisher, owner]),
38✔
UNCOV
199
    PendingSubscription = lists:any(fun
38✔
200
                ({pending, _}) -> true;
×
201
                (_) -> false
×
202
            end,
203
            Subscriptions),
UNCOV
204
    Owner = Affiliation == owner,
38✔
UNCOV
205
    if not Authorized ->
38✔
206
            {error,
×
207
                mod_pubsub:extended_error((xmpp:err_bad_request()), mod_pubsub:err_invalid_jid())};
208
        (Affiliation == outcast) or (Affiliation == publish_only) ->
UNCOV
209
            {error, xmpp:err_forbidden()};
4✔
210
        PendingSubscription ->
211
            {error,
×
212
                mod_pubsub:extended_error((xmpp:err_not_authorized()), mod_pubsub:err_pending_subscription())};
213
        (AccessModel == presence) and (not PresenceSubscription) and (not Owner) ->
214
            {error,
×
215
                mod_pubsub:extended_error((xmpp:err_not_authorized()), mod_pubsub:err_presence_subscription_required())};
216
        (AccessModel == roster) and (not RosterGroup) and (not Owner) ->
217
            {error,
×
218
                mod_pubsub:extended_error((xmpp:err_not_authorized()), mod_pubsub:err_not_in_roster_group())};
219
        (AccessModel == whitelist) and (not Whitelisted) and (not Owner) ->
220
            {error,
×
221
                mod_pubsub:extended_error((xmpp:err_not_allowed()), mod_pubsub:err_closed_node())};
222
        %%MustPay ->
223
        %%        % Payment is required for a subscription
224
        %%        {error, ?ERR_PAYMENT_REQUIRED};
225
        %%ForbiddenAnonymous ->
226
        %%        % Requesting entity is anonymous
227
        %%        {error, xmpp:err_forbidden()};
228
        true ->
229
            %%SubId = pubsub_subscription:add_subscription(Subscriber, Nidx, Options),
UNCOV
230
            {NewSub, SubId} = case Subscriptions of
34✔
231
                [{subscribed, Id}|_] ->
232
                    {subscribed, Id};
×
233
                [] ->
UNCOV
234
                    Id = pubsub_subscription:make_subid(),
34✔
UNCOV
235
                    Sub = case AccessModel of
34✔
UNCOV
236
                        authorize -> pending;
4✔
UNCOV
237
                        _ -> subscribed
30✔
238
                    end,
UNCOV
239
                    set_state(SubState#pubsub_state{subscriptions =
34✔
240
                            [{Sub, Id} | Subscriptions]}),
UNCOV
241
                    {Sub, Id}
34✔
242
            end,
UNCOV
243
            case {NewSub, SendLast} of
34✔
244
                {subscribed, never} ->
UNCOV
245
                    {result, {default, subscribed, SubId}};
8✔
246
                {subscribed, _} ->
UNCOV
247
                    {result, {default, subscribed, SubId, send_last}};
22✔
248
                {_, _} ->
UNCOV
249
                    {result, {default, pending, SubId}}
4✔
250
            end
251
    end.
252

253
%% @doc <p>Unsubscribe the <tt>Subscriber</tt> from the <tt>Node</tt>.</p>
254
unsubscribe_node(Nidx, Sender, Subscriber, SubId) ->
UNCOV
255
    SubKey = jid:tolower(Subscriber),
18✔
UNCOV
256
    GenKey = jid:remove_resource(SubKey),
18✔
UNCOV
257
    Authorized = jid:tolower(jid:remove_resource(Sender)) == GenKey,
18✔
UNCOV
258
    GenState = get_state(Nidx, GenKey),
18✔
UNCOV
259
    SubState = case SubKey of
18✔
UNCOV
260
        GenKey -> GenState;
4✔
UNCOV
261
        _ -> get_state(Nidx, SubKey)
14✔
262
    end,
UNCOV
263
    Subscriptions = lists:filter(fun
18✔
UNCOV
264
                ({_Sub, _SubId}) -> true;
10✔
265
                (_SubId) -> false
×
266
            end,
267
            SubState#pubsub_state.subscriptions),
UNCOV
268
    SubIdExists = case SubId of
18✔
UNCOV
269
        <<>> -> false;
18✔
270
        Binary when is_binary(Binary) -> true;
×
271
        _ -> false
×
272
    end,
UNCOV
273
    if
18✔
274
        %% Requesting entity is prohibited from unsubscribing entity
275
        not Authorized ->
276
            {error, xmpp:err_forbidden()};
×
277
        %% Entity did not specify SubId
278
        %%SubId == "", ?? ->
279
        %%        {error, mod_pubsub:extended_error(xmpp:err_bad_request(), "subid-required")};
280
        %% Invalid subscription identifier
281
        %%InvalidSubId ->
282
        %%        {error, mod_pubsub:extended_error(?ERR_NOT_ACCEPTABLE, "invalid-subid")};
283
        %% Requesting entity is not a subscriber
284
        Subscriptions == [] ->
UNCOV
285
            {error,
8✔
286
                mod_pubsub:extended_error(xmpp:err_unexpected_request(), mod_pubsub:err_not_subscribed())};
287
        %% Subid supplied, so use that.
288
        SubIdExists ->
289
            Sub = first_in_list(fun
×
290
                        ({_, S}) when S == SubId -> true;
×
291
                        (_) -> false
×
292
                    end,
293
                    SubState#pubsub_state.subscriptions),
294
            case Sub of
×
295
                {value, S} ->
296
                    delete_subscriptions(SubState, [S]),
×
297
                    {result, default};
×
298
                false ->
299
                    {error,
×
300
                        mod_pubsub:extended_error(xmpp:err_unexpected_request(), mod_pubsub:err_not_subscribed())}
301
            end;
302
        %% Asking to remove all subscriptions to the given node
303
        SubId == all ->
304
            delete_subscriptions(SubState, Subscriptions),
×
305
            {result, default};
×
306
        %% No subid supplied, but there's only one matching subscription
307
        length(Subscriptions) == 1 ->
UNCOV
308
            delete_subscriptions(SubState, Subscriptions),
10✔
UNCOV
309
            {result, default};
10✔
310
        %% No subid and more than one possible subscription match.
311
        true ->
312
            {error,
×
313
                mod_pubsub:extended_error((xmpp:err_bad_request()), mod_pubsub:err_subid_required())}
314
    end.
315

316
delete_subscriptions(SubState, Subscriptions) ->
UNCOV
317
    NewSubs = lists:foldl(fun ({Subscription, SubId}, Acc) ->
10✔
318
                    %%pubsub_subscription:delete_subscription(SubKey, Nidx, SubId),
UNCOV
319
                    Acc -- [{Subscription, SubId}]
10✔
320
            end, SubState#pubsub_state.subscriptions, Subscriptions),
UNCOV
321
    case {SubState#pubsub_state.affiliation, NewSubs} of
10✔
UNCOV
322
        {none, []} -> del_state(SubState);
10✔
323
        _          -> set_state(SubState#pubsub_state{subscriptions = NewSubs})
×
324
    end.
325

326
%% @doc <p>Publishes the item passed as parameter.</p>
327
%% <p>The mechanism works as follow:
328
%% <ul>
329
%% <li>The main PubSub module prepares the item to publish and passes the
330
%% result of the preparation as a {@link mod_pubsub:pubsubItem()} record.</li>
331
%% <li>This function gets the prepared record and several other parameters and can decide to:<ul>
332
%%  <li>reject the publication;</li>
333
%%  <li>allow the publication as is, letting the main module perform the database persistence;</li>
334
%%  <li>allow the publication, modifying the record. The main module will store the modified record;</li>
335
%%  <li>allow it, but perform the needed persistence operations.</li></ul>
336
%% </li></ul></p>
337
%% <p>The selected behaviour depends on the return parameter:
338
%%  <ul>
339
%%   <li><tt>{error, Reason}</tt>: an iq error result will be return. No
340
%%   publication is actually performed.</li>
341
%%   <li><tt>true</tt>: Publication operation is allowed, based on the
342
%%   unmodified record passed in parameter <tt>Item</tt>. If the <tt>Item</tt>
343
%%   parameter contains an error, no subscription will actually be
344
%%   performed.</li>
345
%%   <li><tt>{true, Item}</tt>: Publication operation is allowed, but the
346
%%   {@link mod_pubsub:pubsubItem()} record returned replaces the value passed
347
%%   in parameter <tt>Item</tt>. The persistence will be performed by the main
348
%%   module.</li>
349
%%   <li><tt>{true, done}</tt>: Publication operation is allowed, but the
350
%%   {@link mod_pubsub:pubsubItem()} will be considered as already stored and
351
%%   no further persistence operation will be performed. This case is used,
352
%%   when the plugin module is doing the persistence by itself or when it want
353
%%   to completely disable persistence.</li></ul>
354
%% </p>
355
%% <p>In the default plugin module, the record is unchanged.</p>
356
publish_item(Nidx, Publisher, PublishModel, MaxItems, ItemId, Payload,
357
             _PubOpts) ->
UNCOV
358
    SubKey = jid:tolower(Publisher),
74✔
UNCOV
359
    GenKey = jid:remove_resource(SubKey),
74✔
UNCOV
360
    GenState = get_state(Nidx, GenKey),
74✔
UNCOV
361
    SubState = case SubKey of
74✔
UNCOV
362
        GenKey -> GenState;
12✔
UNCOV
363
        _ -> get_state(Nidx, SubKey)
62✔
364
    end,
UNCOV
365
    Affiliation = GenState#pubsub_state.affiliation,
74✔
UNCOV
366
    Subscribed = case PublishModel of
74✔
367
        subscribers -> is_subscribed(GenState#pubsub_state.subscriptions) orelse
×
368
                       is_subscribed(SubState#pubsub_state.subscriptions);
×
UNCOV
369
        _ -> undefined
74✔
370
    end,
UNCOV
371
    if not ((PublishModel == open) or
74✔
372
                    (PublishModel == publishers) and
373
                    ((Affiliation == owner)
374
                        or (Affiliation == publisher)
375
                        or (Affiliation == publish_only))
376
                    or (Subscribed == true)) ->
UNCOV
377
            {error, xmpp:err_forbidden()};
6✔
378
        true ->
UNCOV
379
            if MaxItems > 0;
68✔
380
               MaxItems == unlimited ->
UNCOV
381
                    Now = erlang:timestamp(),
68✔
UNCOV
382
                    case get_item(Nidx, ItemId) of
68✔
383
                        {result, #pubsub_item{creation = {_, GenKey}} = OldItem} ->
UNCOV
384
                            set_item(OldItem#pubsub_item{
2✔
385
                                        modification = {Now, SubKey},
386
                                        payload = Payload}),
UNCOV
387
                            {result, {default, broadcast, []}};
2✔
388
                        % Allow node owner to modify any item, he can also delete it and recreate
389
                        {result, #pubsub_item{creation = {CreationTime, _}} = OldItem} when Affiliation == owner->
390
                            set_item(OldItem#pubsub_item{
×
391
                                creation = {CreationTime, GenKey},
392
                                modification = {Now, SubKey},
393
                                payload = Payload}),
394
                            {result, {default, broadcast, []}};
×
395
                        {result, _} ->
396
                            {error, xmpp:err_forbidden()};
×
397
                        _ ->
UNCOV
398
                            Items = [ItemId | GenState#pubsub_state.items],
66✔
UNCOV
399
                            {result, {NI, OI}} = remove_extra_items(Nidx, MaxItems, Items),
66✔
UNCOV
400
                            set_state(GenState#pubsub_state{items = NI}),
66✔
UNCOV
401
                            set_item(#pubsub_item{
66✔
402
                                        itemid = {ItemId, Nidx},
403
                                        nodeidx = Nidx,
404
                                        creation = {Now, GenKey},
405
                                        modification = {Now, SubKey},
406
                                        payload = Payload}),
UNCOV
407
                            {result, {default, broadcast, OI}}
66✔
408
                    end;
409
                true ->
410
                    {result, {default, broadcast, []}}
×
411
            end
412
    end.
413

414
remove_extra_items(Nidx, MaxItems) ->
415
    {result, States} = get_states(Nidx),
×
416
    Records = States ++ mnesia:read({pubsub_orphan, Nidx}),
×
417
    ItemIds = lists:flatmap(fun(#pubsub_state{items = Is}) ->
×
418
                                    Is;
×
419
                               (#pubsub_orphan{items = Is}) ->
420
                                    Is
×
421
                            end, Records),
422
    remove_extra_items(Nidx, MaxItems, ItemIds).
×
423

424
%% @doc <p>This function is used to remove extra items, most notably when the
425
%% maximum number of items has been reached.</p>
426
%% <p>This function is used internally by the core PubSub module, as no
427
%% permission check is performed.</p>
428
%% <p>In the default plugin module, the oldest items are removed, but other
429
%% rules can be used.</p>
430
%% <p>If another PubSub plugin wants to delegate the item removal (and if the
431
%% plugin is using the default pubsub storage), it can implements this function like this:
432
%% ```remove_extra_items(Nidx, MaxItems, ItemIds) ->
433
%%           node_default:remove_extra_items(Nidx, MaxItems, ItemIds).'''</p>
434
remove_extra_items(_Nidx, unlimited, ItemIds) ->
435
    {result, {ItemIds, []}};
×
436
remove_extra_items(Nidx, MaxItems, ItemIds) ->
UNCOV
437
    NewItems = lists:sublist(ItemIds, MaxItems),
66✔
UNCOV
438
    OldItems = lists:nthtail(length(NewItems), ItemIds),
66✔
UNCOV
439
    del_items(Nidx, OldItems),
66✔
UNCOV
440
    {result, {NewItems, OldItems}}.
66✔
441

442
remove_expired_items(_Nidx, infinity) ->
443
    {result, []};
×
444
remove_expired_items(Nidx, Seconds) ->
445
    Items = mnesia:index_read(pubsub_item, Nidx, #pubsub_item.nodeidx),
×
446
    ExpT = misc:usec_to_now(
×
447
             erlang:system_time(microsecond) - (Seconds * 1000000)),
448
    ExpItems = lists:filtermap(
×
449
                 fun(#pubsub_item{itemid = {ItemId, _},
450
                                  modification = {ModT, _}}) when ModT < ExpT ->
451
                         {true, ItemId};
×
452
                    (#pubsub_item{}) ->
453
                         false
×
454
                 end, Items),
455
    del_items(Nidx, ExpItems),
×
456
    {result, ExpItems}.
×
457

458
%% @doc <p>Triggers item deletion.</p>
459
%% <p>Default plugin: The user performing the deletion must be the node owner
460
%% or a publisher, or PublishModel being open.</p>
461
delete_item(Nidx, Publisher, PublishModel, ItemId) ->
UNCOV
462
    SubKey = jid:tolower(Publisher),
18✔
UNCOV
463
    GenKey = jid:remove_resource(SubKey),
18✔
UNCOV
464
    GenState = get_state(Nidx, GenKey),
18✔
UNCOV
465
    #pubsub_state{affiliation = Affiliation, items = Items} = GenState,
18✔
UNCOV
466
    Allowed = Affiliation == publisher orelse
18✔
UNCOV
467
        Affiliation == owner orelse
16✔
UNCOV
468
        (PublishModel == open andalso
8✔
469
          case get_item(Nidx, ItemId) of
×
470
            {result, #pubsub_item{creation = {_, GenKey}}} -> true;
×
471
            _ -> false
×
472
          end),
UNCOV
473
    if not Allowed ->
18✔
UNCOV
474
            {error, xmpp:err_forbidden()};
8✔
475
        true ->
UNCOV
476
            case lists:member(ItemId, Items) of
10✔
477
                true ->
UNCOV
478
                    del_item(Nidx, ItemId),
8✔
UNCOV
479
                    set_state(GenState#pubsub_state{items = lists:delete(ItemId, Items)}),
8✔
UNCOV
480
                    {result, {default, broadcast}};
8✔
481
                false ->
UNCOV
482
                    case Affiliation of
2✔
483
                        owner ->
UNCOV
484
                            {result, States} = get_states(Nidx),
2✔
UNCOV
485
                            Records = States ++ mnesia:read({pubsub_orphan, Nidx}),
2✔
UNCOV
486
                            lists:foldl(fun
2✔
487
                                    (#pubsub_state{items = RI} = S, Res) ->
UNCOV
488
                                        case lists:member(ItemId, RI) of
4✔
489
                                            true ->
UNCOV
490
                                                NI = lists:delete(ItemId, RI),
2✔
UNCOV
491
                                                del_item(Nidx, ItemId),
2✔
UNCOV
492
                                                mnesia:write(S#pubsub_state{items = NI}),
2✔
UNCOV
493
                                                {result, {default, broadcast}};
2✔
494
                                            false ->
UNCOV
495
                                                Res
2✔
496
                                        end;
497
                                    (#pubsub_orphan{items = RI} = S, Res) ->
498
                                        case lists:member(ItemId, RI) of
×
499
                                            true ->
500
                                                NI = lists:delete(ItemId, RI),
×
501
                                                del_item(Nidx, ItemId),
×
502
                                                mnesia:write(S#pubsub_orphan{items = NI}),
×
503
                                                {result, {default, broadcast}};
×
504
                                            false ->
505
                                                Res
×
506
                                        end
507
                                end,
508
                                {error, xmpp:err_item_not_found()}, Records);
509
                        _ ->
510
                            {error, xmpp:err_forbidden()}
×
511
                    end
512
            end
513
    end.
514

515
purge_node(Nidx, Owner) ->
UNCOV
516
    SubKey = jid:tolower(Owner),
14✔
UNCOV
517
    GenKey = jid:remove_resource(SubKey),
14✔
UNCOV
518
    GenState = get_state(Nidx, GenKey),
14✔
UNCOV
519
    case GenState of
14✔
520
        #pubsub_state{affiliation = owner} ->
UNCOV
521
            {result, States} = get_states(Nidx),
4✔
UNCOV
522
            lists:foreach(fun
4✔
523
                    (#pubsub_state{items = []}) ->
UNCOV
524
                        ok;
4✔
525
                    (#pubsub_state{items = Items} = S) ->
UNCOV
526
                        del_items(Nidx, Items),
2✔
UNCOV
527
                        set_state(S#pubsub_state{items = []})
2✔
528
                end,
529
                States),
UNCOV
530
            del_orphan_items(Nidx),
4✔
UNCOV
531
            {result, {default, broadcast}};
4✔
532
        _ ->
UNCOV
533
            {error, xmpp:err_forbidden()}
10✔
534
    end.
535

536
%% @doc <p>Return the current affiliations for the given user</p>
537
%% <p>The default module reads affiliations in the main Mnesia
538
%% <tt>pubsub_state</tt> table. If a plugin stores its data in the same
539
%% table, it should return an empty list, as the affiliation will be read by
540
%% the default PubSub module. Otherwise, it should return its own affiliation,
541
%% that will be added to the affiliation stored in the main
542
%% <tt>pubsub_state</tt> table.</p>
543
get_entity_affiliations(Host, Owner) ->
UNCOV
544
    SubKey = jid:tolower(Owner),
492✔
UNCOV
545
    GenKey = jid:remove_resource(SubKey),
492✔
UNCOV
546
    States = mnesia:match_object(#pubsub_state{stateid = {GenKey, '_'}, _ = '_'}),
492✔
UNCOV
547
    NodeTree = mod_pubsub:tree(Host),
492✔
UNCOV
548
    Reply = lists:foldl(fun (#pubsub_state{stateid = {_, N}, affiliation = A}, Acc) ->
492✔
UNCOV
549
                    case NodeTree:get_node(N) of
18✔
UNCOV
550
                        #pubsub_node{nodeid = {Host, _}} = Node -> [{Node, A} | Acc];
10✔
UNCOV
551
                        _ -> Acc
8✔
552
                    end
553
            end,
554
            [], States),
UNCOV
555
    {result, Reply}.
492✔
556

557
get_node_affiliations(Nidx) ->
UNCOV
558
    {result, States} = get_states(Nidx),
14✔
UNCOV
559
    Tr = fun (#pubsub_state{stateid = {J, _}, affiliation = A}) -> {J, A} end,
14✔
UNCOV
560
    {result, lists:map(Tr, States)}.
14✔
561

562
get_affiliation(Nidx, Owner) ->
UNCOV
563
    SubKey = jid:tolower(Owner),
158✔
UNCOV
564
    GenKey = jid:remove_resource(SubKey),
158✔
UNCOV
565
    #pubsub_state{affiliation = Affiliation} = get_state(Nidx, GenKey),
158✔
UNCOV
566
    {result, Affiliation}.
158✔
567

568
set_affiliation(Nidx, Owner, Affiliation) ->
UNCOV
569
    SubKey = jid:tolower(Owner),
16✔
UNCOV
570
    GenKey = jid:remove_resource(SubKey),
16✔
UNCOV
571
    GenState = get_state(Nidx, GenKey),
16✔
UNCOV
572
    case {Affiliation, GenState#pubsub_state.subscriptions} of
16✔
UNCOV
573
        {none, []} -> {result, del_state(GenState)};
2✔
UNCOV
574
        _ -> {result, set_state(GenState#pubsub_state{affiliation = Affiliation})}
14✔
575
    end.
576

577
%% @doc <p>Return the current subscriptions for the given user</p>
578
%% <p>The default module reads subscriptions in the main Mnesia
579
%% <tt>pubsub_state</tt> table. If a plugin stores its data in the same
580
%% table, it should return an empty list, as the affiliation will be read by
581
%% the default PubSub module. Otherwise, it should return its own affiliation,
582
%% that will be added to the affiliation stored in the main
583
%% <tt>pubsub_state</tt> table.</p>
584
get_entity_subscriptions(Host, Owner) ->
UNCOV
585
    {U, D, _} = SubKey = jid:tolower(Owner),
194✔
UNCOV
586
    GenKey = jid:remove_resource(SubKey),
194✔
UNCOV
587
    States = case SubKey of
194✔
588
        GenKey ->
UNCOV
589
            mnesia:match_object(#pubsub_state{stateid = {{U, D, '_'}, '_'}, _ = '_'});
136✔
590
        _ ->
591
            mnesia:match_object(#pubsub_state{stateid = {GenKey, '_'}, _ = '_'})
UNCOV
592
            ++
58✔
593
            mnesia:match_object(#pubsub_state{stateid = {SubKey, '_'}, _ = '_'})
594
    end,
UNCOV
595
    NodeTree = mod_pubsub:tree(Host),
194✔
UNCOV
596
    Reply = lists:foldl(fun (#pubsub_state{stateid = {J, N}, subscriptions = Ss}, Acc) ->
194✔
UNCOV
597
                    case NodeTree:get_node(N) of
34✔
598
                        #pubsub_node{nodeid = {Host, _}} = Node ->
UNCOV
599
                            lists:foldl(fun ({Sub, SubId}, Acc2) ->
34✔
UNCOV
600
                                        [{Node, Sub, SubId, J} | Acc2]
16✔
601
                                end,
602
                                Acc, Ss);
603
                        _ ->
604
                            Acc
×
605
                    end
606
            end,
607
            [], States),
UNCOV
608
    {result, Reply}.
194✔
609

610
get_node_subscriptions(Nidx) ->
UNCOV
611
    {result, States} = get_states(Nidx),
232✔
UNCOV
612
    Tr = fun (#pubsub_state{stateid = {J, _}, subscriptions = Subscriptions}) ->
232✔
UNCOV
613
            lists:foldl(fun ({S, SubId}, Acc) ->
230✔
UNCOV
614
                        [{J, S, SubId} | Acc]
40✔
615
                end,
616
                [], Subscriptions)
617
    end,
UNCOV
618
    {result, lists:flatmap(Tr, States)}.
232✔
619

620
get_subscriptions(Nidx, Owner) ->
UNCOV
621
    SubKey = jid:tolower(Owner),
4✔
UNCOV
622
    SubState = get_state(Nidx, SubKey),
4✔
UNCOV
623
    {result, SubState#pubsub_state.subscriptions}.
4✔
624

625
set_subscriptions(Nidx, Owner, Subscription, SubId) ->
UNCOV
626
    SubKey = jid:tolower(Owner),
12✔
UNCOV
627
    SubState = get_state(Nidx, SubKey),
12✔
UNCOV
628
    case {SubId, SubState#pubsub_state.subscriptions} of
12✔
629
        {_, []} ->
UNCOV
630
            case Subscription of
2✔
631
                none ->
632
                    {error,
×
633
                        mod_pubsub:extended_error((xmpp:err_bad_request()), mod_pubsub:err_not_subscribed())};
634
                _ ->
UNCOV
635
                    new_subscription(Nidx, Owner, Subscription, SubState)
2✔
636
            end;
637
        {<<>>, [{_, SID}]} ->
UNCOV
638
            case Subscription of
6✔
UNCOV
639
                none -> unsub_with_subid(SubState, SID);
2✔
UNCOV
640
                _ -> replace_subscription({Subscription, SID}, SubState)
4✔
641
            end;
642
        {<<>>, [_ | _]} ->
643
            {error,
×
644
                mod_pubsub:extended_error((xmpp:err_bad_request()), mod_pubsub:err_subid_required())};
645
        _ ->
UNCOV
646
            case Subscription of
4✔
UNCOV
647
                none -> unsub_with_subid(SubState, SubId);
2✔
UNCOV
648
                _ -> replace_subscription({Subscription, SubId}, SubState)
2✔
649
            end
650
    end.
651

652
replace_subscription(NewSub, SubState) ->
UNCOV
653
    NewSubs = replace_subscription(NewSub, SubState#pubsub_state.subscriptions, []),
6✔
UNCOV
654
    {result, set_state(SubState#pubsub_state{subscriptions = NewSubs})}.
6✔
655

UNCOV
656
replace_subscription(_, [], Acc) -> Acc;
6✔
657
replace_subscription({Sub, SubId}, [{_, SubId} | T], Acc) ->
UNCOV
658
    replace_subscription({Sub, SubId}, T, [{Sub, SubId} | Acc]).
6✔
659

660
new_subscription(_Nidx, _Owner, Sub, SubState) ->
661
    %%SubId = pubsub_subscription:add_subscription(Owner, Nidx, []),
UNCOV
662
    SubId = pubsub_subscription:make_subid(),
2✔
UNCOV
663
    Subs = SubState#pubsub_state.subscriptions,
2✔
UNCOV
664
    set_state(SubState#pubsub_state{subscriptions = [{Sub, SubId} | Subs]}),
2✔
UNCOV
665
    {result, {Sub, SubId}}.
2✔
666

667
unsub_with_subid(SubState, SubId) ->
668
    %%pubsub_subscription:delete_subscription(SubState#pubsub_state.stateid, Nidx, SubId),
UNCOV
669
    NewSubs = [{S, Sid}
4✔
UNCOV
670
            || {S, Sid} <- SubState#pubsub_state.subscriptions,
4✔
UNCOV
671
                SubId =/= Sid],
4✔
UNCOV
672
    case {NewSubs, SubState#pubsub_state.affiliation} of
4✔
UNCOV
673
        {[], none} -> {result, del_state(SubState)};
4✔
674
        _ -> {result, set_state(SubState#pubsub_state{subscriptions = NewSubs})}
×
675
    end.
676

677
%% @doc <p>Returns a list of Owner's nodes on Host with pending
678
%% subscriptions.</p>
679
get_pending_nodes(Host, Owner) ->
680
    GenKey = jid:remove_resource(jid:tolower(Owner)),
×
681
    States = mnesia:match_object(#pubsub_state{stateid = {GenKey, '_'},
×
682
                affiliation = owner,
683
                _ = '_'}),
684
    NodeIdxs = [Nidx || #pubsub_state{stateid = {_, Nidx}} <- States],
×
685
    NodeTree = mod_pubsub:tree(Host),
×
686
    Reply = mnesia:foldl(fun (#pubsub_state{stateid = {_, Nidx}} = S, Acc) ->
×
687
                    case lists:member(Nidx, NodeIdxs) of
×
688
                        true ->
689
                            case get_nodes_helper(NodeTree, S) of
×
690
                                {value, Node} -> [Node | Acc];
×
691
                                false -> Acc
×
692
                            end;
693
                        false ->
694
                            Acc
×
695
                    end
696
            end,
697
            [], pubsub_state),
698
    {result, Reply}.
×
699

700
get_nodes_helper(NodeTree, #pubsub_state{stateid = {_, N}, subscriptions = Subs}) ->
701
    HasPending = fun
×
702
        ({pending, _}) -> true;
×
703
        (pending) -> true;
×
704
        (_) -> false
×
705
    end,
706
    case lists:any(HasPending, Subs) of
×
707
        true ->
708
            case NodeTree:get_node(N) of
×
709
                #pubsub_node{nodeid = {_, Node}} -> {value, Node};
×
710
                _ -> false
×
711
            end;
712
        false ->
713
            false
×
714
    end.
715

716
%% @doc Returns the list of stored states for a given node.
717
%% <p>For the default PubSub module, states are stored in Mnesia database.</p>
718
%% <p>We can consider that the pubsub_state table have been created by the main
719
%% mod_pubsub module.</p>
720
%% <p>PubSub plugins can store the states where they wants (for example in a
721
%% relational database).</p>
722
%% <p>If a PubSub plugin wants to delegate the states storage to the default node,
723
%% they can implement this function like this:
724
%% ```get_states(Nidx) ->
725
%%           node_default:get_states(Nidx).'''</p>
726
get_states(Nidx) ->
UNCOV
727
    States = case catch mnesia:index_read(pubsub_state, Nidx, #pubsub_state.nodeidx) of
320✔
UNCOV
728
        List when is_list(List) -> List;
320✔
729
        _ -> []
×
730
    end,
UNCOV
731
    {result, States}.
320✔
732

733
%% @doc <p>Returns a state (one state list), given its reference.</p>
734
get_state(Nidx, Key) ->
UNCOV
735
    StateId = {Key, Nidx},
522✔
UNCOV
736
    case catch mnesia:read({pubsub_state, StateId}) of
522✔
UNCOV
737
        [State] when is_record(State, pubsub_state) -> State;
336✔
UNCOV
738
        _ -> #pubsub_state{stateid = StateId, nodeidx = Nidx}
186✔
739
    end.
740

741
%% @doc <p>Write a state into database.</p>
742
set_state(State) when is_record(State, pubsub_state) ->
UNCOV
743
    mnesia:write(State).
200✔
744
%set_state(_) -> {error, ?ERR_INTERNAL_SERVER_ERROR}.
745

746
%% @doc <p>Delete a state from database.</p>
747
del_state(#pubsub_state{stateid = {Key, Nidx}, items = Items}) ->
UNCOV
748
    case Items of
116✔
749
        [] ->
UNCOV
750
            ok;
116✔
751
        _ ->
752
            Orphan = #pubsub_orphan{nodeid = Nidx, items =
×
753
                case mnesia:read({pubsub_orphan, Nidx}) of
754
                    [#pubsub_orphan{items = ItemIds}] ->
755
                        lists:usort(ItemIds++Items);
×
756
                  _ ->
757
                        Items
×
758
                end},
759
            mnesia:write(Orphan)
×
760
    end,
UNCOV
761
    mnesia:delete({pubsub_state, {Key, Nidx}}).
116✔
762

763
%% @doc Returns the list of stored items for a given node.
764
%% <p>For the default PubSub module, items are stored in Mnesia database.</p>
765
%% <p>We can consider that the pubsub_item table have been created by the main
766
%% mod_pubsub module.</p>
767
%% <p>PubSub plugins can store the items where they wants (for example in a
768
%% relational database), or they can even decide not to persist any items.</p>
769
get_items(Nidx, _From, undefined) ->
UNCOV
770
    RItems = lists:keysort(#pubsub_item.creation,
34✔
771
                           mnesia:index_read(pubsub_item, Nidx, #pubsub_item.nodeidx)),
UNCOV
772
    {result, {RItems, undefined}};
34✔
773

774
get_items(Nidx, _From, #rsm_set{max = Max, index = IncIndex,
775
                                'after' = After, before = Before}) ->
776
    case lists:keysort(#pubsub_item.creation,
×
777
                       mnesia:index_read(pubsub_item, Nidx, #pubsub_item.nodeidx)) of
778
        [] ->
779
            {result, {[], #rsm_set{count = 0}}};
×
780
        RItems ->
781
            Count = length(RItems),
×
782
            Limit = case Max of
×
783
                        undefined -> ?MAXITEMS;
×
784
                        _ -> Max
×
785
                    end,
786
            {Offset, ItemsPage} =
×
787
                case {IncIndex, Before, After} of
788
                    {undefined, undefined, undefined} ->
789
                        {0, lists:sublist(RItems, Limit)};
×
790
                    {I, undefined, undefined} ->
791
                        SubList = lists:nthtail(I, RItems),
×
792
                        {I, lists:sublist(SubList, Limit)};
×
793
                    {_, <<>>, undefined} ->
794
                        %% 2.5 Requesting the Last Page in a Result Set
795
                        SubList = lists:reverse(RItems),
×
796
                        {Count-Limit, lists:reverse(lists:sublist(SubList, Limit))};
×
797
                    {_, Stamp, undefined} ->
798
                        BeforeNow = encode_stamp(Stamp),
×
799
                        {NewIndex, SubList} = extract_sublist(before_now, BeforeNow,
×
800
                                                              0, lists:reverse(RItems)),
801
                        {Count-NewIndex-Limit, lists:reverse(lists:sublist(SubList, Limit))};
×
802
                    {_, undefined, Stamp} ->
803
                        AfterNow = encode_stamp(Stamp),
×
804
                        {NewIndex, SubList} = extract_sublist(after_now, AfterNow,
×
805
                                                              0, RItems),
806
                        {NewIndex, lists:sublist(SubList, Limit)}
×
807
                end,
808
            Rsm = rsm_page(Count, IncIndex, Offset, ItemsPage),
×
809
            {result, {ItemsPage, Rsm}}
×
810
    end.
811

812
get_items(Nidx, JID, AccessModel, PresenceSubscription, RosterGroup, _SubId, RSM) ->
UNCOV
813
    SubKey = jid:tolower(JID),
28✔
UNCOV
814
    GenKey = jid:remove_resource(SubKey),
28✔
UNCOV
815
    GenState = get_state(Nidx, GenKey),
28✔
UNCOV
816
    SubState = get_state(Nidx, SubKey),
28✔
UNCOV
817
    Affiliation = GenState#pubsub_state.affiliation,
28✔
UNCOV
818
    BareSubscriptions = GenState#pubsub_state.subscriptions,
28✔
UNCOV
819
    FullSubscriptions = SubState#pubsub_state.subscriptions,
28✔
UNCOV
820
    Whitelisted = can_fetch_item(Affiliation, BareSubscriptions) orelse
28✔
UNCOV
821
                  can_fetch_item(Affiliation, FullSubscriptions),
10✔
UNCOV
822
    if %%SubId == "", ?? ->
28✔
823
        %% Entity has multiple subscriptions to the node but does not specify a subscription ID
824
        %{error, mod_pubsub:extended_error(xmpp:err_bad_request(), "subid-required")};
825
        %%InvalidSubId ->
826
        %% Entity is subscribed but specifies an invalid subscription ID
827
        %{error, mod_pubsub:extended_error(?ERR_NOT_ACCEPTABLE, "invalid-subid")};
828
        (Affiliation == outcast) or (Affiliation == publish_only) ->
UNCOV
829
            {error, xmpp:err_forbidden()};
4✔
830
        (AccessModel == presence) and not PresenceSubscription ->
831
            {error,
×
832
                mod_pubsub:extended_error((xmpp:err_not_authorized()), mod_pubsub:err_presence_subscription_required())};
833
        (AccessModel == roster) and not RosterGroup ->
834
            {error,
×
835
                mod_pubsub:extended_error((xmpp:err_not_authorized()), mod_pubsub:err_not_in_roster_group())};
836
        (AccessModel == whitelist) and not Whitelisted ->
837
            {error,
×
838
                mod_pubsub:extended_error((xmpp:err_not_allowed()), mod_pubsub:err_closed_node())};
839
        (AccessModel == authorize) and not Whitelisted ->
840
            {error, xmpp:err_forbidden()};
×
841
        %%MustPay ->
842
        %%        % Payment is required for a subscription
843
        %%        {error, ?ERR_PAYMENT_REQUIRED};
844
        true ->
UNCOV
845
            get_items(Nidx, JID, RSM)
24✔
846
    end.
847

848
extract_sublist(A, Now, Index, [#pubsub_item{creation = {Creation, _}} | RItems])
849
  when ((A == before_now) and (Creation >= Now))
850
    or ((A == after_now) and (Creation =< Now)) ->
851
    extract_sublist(A, Now, Index+1, RItems);
×
852
extract_sublist(_, _, Index, RItems) ->
853
    {Index, RItems}.
×
854

855
get_only_item(Nidx, From) ->
UNCOV
856
    get_last_items(Nidx, From, 1).
2✔
857

858
get_last_items(Nidx, _From, Count) when Count > 0 ->
UNCOV
859
    Items = mnesia:index_read(pubsub_item, Nidx, #pubsub_item.nodeidx),
22✔
UNCOV
860
    LastItems = lists:reverse(lists:keysort(#pubsub_item.modification, Items)),
22✔
UNCOV
861
    {result, lists:sublist(LastItems, Count)};
22✔
862
get_last_items(_Nidx, _From, _Count) ->
863
    {result, []}.
×
864

865
%% @doc <p>Returns an item (one item list), given its reference.</p>
866

867
get_item(Nidx, ItemId) ->
UNCOV
868
    case mnesia:read({pubsub_item, {ItemId, Nidx}}) of
68✔
UNCOV
869
        [Item] when is_record(Item, pubsub_item) -> {result, Item};
2✔
UNCOV
870
        _ -> {error, xmpp:err_item_not_found()}
66✔
871
    end.
872

873
get_item(Nidx, ItemId, JID, AccessModel, PresenceSubscription, RosterGroup, _SubId) ->
874
    SubKey = jid:tolower(JID),
×
875
    GenKey = jid:remove_resource(SubKey),
×
876
    GenState = get_state(Nidx, GenKey),
×
877
    Affiliation = GenState#pubsub_state.affiliation,
×
878
    Subscriptions = GenState#pubsub_state.subscriptions,
×
879
    Whitelisted = can_fetch_item(Affiliation, Subscriptions),
×
880
    if %%SubId == "", ?? ->
×
881
        %% Entity has multiple subscriptions to the node but does not specify a subscription ID
882
        %{error, mod_pubsub:extended_error(xmpp:err_bad_request(), "subid-required")};
883
        %%InvalidSubId ->
884
        %% Entity is subscribed but specifies an invalid subscription ID
885
        %{error, mod_pubsub:extended_error(?ERR_NOT_ACCEPTABLE, "invalid-subid")};
886
        (Affiliation == outcast) or (Affiliation == publish_only) ->
887
            {error, xmpp:err_forbidden()};
×
888
        (AccessModel == presence) and not PresenceSubscription ->
889
            {error,
×
890
                mod_pubsub:extended_error((xmpp:err_not_authorized()), mod_pubsub:err_presence_subscription_required())};
891
        (AccessModel == roster) and not RosterGroup ->
892
            {error,
×
893
                mod_pubsub:extended_error((xmpp:err_not_authorized()), mod_pubsub:err_not_in_roster_group())};
894
        (AccessModel == whitelist) and not Whitelisted ->
895
            {error,
×
896
                mod_pubsub:extended_error((xmpp:err_not_allowed()), mod_pubsub:err_closed_node())};
897
        (AccessModel == authorize) and not Whitelisted ->
898
            {error, xmpp:err_forbidden()};
×
899
        %%MustPay ->
900
        %%        % Payment is required for a subscription
901
        %%        {error, ?ERR_PAYMENT_REQUIRED};
902
        true ->
903
            get_item(Nidx, ItemId)
×
904
    end.
905

906
%% @doc <p>Write an item into database.</p>
907
set_item(Item) when is_record(Item, pubsub_item) ->
UNCOV
908
    mnesia:write(Item).
68✔
909
%set_item(_) -> {error, ?ERR_INTERNAL_SERVER_ERROR}.
910

911
%% @doc <p>Delete an item from database.</p>
912
del_item(Nidx, ItemId) ->
UNCOV
913
    mnesia:delete({pubsub_item, {ItemId, Nidx}}).
66✔
914

915
del_items(Nidx, ItemIds) ->
UNCOV
916
    lists:foreach(fun (ItemId) -> del_item(Nidx, ItemId)
168✔
917
        end,
918
        ItemIds).
919

920
del_orphan_items(Nidx) ->
UNCOV
921
    case mnesia:read({pubsub_orphan, Nidx}) of
72✔
922
        [#pubsub_orphan{items = ItemIds}] ->
923
            del_items(Nidx, ItemIds),
×
924
            mnesia:delete({pubsub_orphan, Nidx});
×
925
        _ ->
UNCOV
926
            ok
72✔
927
    end.
928

929
get_item_name(_Host, _Node, Id) ->
930
    {result, Id}.
×
931

932
%% @doc <p>Return the path of the node. In flat it's just node id.</p>
933
node_to_path(Node) ->
UNCOV
934
    {result, [Node]}.
438✔
935

936
path_to_node(Path) ->
937
    {result,
×
938
     case Path of
939
         %% default slot
940
         [Node] -> iolist_to_binary(Node);
×
941
         %% handle old possible entries, used when migrating database content to new format
942
         [Node | _] when is_binary(Node) ->
943
             iolist_to_binary(str:join([<<"">> | Path], <<"/">>));
×
944
         %% default case (used by PEP for example)
945
         _ -> iolist_to_binary(Path)
×
946
     end}.
947

UNCOV
948
can_fetch_item(owner, _) -> true;
56✔
UNCOV
949
can_fetch_item(member, _) -> true;
8✔
UNCOV
950
can_fetch_item(publisher, _) -> true;
8✔
UNCOV
951
can_fetch_item(publish_only, _) -> false;
10✔
UNCOV
952
can_fetch_item(outcast, _) -> false;
10✔
UNCOV
953
can_fetch_item(none, Subscriptions) -> is_subscribed(Subscriptions).
18✔
954
%can_fetch_item(_Affiliation, _Subscription) -> false.
955

956
is_subscribed(Subscriptions) ->
UNCOV
957
    lists:any(fun
18✔
958
            ({subscribed, _SubId}) -> true;
×
959
            (_) -> false
×
960
        end,
961
        Subscriptions).
962

963
first_in_list(_Pred, []) ->
964
    false;
×
965
first_in_list(Pred, [H | T]) ->
966
    case Pred(H) of
×
967
        true -> {value, H};
×
968
        _ -> first_in_list(Pred, T)
×
969
    end.
970

971
rsm_page(Count, _, _, []) ->
972
    #rsm_set{count = Count};
×
973
rsm_page(Count, Index, Offset, Items) ->
974
    FirstItem = hd(Items),
×
975
    LastItem = lists:last(Items),
×
976
    First = decode_stamp(element(1, FirstItem#pubsub_item.creation)),
×
977
    Last = decode_stamp(element(1, LastItem#pubsub_item.creation)),
×
978
    #rsm_set{count = Count, index = Index,
×
979
             first = #rsm_first{index = Offset, data = First},
980
             last = Last}.
981

982
encode_stamp(Stamp) ->
983
    try xmpp_util:decode_timestamp(Stamp)
×
984
    catch _:{bad_timestamp, _} ->
985
            Stamp % We should return a proper error to the client instead.
×
986
    end.
987
decode_stamp(Stamp) ->
988
    xmpp_util:encode_timestamp(Stamp).
×
989

990
transform({pubsub_state, {Id, Nidx}, Is, A, Ss}) ->
991
    {pubsub_state, {Id, Nidx}, Nidx, Is, A, Ss};
×
992
transform({pubsub_item, {Id, Nidx}, C, M, P}) ->
993
    {pubsub_item, {Id, Nidx}, Nidx, C, M, P};
×
994
transform(Rec) ->
995
    Rec.
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc