Group.pm.in 24.3 KB
Newer Older
1
2
3
#!/usr/bin/perl -wT
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2005, 2006, 2007 University of Utah and the Flux Group.
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# All rights reserved.
#
package Group;

use strict;
use Exporter;
use vars qw(@ISA @EXPORT);

@ISA    = "Exporter";
@EXPORT = qw ( );

# Must come after package declaration!
use lib '@prefix@/lib';
use libdb;
use libtestbed;
20
use User;
21
22
23
24
use English;
use Data::Dumper;
use File::Basename;
use overload ('""' => 'Stringify');
25
use vars qw($MEMBERLIST_FLAGS_UIDSONLY $MEMBERLIST_FLAGS_ALLUSERS);
26
27

# Configure variables
28
29
30
31
32
33
34
35
36
my $TB		  = "@prefix@";
my $BOSSNODE      = "@BOSSNODE@";
my $CONTROL	  = "@USERNODE@";
my $TBOPS         = "@TBOPSEMAIL@";
my $TBAPPROVAL    = "@TBAPPROVALEMAIL@";
my $TBAUDIT       = "@TBAUDITEMAIL@";
my $TBBASE        = "@TBBASE@";
my $TBWWW         = "@TBWWW@";
my $MIN_UNIX_GID  = @MIN_UNIX_GID@;
37
38
39
40
41

# Cache of instances to avoid regenerating them.
my %groups    = ();
my $debug      = 0;

42
43
44
45
# MemberList flags.
$MEMBERLIST_FLAGS_UIDSONLY	= 0x01;
$MEMBERLIST_FLAGS_ALLUSERS	= 0x02;

46
47
48
49
50
51
52
53
54
55
56
57
58
# Little helper and debug function.
sub mysystem($)
{
    my ($command) = @_;

    print STDERR "Running '$command'\n"
	if ($debug);
    return system($command);
}

#
# Lookup by idx.
#
59
sub Lookup($$;$)
60
{
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
    my ($class, $arg1, $arg2) = @_;
    my $gid_idx;

    #
    # A single arg is either an index or a "pid,gid" or "pid/gid" string.
    #
    if (!defined($arg2)) {
	if ($arg1 =~ /^(\d*)$/) {
	    $gid_idx = $1;
	}
	elsif ($arg1 =~ /^([-\w]*),([-\w]*)$/ ||
	       $arg1 =~ /^([-\w]*)\/([-\w]*)$/) {
	    $arg1 = $1;
	    $arg2 = $2;
	}
	else {
	    return undef;
	}
    }
    elsif (! (($arg1 =~ /^[-\w]*$/) && ($arg2 =~ /^[-\w]*$/))) {
	return undef;
    }

    #
    # Two args means pid/gid lookup instead of gid_idx.
    #
    if (defined($arg2)) {
	my $groups_result =
	    DBQueryWarn("select gid_idx from groups ".
			"where pid='$arg1' and gid='$arg2'");

	return undef
	    if (! $groups_result || !$groups_result->numrows);

	($gid_idx) = $groups_result->fetchrow_array();
    }
97
98
99
100
101
102

    # Look in cache first
    return $groups{"$gid_idx"}
        if (exists($groups{"$gid_idx"}));
    
    my $query_result =
103
	DBQueryWarn("select * from groups where gid_idx='$gid_idx'");
104
105
106
107

    return undef
	if (!$query_result || !$query_result->numrows);

108
109
110
    my $self           = {};
    $self->{'GROUP'}   = $query_result->fetchrow_hashref();
    $self->{'PROJECT'} = undef;
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125

    bless($self, $class);
    
    # Add to cache. 
    $groups{"$gid_idx"} = $self;
    
    return $self;
}
# accessors
sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'GROUP'}->{$_[1]}); }
sub pid($)	        { return field($_[0], "pid"); }
sub gid($)	        { return field($_[0], "gid"); }
sub pid_idx($)          { return field($_[0], "pid_idx"); }
sub gid_idx($)          { return field($_[0], "gid_idx"); }
sub leader($)           { return field($_[0], "leader"); }
126
sub leader_idx($)       { return field($_[0], "leader_idx"); }
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
sub created($)          { return field($_[0], "created"); }
sub description($)      { return field($_[0], "description"); }
sub unix_gid($)         { return field($_[0], "unix_gid"); }
sub unix_name($)        { return field($_[0], "unix_name"); }
sub expt_count($)       { return field($_[0], "expt_count"); }
sub expt_last($)        { return field($_[0], "expt_last"); }
sub wikiname($)         { return field($_[0], "wikiname"); }
sub mailman_password($) { return field($_[0], "mailman_password"); }

#
# Lookup given pid/gid. For backwards compat.
#
sub LookupByPidGid($$$)
{
    my ($class, $pid, $gid) = @_;

143
    return Group->Lookup($pid, $gid);
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
}

#
# Refresh a class instance by reloading from the DB.
#
sub Refresh($)
{
    my ($self) = @_;

    return -1
	if (! ref($self));

    my $gid_idx = $self->gid_idx();
    
    my $query_result =
	DBQueryWarn("select * from groups where gid_idx=$gid_idx");

    return -1
	if (!$query_result || !$query_result->numrows);

    $self->{'GROUP'} = $query_result->fetchrow_hashref();

    return 0;
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $pid     = $self->pid();
    my $gid     = $self->gid();
    my $gid_idx = $self->gid_idx();
    my $pid_idx = $self->pid_idx();

    return "[Group: $pid/$gid, IDX: $pid_idx/$gid_idx]";
}

#
# Perform some updates ...
#
sub Update($$)
{
    my ($self, $argref) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $gid_idx = $self->gid_idx();

    my $query = "update groups set ".
	join(",", map("$_='" . $argref->{$_} . "'", keys(%{$argref})));

    $query .= " where gid_idx='$gid_idx'";

    return -1
	if (! DBQueryWarn($query));

    return Refresh($self);
}

208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
#
# Class function to create new group and return object.
#
sub Create($$$$$$)
{
    my ($class, $project, $gid, $leader, $description, $unix_name) = @_;
    my $pid;
    my $pid_idx;
    
    #
    # Check that we can guarantee uniqueness of the unix group name.
    # 
    my $query_result =
	DBQueryFatal("select gid from groups ".
		     "where unix_name='$unix_name'");

    if ($query_result->numrows) {
	print "*** Could not form a unique Unix group name: $unix_name!\n";
	return undef;
    }

    # Every group gets a new unique index.
    my $gid_idx = TBGetUniqueIndex('next_gid');

    # If project is not defined, then creating initial project group.
    if (! $project) {
	$pid = $gid;
	$pid_idx = $gid_idx;
    }
    else {
	$pid = $project->pid();
	$pid_idx = $project->pid_idx();
    }

    #
    # Get me an unused unix gid. 
    #
    my $unix_gid;

    #
    # Start here, and keep going if the one picked from the DB just
    # happens to be in use (in the group file). Actually happens!
    #
    my $min_gid = $MIN_UNIX_GID;
    
    while (! defined($unix_gid)) {
	#
	# Get me an unused unix id. Nice query, eh? Basically, find
	# unused numbers by looking at existing numbers plus one, and
	# check to see if that number is taken.
	#
	$query_result =
	    DBQueryWarn("select g.unix_gid + 1 as start from groups as g ".
			"left outer join groups as r on ".
			"  g.unix_gid + 1 = r.unix_gid ".
263
			"where g.unix_gid>=$min_gid and ".
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
			"      g.unix_gid<50000 and ".
			"      r.unix_gid is null limit 1");

	return undef
	    if (! $query_result);

	if (! $query_result->numrows) {
	    print "*** WARNING: Could not find an unused unix_gid!\n";
	    return undef;
	}

	my ($unused) = $query_result->fetchrow_array();

	if (getgrgid($unused)) {
	    # Keep going.
	    $min_gid++;
	}
	else {
	    # Break out of loop.
	    $unix_gid = $unused;
	}
    }

287
288
289
290
291
292
293
    # And a UUID (universally unique identifier).
    my $uuid = NewUUID();
    if (!defined($uuid)) {
	print "*** WARNING: Could not generate a UUID!\n";
	return undef;
    }

294
295
296
297
298
299
300
    if (!DBQueryWarn("insert into groups set ".
		     " pid='$pid', gid='$gid', ".
		     " leader='" . $leader->uid() . "'," .
		     " leader_idx='" . $leader->uid_idx() . "'," .
		     " created=now(), ".
		     " description='$description', ".
		     " unix_name='$unix_name', ".
301
		     " gid_uuid='$uuid', ".
302
303
304
305
306
307
		     " gid_idx=$gid_idx, ".
		     " pid_idx=$pid_idx, ".
		     " unix_gid=$unix_gid")) {
	return undef;
    }

308
309
310
    if (! DBQueryWarn("insert into group_stats ".
		      "  (pid, gid, gid_idx, pid_idx, gid_uuid) ".
		      "values ('$pid','$gid',$gid_idx,$pid_idx,'$uuid')")) {
311
312
313
314
315
316
317
318
319
320
321
	DBQueryFatal("delete from groups where gid_idx='$gid_idx'");
	return undef;
    }
    my $newgroup = Group->Lookup($gid_idx);
    return undef
	if (! $newgroup);

    return $newgroup;
}

#
322
# Delete a group. This will eventually change to group archival.
323
324
325
326
327
328
329
330
331
332
333
#
sub Delete($)
{
    my ($self) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $gid_idx = $self->gid_idx();

334
335
336
337
338
339
340
341
    # Order matters, groups table should be last so we can repeat if failure.
    my @tables = ("group_policies", "group_stats", "groups");

    foreach my $table (@tables) {
	return -1
	    if (!DBQueryWarn("delete from $table where gid_idx='$gid_idx'"));
    }
    
342
343
344
    return 0;
}

345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#
# Generic function to look up some table values given a set of desired
# fields and some conditions. Pretty simple, not widely useful, but it
# helps to avoid spreading queries around then we need to. 
#
sub TableLookUp($$$;$)
{
    my ($self, $table, $fields, $conditions) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));
    
    my $gid_idx = $self->gid_idx();

    if (defined($conditions) && "$conditions" ne "") {
	$conditions = "and ($conditions)";
    }
    else {
	$conditions = "";
    }

    return DBQueryWarn("select distinct $fields from $table ".
		       "where gid_idx='$gid_idx' $conditions");
}

#
# Ditto for update.
#
sub TableUpdate($$$;$)
{
    my ($self, $table, $sets, $conditions) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    if (ref($sets) eq "HASH") {
	$sets = join(",", map("$_='" . $sets->{$_} . "'", keys(%{$sets})));
    }
    my $gid_idx = $self->gid_idx();

    if (defined($conditions) && "$conditions" ne "") {
	$conditions = "and ($conditions)";
    }
    else {
	$conditions = "";
    }

    return 0
	if (DBQueryWarn("update $table set $sets ".
			"where gid_idx='$gid_idx' $conditions"));
    return -1;
}

#
# Check permissions.
#
sub AccessCheck($$$)
{
    my ($self, $user, $access_type) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $uid = (ref($user) ? $user->uid() : $user);
    my $pid = $self->pid();
    my $gid = $self->gid();

    return TBProjAccessCheck($uid, $pid, $gid, $access_type);
}

418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
#
# Change the leader for a group.
#
sub ChangeLeader($$)
{
    my ($self, $leader) = @_;

    # Must be a real reference. 
    return -1
	if (! (ref($self) && ref($leader)));

    my %args = ();
    $args{'leader'}     = $leader->uid();
    $args{'leader_idx'} = $leader->uid_idx();
    return $self->Update(\%args);
}

435
436
437
438
439
440
441
442
443
444
445
#
# Add a user to the group
#
sub AddMemberShip($$;$)
{
    my ($self, $user, $trust) = @_;

    # Must be a real reference. 
    return -1
	if (! (ref($self) && ref($user)));

446
447
448
449
450
451
    my $membership = $self->LookupUser($user);

    if (defined($membership)) {
	print "*** AddMemberShip: $user is already a member of $self!\n";
	return -1;
    }
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
    return Group::MemberShip->NewMemberShip($self, $user, $trust);
}

#
# Remove a user from a group
#
sub DeleteMemberShip($$)
{
    my ($self, $user) = @_;

    # Must be a real reference. 
    return -1
	if (! (ref($self) && ref($user)));

    return Group::MemberShip->DeleteMemberShip($self, $user);
}

469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
#
# Send email notification of user joining a group.
#
sub SendJoinEmail($$)
{
    my ($self, $user) = @_;

    # Must be a real reference. 
    return -1
	if (! (ref($self) && ref($user)));

    #
    # Grab user info.
    #
    my $usr_email   = $user->email();
    my $usr_URL     = $user->URL();
    my $usr_addr    = $user->addr();
    my $usr_addr2   = $user->addr2();
    my $usr_city    = $user->city();
    my $usr_state   = $user->state();
    my $usr_zip	    = $user->zip();
    my $usr_country = $user->country();
    my $usr_name    = $user->name();
    my $usr_phone   = $user->phone();
    my $usr_title   = $user->title();
    my $usr_affil   = $user->affil();
    my $uid_idx     = $user->uid_idx();
    my $uid         = $user->uid();

    # And leader info
    my $leader      = $self->GetLeader();
    my $leader_name = $leader->name();
    my $leader_email= $leader->email();
    my $leader_uid  = $leader->uid();
    my $allleaders  = $self->LeaderMailList();
    my $pid         = $self->pid();
    my $gid         = $self->gid();
506
507
508
509
510
511

    $usr_addr2 = ""
	if (!defined($usr_addr2));
    $usr_URL = ""
	if (!defined($usr_URL));

512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
    SENDMAIL("$leader_name '$leader_uid' <$leader_email>",
	     "$uid $pid Project Join Request",
	     "$usr_name is trying to join your group $gid in project $pid.".
	     "\n".
	     "\n".
	     "Contact Info:\n".
	     "Name:            $usr_name\n".
	     "Emulab ID:       $uid\n".
	     "Email:           $usr_email\n".
	     "User URL:        $usr_URL\n".
	     "Job Title:       $usr_title\n".
	     "Affiliation:     $usr_affil\n".
	     "Address 1:       $usr_addr\n".
	     "Address 2:       $usr_addr2\n".
	     "City:            $usr_city\n".
	     "State:           $usr_state\n".
	     "ZIP/Postal Code: $usr_zip\n".
	     "Country:         $usr_country\n".
	     "Phone:           $usr_phone\n".
	     "\n".
	     "Please return to $TBWWW,\n".
	     "log in, select the 'New User Approval' page, and enter your\n".
	     "decision regarding $usr_name's membership in your project.\n".
	     "\n".
	     "Thanks,\n".
	     "Testbed Operations\n",
	     "$TBAPPROVAL",
	     "CC: $allleaders\n".
	     "Bcc: $TBAUDIT");

    return 0;
}

545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
#
# Send email notifying of initial approval testbed approval in a group.
#
sub SendApprovalEmail($$$)
{
    my ($self, $this_user, $target_user) = @_;

    # Must be a real reference. 
    return -1
	if (! (ref($self) && ref($this_user) && ref($target_user)));

    my $usr_email   = $target_user->email();
    my $usr_name    = $target_user->name();
    my $usr_uid     = $target_user->uid();
    my $this_name   = $this_user->name();
    my $this_email  = $this_user->email();
    my $pid         = $self->pid();
    my $gid         = $self->gid();
    my $allleaders  = $self->LeaderMailList();
    my $membership  = $self->LookupUser($target_user);

    return -1
	if (!defined($membership));

    my $trust = $membership->trust();

    SENDMAIL("$usr_name '$usr_uid' <$usr_email>",
             "Membership Approved in '$pid/$gid' ",
	     "\n".
	     "This message is to notify you that you have been approved as\n".
	     "a member of $pid/$gid with '$trust' permission.\n".
             "\n\n".
             "Thanks,\n".
             "Testbed Operations\n",
             "$this_name <$this_email>",
	     "CC: $allleaders\n".
	     "Bcc: $TBAUDIT");

    return 0;
}

sub SendTrustChangeEmail($$$)
{
    my ($self, $this_user, $target_user) = @_;

    # Must be a real reference. 
    return -1
	if (! (ref($self) && ref($this_user) && ref($target_user)));

    my $usr_email   = $target_user->email();
    my $usr_name    = $target_user->name();
    my $usr_uid     = $target_user->uid();
    my $this_name   = $this_user->name();
    my $this_email  = $this_user->email();
    my $pid         = $self->pid();
    my $gid         = $self->gid();
    my $allleaders  = $self->LeaderMailList();
    my $membership  = $self->LookupUser($target_user);

    return -1
	if (!defined($membership));

    my $trust = $membership->trust();

    SENDMAIL("$usr_name '$usr_uid' <$usr_email>",
             "Membership Change in '$pid/$gid' ",
	     "\n".
	     "This message is to notify you that your permission in $pid/$gid".
	     "\n".
	     "has been changed to '$trust'\n".
             "\n\n".
             "Thanks,\n".
             "Testbed Operations\n",
             "$this_name <$this_email>",
	     "CC: $allleaders\n".
	     "Bcc: $TBAUDIT");

    return 0;
}

625
626
627
628
629
630
631
#
# Lookup user membership in this group
#
sub LookupUser($$)
{
    my ($self, $user) = @_;

632
633
634
635
    # Must be a real reference. 
    return undef
	if (! (ref($self) && ref($user)));

636
637
638
    return Group::MemberShip->LookupUser($self, $user);
}

639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
#
# Is this group the default project group. Returns boolean.
#
sub IsProjectGroup($)
{
    my ($self) = @_;

    # Must be a real reference. 
    return 0
	if (! ref($self));

    return $self->pid_idx() == $self->gid_idx();
}

#
# Return (and cache) the project for a group.
#
sub GetProject($)
{
    my ($self) = @_;

    # Must be a real reference. 
    return undef
	if (! ref($self));

    return $self->{'PROJECT'}
        if (defined($self->{'PROJECT'}));

    $self->{'PROJECT'} = Project->Lookup($self->pid_idx());
    return $self->{'PROJECT'};
}

#
# Is the user the group leader.
#
sub IsLeader($$)
{
    my ($self, $user) = @_;

    # Must be a real reference. 
    return 0
	if (! (ref($self) && ref($user)));

    return $self->leader_idx() == $user->uid_idx();
}

#
# Return user object for leader.
#
sub GetLeader($)
{
    my ($self) = @_;

    # Must be a real reference. 
    return undef
	if (! ref($self));

    return User->Lookup($self->leader_idx());
}

#
# Return a list of leaders (proj/group roots) in the format of an
# email address list.
#
sub LeaderMailList($)
{
    my ($self) = @_;

    # Must be a real reference. 
    return undef
	if (! ref($self));

    my $gid_idx   = $self->gid_idx();
    my $projroot  = $Group::MemberShip::TRUSTSTRING_PROJROOT;
    my $grouproot = $Group::MemberShip::TRUSTSTRING_GROUPROOT;
    my $mailstr   = "";
    
    my $query_result =
	DBQueryFatal("select distinct usr_name,u.uid,usr_email ".
		     "  from users as u ".
		     "left join group_membership as gm on ".
		     "     gm.uid_idx=u.uid_idx ".
		     "where gid_idx='$gid_idx' and ".
		     "      (trust='$projroot' or trust='$grouproot') ".
		     "order by trust DESC, usr_name");

    while (my ($name,$uid,$email) = $query_result->fetchrow_array()) {
	$mailstr .= ", "
	    if ($mailstr ne "");

	$mailstr .= '"' . $name . " (". $uid . ")\" <". $email . ">";
    }
    return $mailstr;
}

734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
#
# Return list of members in this group, by specific trust.
#

sub MemberList($$;$$)
{
    my ($self, $prval, $flags, $desired_trust) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    $flags = 0
	if (!defined($flags));

    my $gid_idx    = $self->gid_idx();
    my $pid_idx    = $self->pid_idx();
    my @result     = ();
    my $uids_only  = ($flags & $MEMBERLIST_FLAGS_UIDSONLY ? 1 : 0);
    my $trust_clause;

    if (defined($desired_trust)) {
	$trust_clause = "and trust='$desired_trust'"
    }
    elsif ($flags & $MEMBERLIST_FLAGS_ALLUSERS) {
	$trust_clause = "";
    }
    else {
	$trust_clause = "and trust!='none'"
    }

    my $query_result =
766
	DBQueryWarn("select distinct m.uid_idx,m.uid ".
767
768
769
770
771
772
		    "   from group_membership as m ".
		    "where m.pid_idx='$pid_idx' and ".
		    "      m.gid_idx='$gid_idx' $trust_clause");

    return -1
	if (!$query_result);
773

774
    while (my ($uid_idx, $uid) = $query_result->fetchrow_array()) {
775
	if ($uids_only) {
776
	    push(@result, $uid);
777
778
779
780
781
782
783
784
785
786
787
788
789
	    next;
	}
	
	my $user = User->Lookup($uid_idx);
	if (!defined($user)) {
	    print "Group::Memberlist: Could not map $uid_idx to object\n";
	    return undef;
	}
	push(@result, $user);
    }
    @$prval = @result;
    return 0;
}
790

791
792
793
794
795
796
797
############################################################################

package Group::MemberShip;
use libdb;
use libtestbed;
use English;
use overload ('""' => 'Stringify');
798
799
800
801
use vars qw($TRUSTSTRING_NONE $TRUSTSTRING_USER
	    $TRUSTSTRING_LOCALROOT $TRUSTSTRING_GROUPROOT
	    $TRUSTSTRING_PROJROOT
	    @EXPORT_OK);
802
803

# Constants for membership.
804
805
806
807
808
809
810
811
812
813
$TRUSTSTRING_NONE		= "none";
$TRUSTSTRING_USER		= "user";
$TRUSTSTRING_LOCALROOT		= "local_root";
$TRUSTSTRING_GROUPROOT		= "group_root";
$TRUSTSTRING_PROJROOT		= "project_root";

# Why, why, why?
@EXPORT_OK = qw($TRUSTSTRING_NONE $TRUSTSTRING_USER
		$TRUSTSTRING_LOCALROOT $TRUSTSTRING_GROUPROOT
		$TRUSTSTRING_PROJROOT);
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048

my @alltrustvals = ($TRUSTSTRING_NONE, $TRUSTSTRING_USER,
		    $TRUSTSTRING_LOCALROOT, $TRUSTSTRING_GROUPROOT,
		    $TRUSTSTRING_PROJROOT);

# Cache of instances to avoid regenerating them.
my %membership = ();

#
# Lookup user membership in a group. Group and User are references. Hmm ...
#
sub LookupUser($$$)
{
    my ($class, $group, $user) = @_;

    # Must be a real reference. 
    return -1
	if (! (ref($group) && ref($user)));

    my $pid_idx = $group->pid_idx();
    my $gid_idx = $group->gid_idx();
    my $uid_idx = $user->uid_idx();

    # Look in cache first
    return $membership{"$uid_idx:$gid_idx"}
        if (exists($membership{"$uid_idx:$gid_idx"}));
    
    my $query_result =
	DBQueryWarn("select * from group_membership ".
		    "where uid_idx=$uid_idx and gid_idx=$gid_idx");

    return undef
	if (!$query_result || !$query_result->numrows);

    my $self              = {};
    $self->{'MEMBERSHIP'} = $query_result->fetchrow_hashref();
    $self->{'GROUP'}      = $group;
    $self->{'USER'}       = $user;

    bless($self, $class);
    
    # Add to cache. 
    $membership{"$uid_idx:$gid_idx"} = $self;
    
    return $self;
}
# accessors
sub field($$) { return ((! ref($_[0])) ? -1 : $_[0]->{'MEMBERSHIP'}->{$_[1]});}
sub uid($)	        { return field($_[0], "uid"); }
sub pid($)	        { return field($_[0], "pid"); }
sub gid($)	        { return field($_[0], "gid"); }
sub uid_idx($)          { return field($_[0], "uid_idx"); }
sub pid_idx($)          { return field($_[0], "pid_idx"); }
sub gid_idx($)          { return field($_[0], "gid_idx"); }
sub trust($)            { return field($_[0], "trust"); }
sub date_applied($)     { return field($_[0], "date_applied"); }
sub date_approved($)    { return field($_[0], "date_approved"); }
sub group($)            { return $_[0]->{'group'}; }
sub user($ )            { return $_[0]->{'user'}; }

#
# Refresh a class instance by reloading from the DB.
#
sub Refresh($)
{
    my ($self) = @_;

    return -1
	if (! ref($self));

    my $uid_idx = $self->uid_idx();
    my $gid_idx = $self->gid_idx();

    my $query_result =
	DBQueryWarn("select * from group_membership ".
		    "where uid_idx=$uid_idx and gid_idx=$gid_idx");

    return -1
	if (!$query_result || !$query_result->numrows);

    $self->{'MEMBERSHIP'} = $query_result->fetchrow_hashref();

    return 0;
}

#
# Stringify for output.
#
sub Stringify($)
{
    my ($self) = @_;
    
    my $uid     = $self->uid();
    my $pid     = $self->pid();
    my $gid     = $self->gid();
    my $uid_idx = $self->uid_idx();
    my $pid_idx = $self->pid_idx();
    my $gid_idx = $self->gid_idx();
    my $trust   = $self->trust();

    return "[MemberShip: $uid/$trust/$pid/$gid]";
}

#
# Perform some updates ...
#
sub Update($$)
{
    my ($self, $argref) = @_;

    # Must be a real reference. 
    return -1
	if (! ref($self));

    my $uid_idx = $self->uid_idx();
    my $gid_idx = $self->gid_idx();

    my $query = "update group_membership set ".
	join(",", map("$_='" . $argref->{$_} . "'", keys(%{$argref})));

    $query .= " where gid_idx='$gid_idx' and uid_idx='$uid_idx'";

    return -1
	if (! DBQueryWarn($query));

    return Refresh($self);
}

#
# Create new membership in a group. This is a "class" method.
#
sub NewMemberShip($$$;$)
{
    my ($class, $group, $user, $trust) = @_;
    my $clause = "";
    
    # Must be a real reference. 
    return -1
	if (! (ref($group) && ref($user)));

    my $uid     = $user->uid();
    my $pid     = $group->pid();
    my $gid     = $group->gid();
    my $uid_idx = $user->uid_idx();
    my $pid_idx = $group->pid_idx();
    my $gid_idx = $group->gid_idx();

    $trust = $TRUSTSTRING_NONE
	if (!defined($trust));
    
    # Sanity check.
    if (! grep {$_ eq $trust} @alltrustvals) {
	print STDERR "*** NewMemberShip: Not a valid trust: $trust\n";
	return -1;
    }

    # If current trust is none, then requesting membership.
    $clause = ", date_approved=now() "
	if ($trust ne $TRUSTSTRING_NONE);

    DBQueryWarn("insert into group_membership set ".
		"     uid='$uid', uid_idx=$uid_idx, ".
		"     pid='$pid', pid_idx=$pid_idx, ".
		"     gid='$gid', gid_idx=$gid_idx, ".
		"     trust='$trust', ".
		"     date_applied=now() $clause ")
	or return -1;

    return 0;
}

#
# Delete membership from a group. This is a "class" method.
#
sub DeleteMemberShip($$$)
{
    my ($class, $group, $user) = @_;
    my $clause = "";
    
    # Must be a real reference. 
    return -1
	if (! (ref($group) && ref($user)));

    my $uid     = $user->uid();
    my $pid     = $group->pid();
    my $gid     = $group->gid();
    my $uid_idx = $user->uid_idx();
    my $pid_idx = $group->pid_idx();
    my $gid_idx = $group->gid_idx();

    # Remove from cache.
    delete($membership{"$uid_idx:$gid_idx"})
	if (exists($membership{"$uid_idx:$gid_idx"}));

    DBQueryWarn("delete from group_membership ".
		"where gid_idx='$gid_idx' and uid_idx='$uid_idx'")
	or return -1;

    return 0;
}

#
# Modify a membership trust value.
#
sub ModifyTrust($$)
{
    my ($self, $trust) = @_;
    my $clause = "";

    # Must be a real reference. 
    return -1
	if (! ref($self));

    # Sanity check.
    if (! grep {$_ eq $trust} @alltrustvals) {
	print STDERR "*** ModifyTrust: Not a valid trust: $trust\n";
	return -1;
    }

    my $uid_idx = $self->uid_idx();
    my $gid_idx = $self->gid_idx();

    # If current trust is none, then also update date_approved.
    $clause  = ", date_approved=now() "
	if ($self->trust() eq $TRUSTSTRING_NONE);

    DBQueryWarn("update group_membership set trust='$trust' $clause ".
		"where gid_idx='$gid_idx' and uid_idx='$uid_idx'")
	or return -1;

    return Refresh($self);
}

# _Always_ make sure that this 1 is at the end of the file...
1;