Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1048.2.4

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1048.2.4! raeburn     4: # $Id: lonnet.pm,v 1.1048.2.3 2010/02/26 23:11:33 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA 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
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968     raeburn    79:             $_64bit %env %protocol);
1.871     albertel   80: 
                     81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        84:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        85: 
1.1       albertel   86: use IO::Socket;
1.31      www        87: use GDBM_File;
1.208     albertel   88: use HTML::LCParser;
1.88      www        89: use Fcntl qw(:flock);
1.870     albertel   90: use Storable qw(thaw nfreeze);
1.539     albertel   91: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   92: use Cache::Memcached;
1.676     albertel   93: use Digest::MD5;
1.790     albertel   94: use Math::Random;
1.1024    raeburn    95: use File::MMagic;
1.807     albertel   96: use LONCAPA qw(:DEFAULT :match);
1.740     www        97: use LONCAPA::Configuration;
1.676     albertel   98: 
1.195     www        99: my $readit;
1.550     foxr      100: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  101: 
1.977     amueller  102: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
                    103: 
1.619     albertel  104: require Exporter;
                    105: 
                    106: our @ISA = qw (Exporter);
                    107: our @EXPORT = qw(%env);
                    108: 
1.449     matthew   109: 
1.1       albertel  110: # --------------------------------------------------------------------- Logging
1.729     www       111: {
                    112:     my $logid;
                    113:     sub instructor_log {
1.957     raeburn   114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    115:         if (($cnum eq '') || ($cdom eq '')) {
                    116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    118:         }
1.729     www       119: 	$logid++;
1.957     raeburn   120:         my $now = time();
                    121: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       123: 				    { $id => {
                    124: 					'exe_uname' => $env{'user.name'},
                    125: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   126: 					'exe_time'  => $now,
1.730     www       127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    128: 					'delflag'   => $delflag,
                    129: 					'logentry'  => $storehash,
                    130: 					'uname'     => $uname,
                    131: 					'udom'      => $udom,
                    132: 				    }
1.957     raeburn   133: 				  },$cdom,$cnum);
1.729     www       134:     }
                    135: }
1.1       albertel  136: 
1.163     harris41  137: sub logtouch {
                    138:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  139:     unless (-e "$execdir/logs/lonnet.log") {	
                    140: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  141: 	close $fh;
                    142:     }
                    143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    145: }
                    146: 
1.1       albertel  147: sub logthis {
                    148:     my $message=shift;
                    149:     my $execdir=$perlvar{'lonDaemons'};
                    150:     my $now=time;
                    151:     my $local=localtime($now);
1.448     albertel  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      153: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    154: 	print $fh $logstring;
1.448     albertel  155: 	close($fh);
                    156:     }
1.1       albertel  157:     return 1;
                    158: }
                    159: 
                    160: sub logperm {
                    161:     my $message=shift;
                    162:     my $execdir=$perlvar{'lonDaemons'};
                    163:     my $now=time;
                    164:     my $local=localtime($now);
1.448     albertel  165:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    166: 	print $fh "$now:$message:$local\n";
                    167: 	close($fh);
                    168:     }
1.1       albertel  169:     return 1;
                    170: }
                    171: 
1.850     albertel  172: sub create_connection {
1.853     albertel  173:     my ($hostname,$lonid) = @_;
1.851     albertel  174:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  175: 				     Type    => SOCK_STREAM,
                    176: 				     Timeout => 10);
                    177:     return 0 if (!$client);
1.890     albertel  178:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  179:     my $result = <$client>;
                    180:     chomp($result);
                    181:     return 1 if ($result eq 'done');
                    182:     return 0;
                    183: }
                    184: 
1.983     raeburn   185: sub get_server_timezone {
                    186:     my ($cnum,$cdom) = @_;
                    187:     my $home=&homeserver($cnum,$cdom);
                    188:     if ($home ne 'no_host') {
                    189:         my $cachetime = 24*3600;
                    190:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    191:         if (defined($cached)) {
                    192:             return $timezone;
                    193:         } else {
                    194:             my $timezone = &reply('servertimezone',$home);
                    195:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    196:         }
                    197:     }
                    198: }
1.850     albertel  199: 
1.993     raeburn   200: sub get_server_loncaparev {
                    201:     my ($dom,$lonhost) = @_;
                    202:     if (defined($lonhost)) {
                    203:         if (!defined(&hostname($lonhost))) {
                    204:             undef($lonhost);
                    205:         }
                    206:     }
                    207:     if (!defined($lonhost)) {
                    208:         if (defined(&domain($dom,'primary'))) {
                    209:             $lonhost=&domain($dom,'primary');
                    210:             if ($lonhost eq 'no_host') {
                    211:                 undef($lonhost);
                    212:             }
                    213:         }
                    214:     }
                    215:     if (defined($lonhost)) {
                    216:         my $cachetime = 24*3600;
                    217:         my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    218:         if (defined($cached)) {
                    219:             return $loncaparev;
                    220:         } else {
                    221:             my $loncaparev = &reply('serverloncaparev',$lonhost);
                    222:             return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
                    223:         }
                    224:     }
                    225: }
                    226: 
1.1       albertel  227: # -------------------------------------------------- Non-critical communication
                    228: sub subreply {
                    229:     my ($cmd,$server)=@_;
1.838     albertel  230:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      231:     #
                    232:     #  With loncnew process trimming, there's a timing hole between lonc server
                    233:     #  process exit and the master server picking up the listen on the AF_UNIX
                    234:     #  socket.  In that time interval, a lock file will exist:
                    235: 
                    236:     my $lockfile=$peerfile.".lock";
                    237:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    238: 	sleep(1);
                    239:     }
                    240:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      241:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      242:     #
1.550     foxr      243:     #   We'll give the connection a few tries before abandoning it.  If
                    244:     #   connection is not possible, we'll con_lost back to the client.
                    245:     #   
                    246:     my $client;
                    247:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    248: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    249: 				      Type    => SOCK_STREAM,
                    250: 				      Timeout => 10);
1.869     albertel  251: 	if ($client) {
1.550     foxr      252: 	    last;		# Connected!
1.850     albertel  253: 	} else {
1.853     albertel  254: 	    &create_connection(&hostname($server),$server);
1.550     foxr      255: 	}
1.850     albertel  256:         sleep(1);		# Try again later if failed connection.
1.550     foxr      257:     }
                    258:     my $answer;
                    259:     if ($client) {
1.704     albertel  260: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      261: 	$answer=<$client>;
                    262: 	if (!$answer) { $answer="con_lost"; }
                    263: 	chomp($answer);
                    264:     } else {
                    265: 	$answer = 'con_lost';	# Failed connection.
                    266:     }
1.1       albertel  267:     return $answer;
                    268: }
                    269: 
                    270: sub reply {
                    271:     my ($cmd,$server)=@_;
1.838     albertel  272:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  273:     my $answer=subreply($cmd,$server);
1.65      www       274:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  275:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       276:                 " $cmd to $server returned $answer</font>");
                    277:     }
1.1       albertel  278:     return $answer;
                    279: }
                    280: 
                    281: # ----------------------------------------------------------- Send USR1 to lonc
                    282: 
                    283: sub reconlonc {
1.891     albertel  284:     my ($lonid) = @_;
                    285:     my $hostname = &hostname($lonid);
                    286:     if ($lonid) {
                    287: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    288: 	if ($hostname && -e $peerfile) {
                    289: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    290: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    291: 					     Type    => SOCK_STREAM,
                    292: 					     Timeout => 10);
                    293: 	    if ($client) {
                    294: 		print $client ("reset_retries\n");
                    295: 		my $answer=<$client>;
                    296: 		#reset just this one.
                    297: 	    }
                    298: 	}
                    299: 	return;
                    300:     }
                    301: 
1.836     www       302:     &logthis("Trying to reconnect lonc");
1.1       albertel  303:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  304:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  305: 	my $loncpid=<$fh>;
                    306:         chomp($loncpid);
                    307:         if (kill 0 => $loncpid) {
                    308: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    309:             kill USR1 => $loncpid;
                    310:             sleep 1;
1.836     www       311:          } else {
1.12      www       312: 	    &logthis(
1.672     albertel  313:                "<font color=\"blue\">WARNING:".
1.12      www       314:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  315:         }
                    316:     } else {
1.836     www       317: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  318:     }
                    319: }
                    320: 
                    321: # ------------------------------------------------------ Critical communication
1.12      www       322: 
1.1       albertel  323: sub critical {
                    324:     my ($cmd,$server)=@_;
1.838     albertel  325:     unless (&hostname($server)) {
1.672     albertel  326:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       327:                " Critical message to unknown server ($server)</font>");
                    328:         return 'no_such_host';
                    329:     }
1.1       albertel  330:     my $answer=reply($cmd,$server);
                    331:     if ($answer eq 'con_lost') {
                    332: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  333: 	my $answer=reply($cmd,$server);
1.1       albertel  334:         if ($answer eq 'con_lost') {
                    335:             my $now=time;
                    336:             my $middlename=$cmd;
1.5       www       337:             $middlename=substr($middlename,0,16);
1.1       albertel  338:             $middlename=~s/\W//g;
                    339:             my $dfilename=
1.305     www       340:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    341:             $dumpcount++;
1.1       albertel  342:             {
1.448     albertel  343: 		my $dfh;
                    344: 		if (open($dfh,">$dfilename")) {
                    345: 		    print $dfh "$cmd\n"; 
                    346: 		    close($dfh);
                    347: 		}
1.1       albertel  348:             }
                    349:             sleep 2;
                    350:             my $wcmd='';
                    351:             {
1.448     albertel  352: 		my $dfh;
                    353: 		if (open($dfh,"<$dfilename")) {
                    354: 		    $wcmd=<$dfh>; 
                    355: 		    close($dfh);
                    356: 		}
1.1       albertel  357:             }
                    358:             chomp($wcmd);
1.7       www       359:             if ($wcmd eq $cmd) {
1.672     albertel  360: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       361:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  362:                 &logperm("D:$server:$cmd");
                    363: 	        return 'con_delayed';
                    364:             } else {
1.672     albertel  365:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       366:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  367:                 &logperm("F:$server:$cmd");
                    368:                 return 'con_failed';
                    369:             }
                    370:         }
                    371:     }
                    372:     return $answer;
1.405     albertel  373: }
                    374: 
1.755     albertel  375: # ------------------------------------------- check if return value is an error
                    376: 
                    377: sub error {
                    378:     my ($result) = @_;
1.756     albertel  379:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  380: 	if ($2 == 2) { return undef; }
                    381: 	return $1;
                    382:     }
                    383:     return undef;
                    384: }
                    385: 
1.783     albertel  386: sub convert_and_load_session_env {
                    387:     my ($lonidsdir,$handle)=@_;
                    388:     my @profile;
                    389:     {
1.917     albertel  390: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    391: 	if (!$opened) {
1.915     albertel  392: 	    return 0;
                    393: 	}
1.783     albertel  394: 	flock($idf,LOCK_SH);
                    395: 	@profile=<$idf>;
                    396: 	close($idf);
                    397:     }
                    398:     my %temp_env;
                    399:     foreach my $line (@profile) {
1.786     albertel  400: 	if ($line !~ m/=/) {
                    401: 	    return 0;
                    402: 	}
1.783     albertel  403: 	chomp($line);
                    404: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    405: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    406:     }
                    407:     unlink("$lonidsdir/$handle.id");
                    408:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    409: 	    0640)) {
                    410: 	%disk_env = %temp_env;
                    411: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    412: 	untie(%disk_env);
                    413:     }
1.786     albertel  414:     return 1;
1.783     albertel  415: }
                    416: 
1.374     www       417: # ------------------------------------------- Transfer profile into environment
1.780     albertel  418: my $env_loaded;
                    419: sub transfer_profile_to_env {
1.788     albertel  420:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    421:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       422: 
1.720     albertel  423:     if (!defined($lonidsdir)) {
                    424: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    425:     }
                    426:     if (!defined($handle)) {
                    427:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    428:     }
                    429: 
1.786     albertel  430:     my $convert;
                    431:     {
1.917     albertel  432:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    433: 	if (!$opened) {
1.915     albertel  434: 	    return;
                    435: 	}
1.786     albertel  436: 	flock($idf,LOCK_SH);
                    437: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    438: 		&GDBM_READER(),0640)) {
                    439: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    440: 	    untie(%disk_env);
                    441: 	} else {
                    442: 	    $convert = 1;
                    443: 	}
                    444:     }
                    445:     if ($convert) {
                    446: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    447: 	    &logthis("Failed to load session, or convert session.");
                    448: 	}
1.374     www       449:     }
1.783     albertel  450: 
1.786     albertel  451:     my %remove;
1.783     albertel  452:     while ( my $envname = each(%env) ) {
1.433     matthew   453:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    454:             if ($time < time-300) {
1.783     albertel  455:                 $remove{$key}++;
1.433     matthew   456:             }
                    457:         }
                    458:     }
1.783     albertel  459: 
1.619     albertel  460:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  461:     $env_loaded=1;
1.783     albertel  462:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   463:         &delenv($expired_key);
1.374     www       464:     }
1.1       albertel  465: }
                    466: 
1.916     albertel  467: # ---------------------------------------------------- Check for valid session 
                    468: sub check_for_valid_session {
                    469:     my ($r) = @_;
                    470:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    471:     my $lonid=$cookies{'lonID'};
                    472:     return undef if (!$lonid);
                    473: 
                    474:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    475:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    476:     return undef if (!-e "$lonidsdir/$handle.id");
                    477: 
1.917     albertel  478:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    479:     return undef if (!$opened);
1.916     albertel  480: 
                    481:     flock($idf,LOCK_SH);
                    482:     my %disk_env;
                    483:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    484: 	    &GDBM_READER(),0640)) {
                    485: 	return undef;	
                    486:     }
                    487: 
                    488:     if (!defined($disk_env{'user.name'})
                    489: 	|| !defined($disk_env{'user.domain'})) {
                    490: 	return undef;
                    491:     }
                    492:     return $handle;
                    493: }
                    494: 
1.830     albertel  495: sub timed_flock {
                    496:     my ($file,$lock_type) = @_;
                    497:     my $failed=0;
                    498:     eval {
                    499: 	local $SIG{__DIE__}='DEFAULT';
                    500: 	local $SIG{ALRM}=sub {
                    501: 	    $failed=1;
                    502: 	    die("failed lock");
                    503: 	};
                    504: 	alarm(13);
                    505: 	flock($file,$lock_type);
                    506: 	alarm(0);
                    507:     };
                    508:     if ($failed) {
                    509: 	return undef;
                    510:     } else {
                    511: 	return 1;
                    512:     }
                    513: }
                    514: 
1.5       www       515: # ---------------------------------------------------------- Append Environment
                    516: 
                    517: sub appenv {
1.949     raeburn   518:     my ($newenv,$roles) = @_;
                    519:     if (ref($newenv) eq 'HASH') {
                    520:         foreach my $key (keys(%{$newenv})) {
                    521:             my $refused = 0;
                    522: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    523:                 $refused = 1;
                    524:                 if (ref($roles) eq 'ARRAY') {
                    525:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    526:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    527:                         $refused = 0;
                    528:                     }
                    529:                 }
                    530:             }
                    531:             if ($refused) {
                    532:                 &logthis("<font color=\"blue\">WARNING: ".
                    533:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    534:                          .'</font>');
                    535: 	        delete($newenv->{$key});
                    536:             } else {
                    537:                 $env{$key}=$newenv->{$key};
                    538:             }
                    539:         }
                    540:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    541:         if ($opened
                    542: 	    && &timed_flock($env_file,LOCK_EX)
                    543: 	    &&
                    544: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    545: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    546: 	    while (my ($key,$value) = each(%{$newenv})) {
                    547: 	        $disk_env{$key} = $value;
                    548: 	    }
                    549: 	    untie(%disk_env);
1.35      www       550:         }
1.191     harris41  551:     }
1.56      www       552:     return 'ok';
                    553: }
                    554: # ----------------------------------------------------- Delete from Environment
                    555: 
                    556: sub delenv {
1.987     raeburn   557:     my ($delthis,$regexp) = @_;
1.56      www       558:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  559:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       560:                 "Attempt to delete from environment ".$delthis);
                    561:         return 'error';
                    562:     }
1.917     albertel  563:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    564:     if ($opened
1.915     albertel  565: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  566: 	&&
                    567: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    568: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  569: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   570: 	    if ($regexp) {
                    571:                 if ($key=~/^$delthis/) {
                    572:                     delete($env{$key});
                    573:                     delete($disk_env{$key});
                    574:                 } 
                    575:             } else {
                    576:                 if ($key=~/^\Q$delthis\E/) {
                    577: 		    delete($env{$key});
                    578: 		    delete($disk_env{$key});
                    579: 	        }
                    580:             }
1.448     albertel  581: 	}
1.783     albertel  582: 	untie(%disk_env);
1.5       www       583:     }
                    584:     return 'ok';
1.369     albertel  585: }
                    586: 
1.790     albertel  587: sub get_env_multiple {
                    588:     my ($name) = @_;
                    589:     my @values;
                    590:     if (defined($env{$name})) {
                    591:         # exists is it an array
                    592:         if (ref($env{$name})) {
                    593:             @values=@{ $env{$name} };
                    594:         } else {
                    595:             $values[0]=$env{$name};
                    596:         }
                    597:     }
                    598:     return(@values);
                    599: }
                    600: 
1.958     www       601: # ------------------------------------------------------------------- Locking
                    602: 
                    603: sub set_lock {
                    604:     my ($text)=@_;
                    605:     $locknum++;
                    606:     my $id=$$.'-'.$locknum;
                    607:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    608:              'session.lock.'.$id => $text});
                    609:     return $id;
                    610: }
                    611: 
                    612: sub get_locks {
                    613:     my $num=0;
                    614:     my %texts=();
                    615:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    616:        if ($lock=~/\w/) {
                    617:           $num++;
                    618:           $texts{$lock}=$env{'session.lock.'.$lock};
                    619:        }
                    620:    }
                    621:    return ($num,%texts);
                    622: }
                    623: 
                    624: sub remove_lock {
                    625:     my ($id)=@_;
                    626:     my $newlocks='';
                    627:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    628:        if (($lock=~/\w/) && ($lock ne $id)) {
                    629:           $newlocks.=','.$lock;
                    630:        }
                    631:     }
                    632:     &appenv({'session.locks' => $newlocks});
                    633:     &delenv('session.lock.'.$id);
                    634: }
                    635: 
                    636: sub remove_all_locks {
                    637:     my $activelocks=$env{'session.locks'};
                    638:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    639:        if ($lock=~/\w/) {
                    640:           &remove_lock($lock);
                    641:        }
                    642:     }
                    643: }
                    644: 
                    645: 
1.369     albertel  646: # ------------------------------------------ Find out current server userload
                    647: sub userload {
                    648:     my $numusers=0;
                    649:     {
                    650: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    651: 	my $filename;
                    652: 	my $curtime=time;
                    653: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  654: 	    next if ($filename eq '.' || $filename eq '..');
                    655: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  656: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  657: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  658: 	}
                    659: 	closedir(LONIDS);
                    660:     }
                    661:     my $userloadpercent=0;
                    662:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    663:     if ($maxuserload) {
1.371     albertel  664: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  665:     }
1.372     albertel  666:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  667:     return $userloadpercent;
1.283     www       668: }
                    669: 
                    670: # ------------------------------------------ Fight off request when overloaded
                    671: 
                    672: sub overloaderror {
                    673:     my ($r,$checkserver)=@_;
                    674:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    675:     my $loadavg;
                    676:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  677:        open(my $loadfile,'/proc/loadavg');
1.283     www       678:        $loadavg=<$loadfile>;
                    679:        $loadavg =~ s/\s.*//g;
1.285     matthew   680:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  681:        close($loadfile);
1.283     www       682:     } else {
                    683:        $loadavg=&reply('load',$checkserver);
                    684:     }
1.285     matthew   685:     my $overload=$loadavg-100;
1.283     www       686:     if ($overload>0) {
1.285     matthew   687: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       688:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       689:         return 413;
1.283     www       690:     }    
                    691:     return '';
1.5       www       692: }
1.1       albertel  693: 
                    694: # ------------------------------ Find server with least workload from spare.tab
1.11      www       695: 
1.1       albertel  696: sub spareserver {
1.670     albertel  697:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  698:     my $spare_server;
1.370     albertel  699:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  700:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    701:                                                      :  $userloadpercent;
                    702:     
                    703:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    704: 	($spare_server, $lowest_load) =
                    705: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    706:     }
                    707: 
                    708:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    709: 
                    710:     if (!$found_server) {
                    711: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    712: 	    ($spare_server, $lowest_load) =
                    713: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    714: 	}
                    715:     }
                    716: 
                    717:     if (!$want_server_name) {
1.968     raeburn   718:         my $protocol = 'http';
                    719:         if ($protocol{$spare_server} eq 'https') {
                    720:             $protocol = $protocol{$spare_server};
                    721:         }
1.1001    raeburn   722:         if (defined($spare_server)) {
                    723:             my $hostname = &hostname($spare_server);
                    724:             if (defined($hostname)) {  
                    725: 	        $spare_server = $protocol.'://'.$hostname;
                    726:             }
                    727:         }
1.784     albertel  728:     }
                    729:     return $spare_server;
                    730: }
                    731: 
                    732: sub compare_server_load {
                    733:     my ($try_server, $spare_server, $lowest_load) = @_;
                    734: 
                    735:     my $loadans     = &reply('load',    $try_server);
                    736:     my $userloadans = &reply('userload',$try_server);
                    737: 
                    738:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    739: 	next; #didn't get a number from the server
                    740:     }
                    741: 
                    742:     my $load;
                    743:     if ($loadans =~ /\d/) {
                    744: 	if ($userloadans =~ /\d/) {
                    745: 	    #both are numbers, pick the bigger one
                    746: 	    $load = ($loadans > $userloadans) ? $loadans 
                    747: 		                              : $userloadans;
1.411     albertel  748: 	} else {
1.784     albertel  749: 	    $load = $loadans;
1.411     albertel  750: 	}
1.784     albertel  751:     } else {
                    752: 	$load = $userloadans;
                    753:     }
                    754: 
                    755:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    756: 	$spare_server = $try_server;
                    757: 	$lowest_load  = $load;
1.370     albertel  758:     }
1.784     albertel  759:     return ($spare_server,$lowest_load);
1.202     matthew   760: }
1.914     albertel  761: 
                    762: # --------------------------- ask offload servers if user already has a session
                    763: sub find_existing_session {
                    764:     my ($udom,$uname) = @_;
                    765:     foreach my $try_server (@{ $spareid{'primary'} },
                    766: 			    @{ $spareid{'default'} }) {
                    767: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    768:     }
                    769:     return;
                    770: }
                    771: 
                    772: # -------------------------------- ask if server already has a session for user
                    773: sub has_user_session {
                    774:     my ($lonid,$udom,$uname) = @_;
                    775:     my $result = &reply(join(':','userhassession',
                    776: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    777:     return 1 if ($result eq 'ok');
                    778: 
                    779:     return 0;
                    780: }
                    781: 
1.202     matthew   782: # --------------------------------------------- Try to change a user's password
                    783: 
                    784: sub changepass {
1.799     raeburn   785:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   786:     $currentpass = &escape($currentpass);
                    787:     $newpass     = &escape($newpass);
1.1030    raeburn   788:     my $lonhost = $perlvar{'lonHostID'};
                    789:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   790: 		       $server);
                    791:     if (! $answer) {
                    792: 	&logthis("No reply on password change request to $server ".
                    793: 		 "by $uname in domain $udom.");
                    794:     } elsif ($answer =~ "^ok") {
                    795:         &logthis("$uname in $udom successfully changed their password ".
                    796: 		 "on $server.");
                    797:     } elsif ($answer =~ "^pwchange_failure") {
                    798: 	&logthis("$uname in $udom was unable to change their password ".
                    799: 		 "on $server.  The action was blocked by either lcpasswd ".
                    800: 		 "or pwchange");
                    801:     } elsif ($answer =~ "^non_authorized") {
                    802:         &logthis("$uname in $udom did not get their password correct when ".
                    803: 		 "attempting to change it on $server.");
                    804:     } elsif ($answer =~ "^auth_mode_error") {
                    805:         &logthis("$uname in $udom attempted to change their password despite ".
                    806: 		 "not being locally or internally authenticated on $server.");
                    807:     } elsif ($answer =~ "^unknown_user") {
                    808:         &logthis("$uname in $udom attempted to change their password ".
                    809: 		 "on $server but were unable to because $server is not ".
                    810: 		 "their home server.");
                    811:     } elsif ($answer =~ "^refused") {
                    812: 	&logthis("$server refused to change $uname in $udom password because ".
                    813: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   814:     } elsif ($answer =~ "invalid_client") {
                    815:         &logthis("$server refused to change $uname in $udom password because ".
                    816:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   817:     }
                    818:     return $answer;
1.1       albertel  819: }
                    820: 
1.169     harris41  821: # ----------------------- Try to determine user's current authentication scheme
                    822: 
                    823: sub queryauthenticate {
                    824:     my ($uname,$udom)=@_;
1.456     albertel  825:     my $uhome=&homeserver($uname,$udom);
                    826:     if (!$uhome) {
                    827: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    828: 	return 'no_host';
                    829:     }
                    830:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    831:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    832: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  833:     }
1.456     albertel  834:     return $answer;
1.169     harris41  835: }
                    836: 
1.1       albertel  837: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       838: 
1.1       albertel  839: sub authenticate {
1.952     raeburn   840:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  841:     $upass=&escape($upass);
                    842:     $uname= &LONCAPA::clean_username($uname);
1.836     www       843:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   844:     my $newhome;
1.836     www       845:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    846: # Maybe the machine was offline and only re-appeared again recently?
                    847:         &reconlonc();
                    848: # One more
1.952     raeburn   849: 	$uhome=&homeserver($uname,$udom,1);
                    850:         if (($uhome eq 'no_host') && $checkdefauth) {
                    851:             if (defined(&domain($udom,'primary'))) {
                    852:                 $newhome=&domain($udom,'primary');
                    853:             }
                    854:             if ($newhome ne '') {
                    855:                 $uhome = $newhome;
                    856:             }
                    857:         }
1.836     www       858: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    859: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   860: 	    return 'no_host';
                    861:         }
1.1       albertel  862:     }
1.952     raeburn   863:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  864:     if ($answer eq 'authorized') {
1.952     raeburn   865:         if ($newhome) {
                    866:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    867:             return 'no_account_on_host'; 
                    868:         } else {
                    869:             &logthis("User $uname at $udom authorized by $uhome");
                    870:             return $uhome;
                    871:         }
1.471     albertel  872:     }
                    873:     if ($answer eq 'non_authorized') {
                    874: 	&logthis("User $uname at $udom rejected by $uhome");
                    875: 	return 'no_host'; 
1.9       www       876:     }
1.471     albertel  877:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  878:     return 'no_host';
                    879: }
                    880: 
                    881: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       882: 
1.599     albertel  883: my %homecache;
1.1       albertel  884: sub homeserver {
1.230     stredwic  885:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  886:     my $index="$uname:$udom";
1.426     albertel  887: 
1.599     albertel  888:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  889: 
                    890:     my %servers = &get_servers($udom,'library');
                    891:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  892:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  893: 		 exists($badServerCache{$tryserver}));
1.841     albertel  894: 
                    895: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    896: 	if ($answer eq 'found') {
                    897: 	    delete($badServerCache{$tryserver}); 
                    898: 	    return $homecache{$index}=$tryserver;
                    899: 	} elsif ($answer eq 'no_host') {
                    900: 	    $badServerCache{$tryserver}=1;
                    901: 	}
1.1       albertel  902:     }    
                    903:     return 'no_host';
1.70      www       904: }
                    905: 
                    906: # ------------------------------------- Find the usernames behind a list of IDs
                    907: 
                    908: sub idget {
                    909:     my ($udom,@ids)=@_;
                    910:     my %returnhash=();
                    911:     
1.841     albertel  912:     my %servers = &get_servers($udom,'library');
                    913:     foreach my $tryserver (keys(%servers)) {
                    914: 	my $idlist=join('&',@ids);
                    915: 	$idlist=~tr/A-Z/a-z/; 
                    916: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    917: 	my @answer=();
                    918: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    919: 	    @answer=split(/\&/,$reply);
                    920: 	}                    ;
                    921: 	my $i;
                    922: 	for ($i=0;$i<=$#ids;$i++) {
                    923: 	    if ($answer[$i]) {
                    924: 		$returnhash{$ids[$i]}=$answer[$i];
                    925: 	    } 
                    926: 	}
                    927:     } 
1.70      www       928:     return %returnhash;
                    929: }
                    930: 
                    931: # ------------------------------------- Find the IDs behind a list of usernames
                    932: 
                    933: sub idrget {
                    934:     my ($udom,@unames)=@_;
                    935:     my %returnhash=();
1.800     albertel  936:     foreach my $uname (@unames) {
                    937:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  938:     }
1.70      www       939:     return %returnhash;
                    940: }
                    941: 
                    942: # ------------------------------- Store away a list of names and associated IDs
                    943: 
                    944: sub idput {
                    945:     my ($udom,%ids)=@_;
                    946:     my %servers=();
1.800     albertel  947:     foreach my $uname (keys(%ids)) {
                    948: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    949:         my $uhom=&homeserver($uname,$udom);
1.70      www       950:         if ($uhom ne 'no_host') {
1.800     albertel  951:             my $id=&escape($ids{$uname});
1.70      www       952:             $id=~tr/A-Z/a-z/;
1.800     albertel  953:             my $esc_unam=&escape($uname);
1.70      www       954: 	    if ($servers{$uhom}) {
1.800     albertel  955: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       956:             } else {
1.800     albertel  957:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       958:             }
                    959:         }
1.191     harris41  960:     }
1.800     albertel  961:     foreach my $server (keys(%servers)) {
                    962:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  963:     }
1.344     www       964: }
                    965: 
1.1023    raeburn   966: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn   967: sub dump_dom {
1.1023    raeburn   968:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn   969:     if (!$udom) {
                    970:         $udom=$env{'user.domain'};
                    971:     }
                    972:     my %returnhash;
1.1023    raeburn   973:     if ($udom) {
                    974:         my $uname = &get_domainconfiguser($udom);
                    975:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn   976:     }
                    977:     return %returnhash;
                    978: }
                    979: 
1.1023    raeburn   980: # ------------------------------------------ get items from domain db files   
1.806     raeburn   981: 
                    982: sub get_dom {
1.860     raeburn   983:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   984:     my $items='';
                    985:     foreach my $item (@$storearr) {
                    986:         $items.=&escape($item).'&';
                    987:     }
                    988:     $items=~s/\&$//;
1.860     raeburn   989:     if (!$udom) {
                    990:         $udom=$env{'user.domain'};
                    991:         if (defined(&domain($udom,'primary'))) {
                    992:             $uhome=&domain($udom,'primary');
                    993:         } else {
1.874     albertel  994:             undef($uhome);
1.860     raeburn   995:         }
                    996:     } else {
                    997:         if (!$uhome) {
                    998:             if (defined(&domain($udom,'primary'))) {
                    999:                 $uhome=&domain($udom,'primary');
                   1000:             }
                   1001:         }
                   1002:     }
                   1003:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1004:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1005:         my %returnhash;
1.875     albertel 1006:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1007:             return %returnhash;
                   1008:         }
1.806     raeburn  1009:         my @pairs=split(/\&/,$rep);
                   1010:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1011:             return @pairs;
                   1012:         }
                   1013:         my $i=0;
                   1014:         foreach my $item (@$storearr) {
                   1015:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1016:             $i++;
                   1017:         }
                   1018:         return %returnhash;
                   1019:     } else {
1.880     banghart 1020:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1021:     }
                   1022: }
                   1023: 
                   1024: # -------------------------------------------- put items in domain db files 
                   1025: 
                   1026: sub put_dom {
1.860     raeburn  1027:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1028:     if (!$udom) {
                   1029:         $udom=$env{'user.domain'};
                   1030:         if (defined(&domain($udom,'primary'))) {
                   1031:             $uhome=&domain($udom,'primary');
                   1032:         } else {
1.874     albertel 1033:             undef($uhome);
1.860     raeburn  1034:         }
                   1035:     } else {
                   1036:         if (!$uhome) {
                   1037:             if (defined(&domain($udom,'primary'))) {
                   1038:                 $uhome=&domain($udom,'primary');
                   1039:             }
                   1040:         }
                   1041:     } 
                   1042:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1043:         my $items='';
                   1044:         foreach my $item (keys(%$storehash)) {
                   1045:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1046:         }
                   1047:         $items=~s/\&$//;
                   1048:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1049:     } else {
1.860     raeburn  1050:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1051:     }
                   1052: }
                   1053: 
1.1023    raeburn  1054: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1055: sub newput_dom {
1.1023    raeburn  1056:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1057:     my $result;
                   1058:     if (!$udom) {
                   1059:         $udom=$env{'user.domain'};
                   1060:     }
1.1023    raeburn  1061:     if ($udom) {
                   1062:         my $uname = &get_domainconfiguser($udom);
                   1063:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1064:     }
                   1065:     return $result;
                   1066: }
                   1067: 
1.1023    raeburn  1068: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1069: sub del_dom {
1.1023    raeburn  1070:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1071:     if (ref($storearr) eq 'ARRAY') {
                   1072:         if (!$udom) {
                   1073:             $udom=$env{'user.domain'};
                   1074:         }
1.1023    raeburn  1075:         if ($udom) {
                   1076:             my $uname = &get_domainconfiguser($udom); 
                   1077:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1078:         }
                   1079:     }
                   1080: }
                   1081: 
1.1023    raeburn  1082: # ----------------------------------construct domainconfig user for a domain 
                   1083: sub get_domainconfiguser {
                   1084:     my ($udom) = @_;
                   1085:     return $udom.'-domainconfig';
                   1086: }
                   1087: 
1.837     raeburn  1088: sub retrieve_inst_usertypes {
                   1089:     my ($udom) = @_;
                   1090:     my (%returnhash,@order);
1.989     raeburn  1091:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1092:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1093:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1094:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1095:         @order = @{$domdefs{'inststatusorder'}};
                   1096:     } else {
                   1097:         if (defined(&domain($udom,'primary'))) {
                   1098:             my $uhome=&domain($udom,'primary');
                   1099:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1100:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1101:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1102:                 return (\%returnhash,\@order);
                   1103:             }
                   1104:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1105:             my @pairs=split(/\&/,$hashitems);
                   1106:             foreach my $item (@pairs) {
                   1107:                 my ($key,$value)=split(/=/,$item,2);
                   1108:                 $key = &unescape($key);
                   1109:                 next if ($key =~ /^error: 2 /);
                   1110:                 $returnhash{$key}=&thaw_unescape($value);
                   1111:             }
                   1112:             my @esc_order = split(/\&/,$orderitems);
                   1113:             foreach my $item (@esc_order) {
                   1114:                 push(@order,&unescape($item));
                   1115:             }
                   1116:         } else {
                   1117:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1118:         }
                   1119:     }
                   1120:     return (\%returnhash,\@order);
                   1121: }
                   1122: 
1.868     raeburn  1123: sub is_domainimage {
                   1124:     my ($url) = @_;
                   1125:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1126:         if (&domain($1) ne '') {
                   1127:             return '1';
                   1128:         }
                   1129:     }
                   1130:     return;
                   1131: }
                   1132: 
1.899     raeburn  1133: sub inst_directory_query {
                   1134:     my ($srch) = @_;
                   1135:     my $udom = $srch->{'srchdomain'};
                   1136:     my %results;
                   1137:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1138:     my $outcome;
1.899     raeburn  1139:     if ($homeserver ne '') {
1.904     albertel 1140: 	my $queryid=&reply("querysend:instdirsearch:".
                   1141: 			   &escape($srch->{'srchby'}).':'.
                   1142: 			   &escape($srch->{'srchterm'}).':'.
                   1143: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1144: 	my $host=&hostname($homeserver);
                   1145: 	if ($queryid !~/^\Q$host\E\_/) {
                   1146: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1147: 	    return;
                   1148: 	}
                   1149: 	my $response = &get_query_reply($queryid);
                   1150: 	my $maxtries = 5;
                   1151: 	my $tries = 1;
                   1152: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1153: 	    $response = &get_query_reply($queryid);
                   1154: 	    $tries ++;
                   1155: 	}
                   1156: 
                   1157:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1158:             if ($response eq 'unavailable') {
                   1159:                 $outcome = $response;
                   1160:             } else {
                   1161:                 $outcome = 'ok';
                   1162:                 my @matches = split(/\n/,$response);
                   1163:                 foreach my $match (@matches) {
                   1164:                     my ($key,$value) = split(/=/,$match);
                   1165:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1166:                 }
1.899     raeburn  1167:             }
                   1168:         }
                   1169:     }
1.909     raeburn  1170:     return ($outcome,%results);
1.899     raeburn  1171: }
                   1172: 
                   1173: sub usersearch {
                   1174:     my ($srch) = @_;
                   1175:     my $dom = $srch->{'srchdomain'};
                   1176:     my %results;
                   1177:     my %libserv = &all_library();
                   1178:     my $query = 'usersearch';
                   1179:     foreach my $tryserver (keys(%libserv)) {
                   1180:         if (&host_domain($tryserver) eq $dom) {
                   1181:             my $host=&hostname($tryserver);
                   1182:             my $queryid=
1.911     raeburn  1183:                 &reply("querysend:".&escape($query).':'.
                   1184:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1185:                        &escape($srch->{'srchtype'}).':'.
                   1186:                        &escape($srch->{'srchterm'}),$tryserver);
                   1187:             if ($queryid !~/^\Q$host\E\_/) {
                   1188:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1189:                 next;
1.899     raeburn  1190:             }
                   1191:             my $reply = &get_query_reply($queryid);
                   1192:             my $maxtries = 1;
                   1193:             my $tries = 1;
                   1194:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1195:                 $reply = &get_query_reply($queryid);
                   1196:                 $tries ++;
                   1197:             }
                   1198:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1199:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1200:             } else {
1.911     raeburn  1201:                 my @matches;
                   1202:                 if ($reply =~ /\n/) {
                   1203:                     @matches = split(/\n/,$reply);
                   1204:                 } else {
                   1205:                     @matches = split(/\&/,$reply);
                   1206:                 }
1.899     raeburn  1207:                 foreach my $match (@matches) {
                   1208:                     my ($uname,$udom,%userhash);
1.911     raeburn  1209:                     foreach my $entry (split(/:/,$match)) {
                   1210:                         my ($key,$value) =
                   1211:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1212:                         $userhash{$key} = $value;
                   1213:                         if ($key eq 'username') {
                   1214:                             $uname = $value;
                   1215:                         } elsif ($key eq 'domain') {
                   1216:                             $udom = $value;
1.911     raeburn  1217:                         }
1.899     raeburn  1218:                     }
                   1219:                     $results{$uname.':'.$udom} = \%userhash;
                   1220:                 }
                   1221:             }
                   1222:         }
                   1223:     }
                   1224:     return %results;
                   1225: }
                   1226: 
1.912     raeburn  1227: sub get_instuser {
                   1228:     my ($udom,$uname,$id) = @_;
                   1229:     my $homeserver = &domain($udom,'primary');
                   1230:     my ($outcome,%results);
                   1231:     if ($homeserver ne '') {
                   1232:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1233:                            &escape($id).':'.&escape($udom),$homeserver);
                   1234:         my $host=&hostname($homeserver);
                   1235:         if ($queryid !~/^\Q$host\E\_/) {
                   1236:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1237:             return;
                   1238:         }
                   1239:         my $response = &get_query_reply($queryid);
                   1240:         my $maxtries = 5;
                   1241:         my $tries = 1;
                   1242:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1243:             $response = &get_query_reply($queryid);
                   1244:             $tries ++;
                   1245:         }
                   1246:         if (!&error($response) && $response ne 'refused') {
                   1247:             if ($response eq 'unavailable') {
                   1248:                 $outcome = $response;
                   1249:             } else {
                   1250:                 $outcome = 'ok';
                   1251:                 my @matches = split(/\n/,$response);
                   1252:                 foreach my $match (@matches) {
                   1253:                     my ($key,$value) = split(/=/,$match);
                   1254:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1255:                 }
                   1256:             }
                   1257:         }
                   1258:     }
                   1259:     my %userinfo;
                   1260:     if (ref($results{$uname}) eq 'HASH') {
                   1261:         %userinfo = %{$results{$uname}};
                   1262:     } 
                   1263:     return ($outcome,%userinfo);
                   1264: }
                   1265: 
                   1266: sub inst_rulecheck {
1.923     raeburn  1267:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1268:     my %returnhash;
                   1269:     if ($udom ne '') {
                   1270:         if (ref($rules) eq 'ARRAY') {
                   1271:             @{$rules} = map {&escape($_);} (@{$rules});
                   1272:             my $rulestr = join(':',@{$rules});
                   1273:             my $homeserver=&domain($udom,'primary');
                   1274:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1275:                 my $response;
                   1276:                 if ($item eq 'username') {                
                   1277:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1278:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1279:                                               $homeserver));
1.923     raeburn  1280:                 } elsif ($item eq 'id') {
                   1281:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1282:                                               ':'.&escape($id).':'.$rulestr,
                   1283:                                               $homeserver));
1.945     raeburn  1284:                 } elsif ($item eq 'selfcreate') {
                   1285:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1286:                                                &escape($udom).':'.&escape($uname).
                   1287:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1288:                 }
1.912     raeburn  1289:                 if ($response ne 'refused') {
                   1290:                     my @pairs=split(/\&/,$response);
                   1291:                     foreach my $item (@pairs) {
                   1292:                         my ($key,$value)=split(/=/,$item,2);
                   1293:                         $key = &unescape($key);
                   1294:                         next if ($key =~ /^error: 2 /);
                   1295:                         $returnhash{$key}=&thaw_unescape($value);
                   1296:                     }
                   1297:                 }
                   1298:             }
                   1299:         }
                   1300:     }
                   1301:     return %returnhash;
                   1302: }
                   1303: 
                   1304: sub inst_userrules {
1.923     raeburn  1305:     my ($udom,$check) = @_;
1.912     raeburn  1306:     my (%ruleshash,@ruleorder);
                   1307:     if ($udom ne '') {
                   1308:         my $homeserver=&domain($udom,'primary');
                   1309:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1310:             my $response;
                   1311:             if ($check eq 'id') {
                   1312:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1313:                                  $homeserver);
1.943     raeburn  1314:             } elsif ($check eq 'email') {
                   1315:                 $response=&reply('instemailrules:'.&escape($udom),
                   1316:                                  $homeserver);
1.923     raeburn  1317:             } else {
                   1318:                 $response=&reply('instuserrules:'.&escape($udom),
                   1319:                                  $homeserver);
                   1320:             }
1.912     raeburn  1321:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1322:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1323:                 ($response ne 'no_such_host')) {
                   1324:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1325:                 my @pairs=split(/\&/,$hashitems);
                   1326:                 foreach my $item (@pairs) {
                   1327:                     my ($key,$value)=split(/=/,$item,2);
                   1328:                     $key = &unescape($key);
                   1329:                     next if ($key =~ /^error: 2 /);
                   1330:                     $ruleshash{$key}=&thaw_unescape($value);
                   1331:                 }
                   1332:                 my @esc_order = split(/\&/,$orderitems);
                   1333:                 foreach my $item (@esc_order) {
                   1334:                     push(@ruleorder,&unescape($item));
                   1335:                 }
                   1336:             }
                   1337:         }
                   1338:     }
                   1339:     return (\%ruleshash,\@ruleorder);
                   1340: }
                   1341: 
1.976     raeburn  1342: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1343: 
                   1344: sub get_domain_defaults {
                   1345:     my ($domain) = @_;
                   1346:     my $cachetime = 60*60*24;
                   1347:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1348:     if (defined($cached)) {
                   1349:         if (ref($result) eq 'HASH') {
                   1350:             return %{$result};
                   1351:         }
                   1352:     }
                   1353:     my %domdefaults;
                   1354:     my %domconfig =
1.989     raeburn  1355:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1356:                                   'requestcourses','inststatus',
                   1357:                                   'coursedefaults'],$domain);
1.943     raeburn  1358:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1359:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1360:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1361:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1362:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1363:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1364:     } else {
                   1365:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1366:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1367:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1368:     }
1.976     raeburn  1369:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1370:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1371:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1372:         } else {
                   1373:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1374:         } 
                   1375:         my @usertools = ('aboutme','blog','portfolio');
                   1376:         foreach my $item (@usertools) {
                   1377:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1378:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1379:             }
                   1380:         }
                   1381:     }
1.985     raeburn  1382:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1383:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1384:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1385:         }
                   1386:     }
1.989     raeburn  1387:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1388:         foreach my $item ('inststatustypes','inststatusorder') {
                   1389:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1390:         }
                   1391:     }
1.1047    raeburn  1392:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1393:         foreach my $item ('canuse_pdfforms') {
                   1394:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1395:         }
                   1396:     }
1.943     raeburn  1397:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1398:                                   $cachetime);
                   1399:     return %domdefaults;
                   1400: }
                   1401: 
1.344     www      1402: # --------------------------------------------------- Assign a key to a student
                   1403: 
                   1404: sub assign_access_key {
1.364     www      1405: #
                   1406: # a valid key looks like uname:udom#comments
                   1407: # comments are being appended
                   1408: #
1.498     www      1409:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1410:     $kdom=
1.620     albertel 1411:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1412:     $knum=
1.620     albertel 1413:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1414:     $cdom=
1.620     albertel 1415:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1416:     $cnum=
1.620     albertel 1417:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1418:     $udom=$env{'user.name'} unless (defined($udom));
                   1419:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1420:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1421:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1422:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1423:                                                   # assigned to this person
                   1424:                                                   # - this should not happen,
1.345     www      1425:                                                   # unless something went wrong
                   1426:                                                   # the first time around
                   1427: # ready to assign
1.364     www      1428:         $logentry=$1.'; '.$logentry;
1.496     www      1429:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1430:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1431: # key now belongs to user
1.346     www      1432: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1433:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1434:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1435:                 return 'ok';
                   1436:             } else {
                   1437:                 return 
                   1438:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1439: 	    }
                   1440:         } else {
                   1441:             return 'error: Could not assign key, try again later.';
                   1442:         }
1.364     www      1443:     } elsif (!$existing{$ckey}) {
1.345     www      1444: # the key does not exist
                   1445: 	return 'error: The key does not exist';
                   1446:     } else {
                   1447: # the key is somebody else's
                   1448: 	return 'error: The key is already in use';
                   1449:     }
1.344     www      1450: }
                   1451: 
1.364     www      1452: # ------------------------------------------ put an additional comment on a key
                   1453: 
                   1454: sub comment_access_key {
                   1455: #
                   1456: # a valid key looks like uname:udom#comments
                   1457: # comments are being appended
                   1458: #
                   1459:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1460:     $cdom=
1.620     albertel 1461:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1462:     $cnum=
1.620     albertel 1463:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1464:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1465:     if ($existing{$ckey}) {
                   1466:         $existing{$ckey}.='; '.$logentry;
                   1467: # ready to assign
1.367     www      1468:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1469:                                                  $cdom,$cnum) eq 'ok') {
                   1470: 	    return 'ok';
                   1471:         } else {
                   1472: 	    return 'error: Count not store comment.';
                   1473:         }
                   1474:     } else {
                   1475: # the key does not exist
                   1476: 	return 'error: The key does not exist';
                   1477:     }
                   1478: }
                   1479: 
1.344     www      1480: # ------------------------------------------------------ Generate a set of keys
                   1481: 
                   1482: sub generate_access_keys {
1.364     www      1483:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1484:     $cdom=
1.620     albertel 1485:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1486:     $cnum=
1.620     albertel 1487:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1488:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1489:     unless (($cdom) && ($cnum)) { return 0; }
                   1490:     if ($number>10000) { return 0; }
                   1491:     sleep(2); # make sure don't get same seed twice
                   1492:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1493:     my $total=0;
                   1494:     for (my $i=1;$i<=$number;$i++) {
                   1495:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1496:                   sprintf("%lx",int(100000*rand)).'-'.
                   1497:                   sprintf("%lx",int(100000*rand));
                   1498:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1499:        $newkey=~s/0/h/g; # and also 0 and O
                   1500:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1501:        if ($existing{$newkey}) {
                   1502:            $i--;
                   1503:        } else {
1.364     www      1504: 	  if (&put('accesskeys',
                   1505:               { $newkey => '# generated '.localtime().
1.620     albertel 1506:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1507:                            '; '.$logentry },
                   1508: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1509:               $total++;
                   1510: 	  }
                   1511:        }
                   1512:     }
1.620     albertel 1513:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1514:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1515:     return $total;
                   1516: }
                   1517: 
                   1518: # ------------------------------------------------------- Validate an accesskey
                   1519: 
                   1520: sub validate_access_key {
                   1521:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1522:     $cdom=
1.620     albertel 1523:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1524:     $cnum=
1.620     albertel 1525:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1526:     $udom=$env{'user.domain'} unless (defined($udom));
                   1527:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1528:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1529:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1530: }
                   1531: 
                   1532: # ------------------------------------- Find the section of student in a course
1.652     albertel 1533: sub devalidate_getsection_cache {
                   1534:     my ($udom,$unam,$courseid)=@_;
                   1535:     my $hashid="$udom:$unam:$courseid";
                   1536:     &devalidate_cache_new('getsection',$hashid);
                   1537: }
1.298     matthew  1538: 
1.815     albertel 1539: sub courseid_to_courseurl {
                   1540:     my ($courseid) = @_;
                   1541:     #already url style courseid
                   1542:     return $courseid if ($courseid =~ m{^/});
                   1543: 
                   1544:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1545: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1546: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1547: 	return "/$cdom/$cnum";
                   1548:     }
                   1549: 
                   1550:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1551:     if (exists($courseinfo{'num'})) {
                   1552: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1553:     }
                   1554: 
                   1555:     return undef;
                   1556: }
                   1557: 
1.298     matthew  1558: sub getsection {
                   1559:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1560:     my $cachetime=1800;
1.551     albertel 1561: 
                   1562:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1563:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1564:     if (defined($cached)) { return $result; }
                   1565: 
1.298     matthew  1566:     my %Pending; 
                   1567:     my %Expired;
                   1568:     #
                   1569:     # Each role can either have not started yet (pending), be active, 
                   1570:     #    or have expired.
                   1571:     #
                   1572:     # If there is an active role, we are done.
                   1573:     #
                   1574:     # If there is more than one role which has not started yet, 
                   1575:     #     choose the one which will start sooner
                   1576:     # If there is one role which has not started yet, return it.
                   1577:     #
                   1578:     # If there is more than one expired role, choose the one which ended last.
                   1579:     # If there is a role which has expired, return it.
                   1580:     #
1.815     albertel 1581:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1582:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1583:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1584:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1585:         my $section=$1;
                   1586:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1587:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1588:         my $now=time;
1.548     albertel 1589:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1590:             $Expired{$end}=$section;
                   1591:             next;
                   1592:         }
1.548     albertel 1593:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1594:             $Pending{$start}=$section;
                   1595:             next;
                   1596:         }
1.599     albertel 1597:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1598:     }
                   1599:     #
                   1600:     # Presumedly there will be few matching roles from the above
                   1601:     # loop and the sorting time will be negligible.
                   1602:     if (scalar(keys(%Pending))) {
                   1603:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1604:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1605:     } 
                   1606:     if (scalar(keys(%Expired))) {
                   1607:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1608:         my $time = pop(@sorted);
1.599     albertel 1609:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1610:     }
1.599     albertel 1611:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1612: }
1.70      www      1613: 
1.599     albertel 1614: sub save_cache {
                   1615:     &purge_remembered();
1.722     albertel 1616:     #&Apache::loncommon::validate_page();
1.620     albertel 1617:     undef(%env);
1.780     albertel 1618:     undef($env_loaded);
1.599     albertel 1619: }
1.452     albertel 1620: 
1.599     albertel 1621: my $to_remember=-1;
                   1622: my %remembered;
                   1623: my %accessed;
                   1624: my $kicks=0;
                   1625: my $hits=0;
1.849     albertel 1626: sub make_key {
                   1627:     my ($name,$id) = @_;
1.872     albertel 1628:     if (length($id) > 65 
                   1629: 	&& length(&escape($id)) > 200) {
                   1630: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1631:     }
1.849     albertel 1632:     return &escape($name.':'.$id);
                   1633: }
                   1634: 
1.599     albertel 1635: sub devalidate_cache_new {
                   1636:     my ($name,$id,$debug) = @_;
                   1637:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1638:     $id=&make_key($name,$id);
1.599     albertel 1639:     $memcache->delete($id);
                   1640:     delete($remembered{$id});
                   1641:     delete($accessed{$id});
                   1642: }
                   1643: 
                   1644: sub is_cached_new {
                   1645:     my ($name,$id,$debug) = @_;
1.849     albertel 1646:     $id=&make_key($name,$id);
1.599     albertel 1647:     if (exists($remembered{$id})) {
                   1648: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1649: 	$accessed{$id}=[&gettimeofday()];
                   1650: 	$hits++;
                   1651: 	return ($remembered{$id},1);
                   1652:     }
                   1653:     my $value = $memcache->get($id);
                   1654:     if (!(defined($value))) {
                   1655: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1656: 	return (undef,undef);
1.416     albertel 1657:     }
1.599     albertel 1658:     if ($value eq '__undef__') {
                   1659: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1660: 	$value=undef;
                   1661:     }
                   1662:     &make_room($id,$value,$debug);
                   1663:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1664:     return ($value,1);
                   1665: }
                   1666: 
                   1667: sub do_cache_new {
                   1668:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1669:     $id=&make_key($name,$id);
1.599     albertel 1670:     my $setvalue=$value;
                   1671:     if (!defined($setvalue)) {
                   1672: 	$setvalue='__undef__';
                   1673:     }
1.623     albertel 1674:     if (!defined($time) ) {
                   1675: 	$time=600;
                   1676:     }
1.599     albertel 1677:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1678:     my $result = $memcache->set($id,$setvalue,$time);
                   1679:     if (! $result) {
1.872     albertel 1680: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1681: 	$memcache->disconnect_all();
1.872     albertel 1682:     }
1.600     albertel 1683:     # need to make a copy of $value
1.919     albertel 1684:     &make_room($id,$value,$debug);
1.599     albertel 1685:     return $value;
                   1686: }
                   1687: 
                   1688: sub make_room {
                   1689:     my ($id,$value,$debug)=@_;
1.919     albertel 1690: 
                   1691:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1692:                                     : $value;
1.599     albertel 1693:     if ($to_remember<0) { return; }
                   1694:     $accessed{$id}=[&gettimeofday()];
                   1695:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1696:     my $to_kick;
                   1697:     my $max_time=0;
                   1698:     foreach my $other (keys(%accessed)) {
                   1699: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1700: 	    $to_kick=$other;
                   1701: 	    $max_time=&tv_interval($accessed{$other});
                   1702: 	}
                   1703:     }
                   1704:     delete($remembered{$to_kick});
                   1705:     delete($accessed{$to_kick});
                   1706:     $kicks++;
                   1707:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1708:     return;
                   1709: }
                   1710: 
1.599     albertel 1711: sub purge_remembered {
1.604     albertel 1712:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1713:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1714:     undef(%remembered);
                   1715:     undef(%accessed);
1.428     albertel 1716: }
1.70      www      1717: # ------------------------------------- Read an entry from a user's environment
                   1718: 
                   1719: sub userenvironment {
                   1720:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1721:     my $items;
                   1722:     foreach my $item (@what) {
                   1723:         $items.=&escape($item).'&';
                   1724:     }
                   1725:     $items=~s/\&$//;
1.70      www      1726:     my %returnhash=();
1.1009    raeburn  1727:     my $uhome = &homeserver($unam,$udom);
                   1728:     unless ($uhome eq 'no_host') {
                   1729:         my @answer=split(/\&/, 
                   1730:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  1731:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   1732:             return %returnhash;
                   1733:         }
1.1009    raeburn  1734:         my $i;
                   1735:         for ($i=0;$i<=$#what;$i++) {
                   1736: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   1737:         }
1.70      www      1738:     }
                   1739:     return %returnhash;
1.1       albertel 1740: }
                   1741: 
1.617     albertel 1742: # ---------------------------------------------------------- Get a studentphoto
                   1743: sub studentphoto {
                   1744:     my ($udom,$unam,$ext) = @_;
                   1745:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1746:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1747:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1748:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1749:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1750:             } else {
                   1751:                 my ($result,$perm_reqd)=
1.707     albertel 1752: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1753:                 if ($result eq 'ok') {
                   1754:                     if (!($perm_reqd eq 'yes')) {
                   1755:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1756:                     }
                   1757:                 }
                   1758:             }
                   1759:         }
                   1760:     } else {
                   1761:         my ($result,$perm_reqd) = 
1.707     albertel 1762: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1763:         if ($result eq 'ok') {
                   1764:             if (!($perm_reqd eq 'yes')) {
                   1765:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1766:             }
                   1767:         }
                   1768:     }
                   1769:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1770: }
                   1771: 
                   1772: sub retrievestudentphoto {
                   1773:     my ($udom,$unam,$ext,$type) = @_;
                   1774:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1775:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1776:     if ($ret eq 'ok') {
                   1777:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1778:         if ($type eq 'thumbnail') {
                   1779:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1780:         }
                   1781:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1782:         return $tokenurl;
                   1783:     } else {
                   1784:         if ($type eq 'thumbnail') {
                   1785:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1786:         } else { 
                   1787:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1788:         }
1.617     albertel 1789:     }
                   1790: }
                   1791: 
1.263     www      1792: # -------------------------------------------------------------------- New chat
                   1793: 
                   1794: sub chatsend {
1.724     raeburn  1795:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1796:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1797:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1798:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1799:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1800: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1801: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1802: }
                   1803: 
                   1804: # ------------------------------------------ Find current version of a resource
                   1805: 
                   1806: sub getversion {
                   1807:     my $fname=&clutter(shift);
                   1808:     unless ($fname=~/^\/res\//) { return -1; }
                   1809:     return &currentversion(&filelocation('',$fname));
                   1810: }
                   1811: 
                   1812: sub currentversion {
                   1813:     my $fname=shift;
1.599     albertel 1814:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1815:     if (defined($cached)) { return $result; }
1.292     www      1816:     my $author=$fname;
                   1817:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1818:     my ($udom,$uname)=split(/\//,$author);
                   1819:     my $home=homeserver($uname,$udom);
                   1820:     if ($home eq 'no_host') { 
                   1821:         return -1; 
                   1822:     }
                   1823:     my $answer=reply("currentversion:$fname",$home);
                   1824:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1825: 	return -1;
                   1826:     }
1.599     albertel 1827:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1828: }
                   1829: 
1.1       albertel 1830: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1831: 
1.1       albertel 1832: sub subscribe {
                   1833:     my $fname=shift;
1.761     raeburn  1834:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1835:     $fname=~s/[\n\r]//g;
1.1       albertel 1836:     my $author=$fname;
                   1837:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1838:     my ($udom,$uname)=split(/\//,$author);
                   1839:     my $home=homeserver($uname,$udom);
1.335     albertel 1840:     if ($home eq 'no_host') {
                   1841:         return 'not_found';
1.1       albertel 1842:     }
                   1843:     my $answer=reply("sub:$fname",$home);
1.64      www      1844:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1845: 	$answer.=' by '.$home;
                   1846:     }
1.1       albertel 1847:     return $answer;
                   1848: }
                   1849:     
1.8       www      1850: # -------------------------------------------------------------- Replicate file
                   1851: 
                   1852: sub repcopy {
                   1853:     my $filename=shift;
1.23      www      1854:     $filename=~s/\/+/\//g;
1.607     raeburn  1855:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1856:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1857:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1858: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1859: 	return &repcopy_userfile($filename);
                   1860:     }
1.532     albertel 1861:     $filename=~s/[\n\r]//g;
1.8       www      1862:     my $transname="$filename.in.transfer";
1.828     www      1863: # FIXME: this should flock
1.607     raeburn  1864:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1865:     my $remoteurl=subscribe($filename);
1.64      www      1866:     if ($remoteurl =~ /^con_lost by/) {
                   1867: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1868:            return 'unavailable';
1.8       www      1869:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1870: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1871: 	   return 'not_found';
1.64      www      1872:     } elsif ($remoteurl =~ /^rejected by/) {
                   1873: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1874:            return 'forbidden';
1.20      www      1875:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1876:            return 'ok';
1.8       www      1877:     } else {
1.290     www      1878:         my $author=$filename;
                   1879:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1880:         my ($udom,$uname)=split(/\//,$author);
                   1881:         my $home=homeserver($uname,$udom);
                   1882:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1883:            my @parts=split(/\//,$filename);
                   1884:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1885:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1886:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1887: 	       return 'bad_request';
1.8       www      1888:            }
                   1889:            my $count;
                   1890:            for ($count=5;$count<$#parts;$count++) {
                   1891:                $path.="/$parts[$count]";
                   1892:                if ((-e $path)!=1) {
                   1893: 		   mkdir($path,0777);
                   1894:                }
                   1895:            }
                   1896:            my $ua=new LWP::UserAgent;
                   1897:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1898:            my $response=$ua->request($request,$transname);
                   1899:            if ($response->is_error()) {
                   1900: 	       unlink($transname);
                   1901:                my $message=$response->status_line;
1.672     albertel 1902:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1903:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1904:                return 'unavailable';
1.8       www      1905:            } else {
1.16      www      1906: 	       if ($remoteurl!~/\.meta$/) {
                   1907:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1908:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1909:                   if ($mresponse->is_error()) {
                   1910: 		      unlink($filename.'.meta');
                   1911:                       &logthis(
1.672     albertel 1912:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1913:                   }
                   1914: 	       }
1.8       www      1915:                rename($transname,$filename);
1.607     raeburn  1916:                return 'ok';
1.8       www      1917:            }
1.290     www      1918:        }
1.8       www      1919:     }
1.330     www      1920: }
                   1921: 
                   1922: # ------------------------------------------------ Get server side include body
                   1923: sub ssi_body {
1.381     albertel 1924:     my ($filelink,%form)=@_;
1.606     matthew  1925:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1926:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1927:     }
1.953     www      1928:     my $output='';
                   1929:     my $response;
1.980     raeburn  1930:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1931:        ($output,$response)=&externalssi($filelink);
1.953     www      1932:     } else {
1.1004    droeschl 1933:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   1934:        $filelink .= 'inhibitmenu=yes';
1.953     www      1935:        ($output,$response)=&ssi($filelink,%form);
                   1936:     }
1.778     albertel 1937:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1938:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1939:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1940:     if (wantarray) {
                   1941:         return ($output, $response);
                   1942:     } else {
                   1943:         return $output;
                   1944:     }
1.8       www      1945: }
                   1946: 
1.15      www      1947: # --------------------------------------------------------- Server Side Include
                   1948: 
1.782     albertel 1949: sub absolute_url {
                   1950:     my ($host_name) = @_;
                   1951:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1952:     if ($host_name eq '') {
                   1953: 	$host_name = $ENV{'SERVER_NAME'};
                   1954:     }
                   1955:     return $protocol.$host_name;
                   1956: }
                   1957: 
1.942     foxr     1958: #
                   1959: #   Server side include.
                   1960: # Parameters:
                   1961: #  fn     Possibly encrypted resource name/id.
                   1962: #  form   Hash that describes how the rendering should be done
                   1963: #         and other things.
1.944     foxr     1964: # Returns:
1.950     raeburn  1965: #   Scalar context: The content of the response.
                   1966: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1967: #     
1.15      www      1968: sub ssi {
                   1969: 
1.944     foxr     1970:     my ($fn,%form)=@_;
1.15      www      1971:     my $ua=new LWP::UserAgent;
1.23      www      1972:     my $request;
1.711     albertel 1973: 
                   1974:     $form{'no_update_last_known'}=1;
1.895     albertel 1975:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1976:     if (%form) {
1.782     albertel 1977:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  1978:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      1979:     } else {
1.782     albertel 1980:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1981:     }
                   1982: 
1.15      www      1983:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1984:     my $response=$ua->request($request);
                   1985: 
1.944     foxr     1986:     if (wantarray) {
                   1987: 	return ($response->content, $response);
                   1988:     } else {
                   1989: 	return $response->content;
1.942     foxr     1990:     }
1.324     www      1991: }
                   1992: 
                   1993: sub externalssi {
                   1994:     my ($url)=@_;
                   1995:     my $ua=new LWP::UserAgent;
                   1996:     my $request=new HTTP::Request('GET',$url);
                   1997:     my $response=$ua->request($request);
1.954     raeburn  1998:     if (wantarray) {
                   1999:         return ($response->content, $response);
                   2000:     } else {
                   2001:         return $response->content;
                   2002:     }
1.15      www      2003: }
1.254     www      2004: 
1.492     albertel 2005: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2006: 
                   2007: sub allowuploaded {
                   2008:     my ($srcurl,$url)=@_;
                   2009:     $url=&clutter(&declutter($url));
                   2010:     my $dir=$url;
                   2011:     $dir=~s/\/[^\/]+$//;
                   2012:     my %httpref=();
                   2013:     my $httpurl=&hreflocation('',$url);
                   2014:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2015:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2016: }
1.477     raeburn  2017: 
1.478     albertel 2018: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2019: # input: action, courseID, current domain, intended
1.637     raeburn  2020: #        path to file, source of file, instruction to parse file for objects,
                   2021: #        ref to hash for embedded objects,
                   2022: #        ref to hash for codebase of java objects.
                   2023: #
1.485     raeburn  2024: # output: url to file (if action was uploaddoc), 
                   2025: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2026: #
1.478     albertel 2027: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2028: # course.
1.477     raeburn  2029: #
1.478     albertel 2030: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2031: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2032: #          course's home server.
1.477     raeburn  2033: #
1.478     albertel 2034: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2035: #          be copied from $source (current location) to 
                   2036: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2037: #         and will then be copied to
                   2038: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2039: #         course's home server.
1.485     raeburn  2040: #
1.481     raeburn  2041: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2042: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2043: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2044: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2045: #         in course's home server.
1.637     raeburn  2046: #
1.477     raeburn  2047: 
                   2048: sub process_coursefile {
1.638     albertel 2049:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  2050:     my $fetchresult;
1.638     albertel 2051:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2052:     if ($action eq 'propagate') {
1.638     albertel 2053:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2054: 			     $home);
1.481     raeburn  2055:     } else {
1.477     raeburn  2056:         my $fpath = '';
                   2057:         my $fname = $file;
1.478     albertel 2058:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2059:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2060:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2061:         if ($action eq 'copy') {
                   2062:             if ($source eq '') {
                   2063:                 $fetchresult = 'no source file';
                   2064:                 return $fetchresult;
                   2065:             } else {
                   2066:                 my $destination = $filepath.'/'.$fname;
                   2067:                 rename($source,$destination);
                   2068:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2069:                                  $home);
1.481     raeburn  2070:             }
                   2071:         } elsif ($action eq 'uploaddoc') {
                   2072:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2073:             print $fh $env{'form.'.$source};
1.481     raeburn  2074:             close($fh);
1.637     raeburn  2075:             if ($parser eq 'parse') {
1.1024    raeburn  2076:                 my $mm = new File::MMagic;
                   2077:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
                   2078:                 if ($mime_type eq 'text/html') {
                   2079:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2080:                     unless ($parse_result eq 'ok') {
                   2081:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2082:                     }
1.637     raeburn  2083:                 }
                   2084:             }
1.477     raeburn  2085:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2086:                                  $home);
1.481     raeburn  2087:             if ($fetchresult eq 'ok') {
                   2088:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2089:             } else {
                   2090:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2091:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2092:                 return '/adm/notfound.html';
                   2093:             }
1.477     raeburn  2094:         }
                   2095:     }
1.485     raeburn  2096:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2097:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2098:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2099:     }
                   2100:     return $fetchresult;
                   2101: }
                   2102: 
1.637     raeburn  2103: sub build_filepath {
                   2104:     my ($fpath) = @_;
                   2105:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2106:     unless ($fpath eq '') {
                   2107:         my @parts=split('/',$fpath);
                   2108:         foreach my $part (@parts) {
                   2109:             $filepath.= '/'.$part;
                   2110:             if ((-e $filepath)!=1) {
                   2111:                 mkdir($filepath,0777);
                   2112:             }
                   2113:         }
                   2114:     }
                   2115:     return $filepath;
                   2116: }
                   2117: 
                   2118: sub store_edited_file {
1.638     albertel 2119:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2120:     my $file = $primary_url;
                   2121:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2122:     my $fpath = '';
                   2123:     my $fname = $file;
                   2124:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2125:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2126:     my $filepath = &build_filepath($fpath);
                   2127:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2128:     print $fh $content;
                   2129:     close($fh);
1.638     albertel 2130:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2131:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2132: 			  $home);
1.637     raeburn  2133:     if ($$fetchresult eq 'ok') {
                   2134:         return '/uploaded/'.$fpath.'/'.$fname;
                   2135:     } else {
1.638     albertel 2136:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2137: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2138:         return '/adm/notfound.html';
                   2139:     }
                   2140: }
                   2141: 
1.531     albertel 2142: sub clean_filename {
1.831     albertel 2143:     my ($fname,$args)=@_;
1.315     www      2144: # Replace Windows backslashes by forward slashes
1.257     www      2145:     $fname=~s/\\/\//g;
1.831     albertel 2146:     if (!$args->{'keep_path'}) {
                   2147:         # Get rid of everything but the actual filename
                   2148: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2149:     }
1.315     www      2150: # Replace spaces by underscores
                   2151:     $fname=~s/\s+/\_/g;
                   2152: # Replace all other weird characters by nothing
1.831     albertel 2153:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2154: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2155: # numbers
                   2156:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2157:     return $fname;
                   2158: }
1.984     neumanie 2159: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
                   2160: sub resizeImage {
                   2161: 	my($img_url) = @_;	
                   2162: 	my $ima = Image::Magick->new;                       
                   2163:         $ima->Read($img_url);
                   2164: 	if($ima->Get('width') > 400)
                   2165: 	{
                   2166: 		my $factor = $ima->Get('width')/400;
                   2167:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
                   2168: 	}
                   2169: 	if($ima->Get('height') > 500)
                   2170:         {
                   2171:         	my $factor = $ima->Get('height')/500;
                   2172:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
                   2173:         } 
                   2174: 		
                   2175: 	$ima->Write($img_url);
                   2176: }
1.531     albertel 2177: 
1.977     amueller 2178: #Wrapper function for userphotoupload
                   2179: sub userphotoupload
                   2180: {
                   2181: 	my($formname,$subdir) = @_;
                   2182: 	$upload_photo_form = 1;
                   2183: 	return &userfileupload($formname,undef,$subdir);
                   2184: }
                   2185: 
1.608     albertel 2186: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2187: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2188: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2189: #        $coursedoc - if true up to the current course
                   2190: #                     if false
                   2191: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2192: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2193: #        $allfiles - reference to hash for embedded objects
                   2194: #        $codebase - reference to hash for codebase of java objects
                   2195: #        $desuname - username for permanent storage of uploaded file
                   2196: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2197: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2198: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2199: # 
1.686     albertel 2200: # output: url of file in userspace, or error: <message> 
                   2201: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2202: 
                   2203: 
1.531     albertel 2204: sub userfileupload {
1.860     raeburn  2205:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2206:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2207:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2208:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2209:     $fname=&clean_filename($fname);
1.315     www      2210: # See if there is anything left
1.257     www      2211:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2212:     chop($env{'form.'.$formname});
1.523     raeburn  2213:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2214:         my $now = time;
                   2215:         my $filepath = 'tmp/helprequests/'.$now;
                   2216:         my @parts=split(/\//,$filepath);
                   2217:         my $fullpath = $perlvar{'lonDaemons'};
                   2218:         for (my $i=0;$i<@parts;$i++) {
                   2219:             $fullpath .= '/'.$parts[$i];
                   2220:             if ((-e $fullpath)!=1) {
                   2221:                 mkdir($fullpath,0777);
                   2222:             }
                   2223:         }
                   2224:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2225:         print $fh $env{'form.'.$formname};
1.523     raeburn  2226:         close($fh);
1.741     raeburn  2227:         return $fullpath.'/'.$fname;
                   2228:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2229:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2230:                        '_'.$env{'user.domain'}.'/pending';
                   2231:         my @parts=split(/\//,$filepath);
                   2232:         my $fullpath = $perlvar{'lonDaemons'};
                   2233:         for (my $i=0;$i<@parts;$i++) {
                   2234:             $fullpath .= '/'.$parts[$i];
                   2235:             if ((-e $fullpath)!=1) {
                   2236:                 mkdir($fullpath,0777);
                   2237:             }
                   2238:         }
                   2239:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2240:         print $fh $env{'form.'.$formname};
                   2241:         close($fh);
                   2242:         return $fullpath.'/'.$fname;
1.523     raeburn  2243:     }
1.995     raeburn  2244:     if ($subdir eq 'scantron') {
                   2245:         $fname = 'scantron_orig_'.$fname;
                   2246:     } else {   
1.258     www      2247: # Create the directory if not present
1.995     raeburn  2248:         $fname="$subdir/$fname";
                   2249:     }
1.259     www      2250:     if ($coursedoc) {
1.638     albertel 2251: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2252: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2253:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2254:             return &finishuserfileupload($docuname,$docudom,
                   2255: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2256: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2257:         } else {
1.620     albertel 2258:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2259:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2260: 				       $fname,$formname,$parser,
                   2261: 				       $allfiles,$codebase);
1.481     raeburn  2262:         }
1.719     banghart 2263:     } elsif (defined($destuname)) {
                   2264:         my $docuname=$destuname;
                   2265:         my $docudom=$destudom;
1.860     raeburn  2266: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2267: 				     $parser,$allfiles,$codebase,
                   2268:                                      $thumbwidth,$thumbheight);
1.719     banghart 2269:         
1.259     www      2270:     } else {
1.638     albertel 2271:         my $docuname=$env{'user.name'};
                   2272:         my $docudom=$env{'user.domain'};
1.714     raeburn  2273:         if (exists($env{'form.group'})) {
                   2274:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2275:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2276:         }
1.860     raeburn  2277: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2278: 				     $parser,$allfiles,$codebase,
                   2279:                                      $thumbwidth,$thumbheight);
1.259     www      2280:     }
1.271     www      2281: }
                   2282: 
                   2283: sub finishuserfileupload {
1.860     raeburn  2284:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2285:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2286:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2287:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2288:   
1.860     raeburn  2289:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2290:     $file=$fname;
                   2291:     if ($fname=~m|/|) {
                   2292:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2293: 	$path.=$fnamepath.'/';
                   2294:     }
1.259     www      2295:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2296:     my $count;
                   2297:     for ($count=4;$count<=$#parts;$count++) {
                   2298:         $filepath.="/$parts[$count]";
                   2299:         if ((-e $filepath)!=1) {
                   2300: 	    mkdir($filepath,0777);
                   2301:         }
                   2302:     }
1.984     neumanie 2303: 
1.258     www      2304: # Save the file
                   2305:     {
1.701     albertel 2306: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2307: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2308: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2309: 	    return '/adm/notfound.html';
                   2310: 	}
                   2311: 	if (!print FH ($env{'form.'.$formname})) {
                   2312: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2313: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2314: 	    return '/adm/notfound.html';
                   2315: 	}
1.570     albertel 2316: 	close(FH);
1.977     amueller 2317: 	if($upload_photo_form==1)
                   2318: 	{
1.984     neumanie 2319: 		resizeImage($filepath.'/'.$file);		
1.977     amueller 2320: 		$upload_photo_form = 0;
                   2321: 	}
1.258     www      2322:     }
1.637     raeburn  2323:     if ($parser eq 'parse') {
1.1024    raeburn  2324:         my $mm = new File::MMagic;
                   2325:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2326:         if ($mime_type eq 'text/html') {
                   2327:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2328:                                                        $allfiles,$codebase);
                   2329:             unless ($parse_result eq 'ok') {
                   2330:                 &logthis('Failed to parse '.$filepath.$file.
                   2331: 	   	         ' for embedded media: '.$parse_result); 
                   2332:             }
1.637     raeburn  2333:         }
                   2334:     }
1.860     raeburn  2335:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2336:         my $input = $filepath.'/'.$file;
                   2337:         my $output = $filepath.'/'.'tn-'.$file;
                   2338:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2339:         system("convert -sample $thumbsize $input $output");
                   2340:         if (-e $filepath.'/'.'tn-'.$file) {
                   2341:             $fetchthumb  = 1; 
                   2342:         }
                   2343:     }
1.858     raeburn  2344:  
1.259     www      2345: # Notify homeserver to grep it
                   2346: #
1.984     neumanie 2347:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2348:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2349:     if ($fetchresult eq 'ok') {
1.860     raeburn  2350:         if ($fetchthumb) {
                   2351:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2352:             if ($thumbresult ne 'ok') {
                   2353:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2354:                          $docuhome.': '.$thumbresult);
                   2355:             }
                   2356:         }
1.259     www      2357: #
1.258     www      2358: # Return the URL to it
1.494     albertel 2359:         return '/uploaded/'.$path.$file;
1.263     www      2360:     } else {
1.494     albertel 2361:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2362: 		 ': '.$fetchresult);
1.263     www      2363:         return '/adm/notfound.html';
1.858     raeburn  2364:     }
1.493     albertel 2365: }
                   2366: 
1.637     raeburn  2367: sub extract_embedded_items {
1.961     raeburn  2368:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2369:     my @state = ();
                   2370:     my %javafiles = (
                   2371:                       codebase => '',
                   2372:                       code => '',
                   2373:                       archive => ''
                   2374:                     );
                   2375:     my %mediafiles = (
                   2376:                       src => '',
                   2377:                       movie => '',
                   2378:                      );
1.648     raeburn  2379:     my $p;
                   2380:     if ($content) {
                   2381:         $p = HTML::LCParser->new($content);
                   2382:     } else {
1.961     raeburn  2383:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2384:     }
1.641     albertel 2385:     while (my $t=$p->get_token()) {
1.640     albertel 2386: 	if ($t->[0] eq 'S') {
                   2387: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2388: 	    push(@state, $tagname);
1.648     raeburn  2389:             if (lc($tagname) eq 'allow') {
                   2390:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2391:             }
1.640     albertel 2392: 	    if (lc($tagname) eq 'img') {
                   2393: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2394: 	    }
1.886     albertel 2395: 	    if (lc($tagname) eq 'a') {
                   2396: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2397: 	    }
1.645     raeburn  2398:             if (lc($tagname) eq 'script') {
                   2399:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2400:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2401:                 } else {
                   2402:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2403:                 }
                   2404:             }
                   2405:             if (lc($tagname) eq 'link') {
                   2406:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2407:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2408:                 }
                   2409:             }
1.640     albertel 2410: 	    if (lc($tagname) eq 'object' ||
                   2411: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2412: 		foreach my $item (keys(%javafiles)) {
                   2413: 		    $javafiles{$item} = '';
                   2414: 		}
                   2415: 	    }
                   2416: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2417: 		my $name = lc($attr->{'name'});
                   2418: 		foreach my $item (keys(%javafiles)) {
                   2419: 		    if ($name eq $item) {
                   2420: 			$javafiles{$item} = $attr->{'value'};
                   2421: 			last;
                   2422: 		    }
                   2423: 		}
                   2424: 		foreach my $item (keys(%mediafiles)) {
                   2425: 		    if ($name eq $item) {
                   2426: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2427: 			last;
                   2428: 		    }
                   2429: 		}
                   2430: 	    }
                   2431: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2432: 		foreach my $item (keys(%javafiles)) {
                   2433: 		    if ($attr->{$item}) {
                   2434: 			$javafiles{$item} = $attr->{$item};
                   2435: 			last;
                   2436: 		    }
                   2437: 		}
                   2438: 		foreach my $item (keys(%mediafiles)) {
                   2439: 		    if ($attr->{$item}) {
                   2440: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2441: 			last;
                   2442: 		    }
                   2443: 		}
                   2444: 	    }
                   2445: 	} elsif ($t->[0] eq 'E') {
                   2446: 	    my ($tagname) = ($t->[1]);
                   2447: 	    if ($javafiles{'codebase'} ne '') {
                   2448: 		$javafiles{'codebase'} .= '/';
                   2449: 	    }  
                   2450: 	    if (lc($tagname) eq 'applet' ||
                   2451: 		lc($tagname) eq 'object' ||
                   2452: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2453: 		) {
                   2454: 		foreach my $item (keys(%javafiles)) {
                   2455: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2456: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2457: 			&add_filetype($allfiles,$file,$item);
                   2458: 		    }
                   2459: 		}
                   2460: 	    } 
                   2461: 	    pop @state;
                   2462: 	}
                   2463:     }
1.637     raeburn  2464:     return 'ok';
                   2465: }
                   2466: 
1.639     albertel 2467: sub add_filetype {
                   2468:     my ($allfiles,$file,$type)=@_;
                   2469:     if (exists($allfiles->{$file})) {
                   2470: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2471: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2472: 	}
                   2473:     } else {
                   2474: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2475:     }
                   2476: }
                   2477: 
1.493     albertel 2478: sub removeuploadedurl {
1.984     neumanie 2479:     my ($url)=@_;	
                   2480:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 2481:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2482: }
                   2483: 
                   2484: sub removeuserfile {
                   2485:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 2486:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  2487:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 2488:     if ($result eq 'ok') {	
1.798     raeburn  2489:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2490:             my $metafile = $fname.'.meta';
                   2491:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2492: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 2493:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  2494:             my $sqlresult = 
1.823     albertel 2495:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2496:                                         'portfolio_metadata',$group,
                   2497:                                         'delete');
1.798     raeburn  2498:         }
                   2499:     }
                   2500:     return $result;
1.257     www      2501: }
1.15      www      2502: 
1.530     albertel 2503: sub mkdiruserfile {
                   2504:     my ($docuname,$docudom,$dir)=@_;
                   2505:     my $home=&homeserver($docuname,$docudom);
                   2506:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2507: }
                   2508: 
1.531     albertel 2509: sub renameuserfile {
                   2510:     my ($docuname,$docudom,$old,$new)=@_;
                   2511:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2512:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2513:                         &escape("$old").':'.&escape("$new"),$home);
                   2514:     if ($result eq 'ok') {
                   2515:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2516:             my $oldmeta = $old.'.meta';
                   2517:             my $newmeta = $new.'.meta';
                   2518:             my $metaresult = 
                   2519:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2520: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2521:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2522:             my $sqlresult = 
1.823     albertel 2523:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2524:                                         'portfolio_metadata',$group,
                   2525:                                         'delete');
1.798     raeburn  2526:         }
                   2527:     }
                   2528:     return $result;
1.531     albertel 2529: }
                   2530: 
1.14      www      2531: # ------------------------------------------------------------------------- Log
                   2532: 
                   2533: sub log {
                   2534:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2535:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2536: }
                   2537: 
                   2538: # ------------------------------------------------------------------ Course Log
1.352     www      2539: #
                   2540: # This routine flushes several buffers of non-mission-critical nature
                   2541: #
1.157     www      2542: 
                   2543: sub flushcourselogs {
1.352     www      2544:     &logthis('Flushing log buffers');
                   2545: #
                   2546: # course logs
                   2547: # This is a log of all transactions in a course, which can be used
                   2548: # for data mining purposes
                   2549: #
                   2550: # It also collects the courseid database, which lists last transaction
                   2551: # times and course titles for all courseids
                   2552: #
                   2553:     my %courseidbuffer=();
1.921     raeburn  2554:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2555:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2556: 		          &escape($courselogs{$crsid}),
                   2557: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2558: 	    delete $courselogs{$crsid};
                   2559:         } else {
                   2560:             &logthis('Failed to flush log buffer for '.$crsid);
                   2561:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2562:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2563:                         " exceeded maximum size, deleting.</font>");
                   2564:                delete $courselogs{$crsid};
                   2565:             }
1.352     www      2566:         }
1.920     raeburn  2567:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2568:             'description' => $coursedescrbuf{$crsid},
                   2569:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2570:             'type'        => $coursetypebuf{$crsid},
                   2571:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2572:         };
1.191     harris41 2573:     }
1.352     www      2574: #
                   2575: # Write course id database (reverse lookup) to homeserver of courses 
                   2576: # Is used in pickcourse
                   2577: #
1.840     albertel 2578:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2579:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2580:                                     $courseidbuffer{$crs_home},
                   2581:                                     $crs_home,'timeonly');
1.352     www      2582:     }
                   2583: #
                   2584: # File accesses
                   2585: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2586: #
1.449     matthew  2587:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2588:         if ($entry =~ /___count$/) {
                   2589:             my ($dom,$name);
1.807     albertel 2590:             ($dom,$name,undef)=
1.811     albertel 2591: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2592:             if (! defined($dom) || $dom eq '' || 
                   2593:                 ! defined($name) || $name eq '') {
1.620     albertel 2594:                 my $cid = $env{'request.course.id'};
                   2595:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2596:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2597:             }
1.450     matthew  2598:             my $value = $accesshash{$entry};
                   2599:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2600:             my %temphash=($url => $value);
1.449     matthew  2601:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2602:             if ($result eq 'ok') {
                   2603:                 delete $accesshash{$entry};
                   2604:             } elsif ($result eq 'unknown_cmd') {
                   2605:                 # Target server has old code running on it.
1.450     matthew  2606:                 my %temphash=($entry => $value);
1.449     matthew  2607:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2608:                     delete $accesshash{$entry};
                   2609:                 }
                   2610:             }
                   2611:         } else {
1.811     albertel 2612:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2613:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2614:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2615:                 delete $accesshash{$entry};
                   2616:             }
1.185     www      2617:         }
1.191     harris41 2618:     }
1.352     www      2619: #
                   2620: # Roles
                   2621: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2622: #
1.800     albertel 2623:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2624:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2625: 	    split(/\:/,$entry);
                   2626:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2627:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2628:                 $rudom,$runame) eq 'ok') {
                   2629: 	    delete $userrolehash{$entry};
                   2630:         }
                   2631:     }
1.662     raeburn  2632: #
                   2633: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2634: #
                   2635:     my %domrolebuffer = ();
1.1000    raeburn  2636:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 2637:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2638:         if ($domrolebuffer{$rudom}) {
                   2639:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2640:                       '='.&escape($domainrolehash{$entry});
                   2641:         } else {
                   2642:             $domrolebuffer{$rudom}.=&escape($entry).
                   2643:                       '='.&escape($domainrolehash{$entry});
                   2644:         }
                   2645:         delete $domainrolehash{$entry};
                   2646:     }
                   2647:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2648: 	my %servers = &get_servers($dom,'library');
                   2649: 	foreach my $tryserver (keys(%servers)) {
                   2650: 	    unless (&reply('domroleput:'.$dom.':'.
                   2651: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2652: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2653: 	    }
1.662     raeburn  2654:         }
                   2655:     }
1.186     www      2656:     $dumpcount++;
1.157     www      2657: }
                   2658: 
                   2659: sub courselog {
                   2660:     my $what=shift;
1.158     www      2661:     $what=time.':'.$what;
1.620     albertel 2662:     unless ($env{'request.course.id'}) { return ''; }
                   2663:     $coursedombuf{$env{'request.course.id'}}=
                   2664:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2665:     $coursenumbuf{$env{'request.course.id'}}=
                   2666:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2667:     $coursehombuf{$env{'request.course.id'}}=
                   2668:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2669:     $coursedescrbuf{$env{'request.course.id'}}=
                   2670:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2671:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2672:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2673:     $courseownerbuf{$env{'request.course.id'}}=
                   2674:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2675:     $coursetypebuf{$env{'request.course.id'}}=
                   2676:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2677:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2678: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2679:     } else {
1.620     albertel 2680: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2681:     }
1.620     albertel 2682:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2683: 	&flushcourselogs();
                   2684:     }
1.158     www      2685: }
                   2686: 
                   2687: sub courseacclog {
                   2688:     my $fnsymb=shift;
1.620     albertel 2689:     unless ($env{'request.course.id'}) { return ''; }
                   2690:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2691:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2692:         $what.=':POST';
1.583     matthew  2693:         # FIXME: Probably ought to escape things....
1.800     albertel 2694: 	foreach my $key (keys(%env)) {
                   2695:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2696:                 my $formitem = $1;
                   2697:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2698:                     $what.=':'.$formitem.'='.$env{$key};
                   2699:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2700:                     $what.=':'.$formitem.'='.$env{$key};
                   2701:                 }
1.158     www      2702:             }
1.191     harris41 2703:         }
1.583     matthew  2704:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2705:         # FIXME: We should not be depending on a form parameter that someone
                   2706:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2707:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2708:             $what.= ':POST';
                   2709:             # FIXME: Probably ought to escape things....
                   2710:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2711:                                  'crsdiscuss') {
1.620     albertel 2712:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2713:             }
                   2714:         }
1.158     www      2715:     }
                   2716:     &courselog($what);
1.149     www      2717: }
                   2718: 
1.185     www      2719: sub countacc {
                   2720:     my $url=&declutter(shift);
1.458     matthew  2721:     return if (! defined($url) || $url eq '');
1.620     albertel 2722:     unless ($env{'request.course.id'}) { return ''; }
                   2723:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2724:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2725:     $accesshash{$key}++;
1.185     www      2726: }
1.349     www      2727: 
1.361     www      2728: sub linklog {
                   2729:     my ($from,$to)=@_;
                   2730:     $from=&declutter($from);
                   2731:     $to=&declutter($to);
                   2732:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2733:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2734: }
                   2735:   
1.349     www      2736: sub userrolelog {
                   2737:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2738:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2739:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2740:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  2741:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      2742:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2743:        $userrolehash
                   2744:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2745:                     =$tend.':'.$tstart;
1.662     raeburn  2746:     }
1.898     albertel 2747:     if (($env{'request.role'} =~ /dc\./) &&
                   2748: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2749: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  2750: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   2751:          ($trole=~/^co/))) {
1.898     albertel 2752:        $userrolehash
                   2753:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2754:                     =$tend.':'.$tstart;
                   2755:     }
1.662     raeburn  2756:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2757:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2758:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2759:         ($trole=~/^sc/)) {
                   2760:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2761:        $domainrolehash
                   2762:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2763:                     = $tend.':'.$tstart;
                   2764:     }
1.351     www      2765: }
                   2766: 
1.957     raeburn  2767: sub courserolelog {
                   2768:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2769:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2770:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2771:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  2772:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   2773:         ($trole eq 'co')) {
1.957     raeburn  2774:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2775:             my $cdom = $1;
                   2776:             my $cnum = $2;
                   2777:             my $sec = $3;
                   2778:             my $namespace = 'rolelog';
                   2779:             my %storehash = (
                   2780:                                role    => $trole,
                   2781:                                start   => $tstart,
                   2782:                                end     => $tend,
                   2783:                                selfenroll => $selfenroll,
                   2784:                                context    => $context,
                   2785:                             );
                   2786:             if ($trole eq 'gr') {
                   2787:                 $namespace = 'groupslog';
                   2788:                 $storehash{'group'} = $sec;
                   2789:             } else {
                   2790:                 $storehash{'section'} = $sec;
                   2791:             }
                   2792:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  2793:             if (($trole ne 'st') || ($sec ne '')) {
                   2794:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   2795:             }
1.957     raeburn  2796:         }
                   2797:     }
                   2798:     return;
                   2799: }
                   2800: 
1.351     www      2801: sub get_course_adv_roles {
1.948     raeburn  2802:     my ($cid,$codes) = @_;
1.620     albertel 2803:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2804:     my %coursehash=&coursedescription($cid);
1.988     raeburn  2805:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      2806:     my %nothide=();
1.800     albertel 2807:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2808:         if ($user !~ /:/) {
                   2809: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2810:         } else {
                   2811:             $nothide{$user}=1;
                   2812:         }
1.470     www      2813:     }
1.351     www      2814:     my %returnhash=();
                   2815:     my %dumphash=
                   2816:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2817:     my $now=time;
1.997     raeburn  2818:     my %privileged;
1.1000    raeburn  2819:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 2820: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2821:         if (($tstart) && ($tstart<0)) { next; }
                   2822:         if (($tend) && ($tend<$now)) { next; }
                   2823:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2824:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2825: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  2826:         unless (ref($privileged{$domain}) eq 'HASH') {
                   2827:             my %dompersonnel =
1.998     raeburn  2828:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  2829:             $privileged{$domain} = {};
                   2830:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  2831:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  2832:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2833:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   2834:                         $privileged{$udom}{$uname} = 1;
                   2835:                     }
                   2836:                 }
                   2837:             }
                   2838:         }
                   2839:         if ((exists($privileged{$domain}{$username})) && 
                   2840:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2841: 	if ($role eq 'cr') { next; }
1.948     raeburn  2842:         if ($codes) {
                   2843:             if ($section) { $role .= ':'.$section; }
                   2844:             if ($returnhash{$role}) {
                   2845:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2846:             } else {
                   2847:                 $returnhash{$role}=$username.':'.$domain;
                   2848:             }
1.351     www      2849:         } else {
1.988     raeburn  2850:             my $key=&plaintext($role,$crstype);
1.973     bisitz   2851:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2852:             if ($returnhash{$key}) {
                   2853: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2854:             } else {
                   2855:                 $returnhash{$key}=$username.':'.$domain;
                   2856:             }
1.351     www      2857:         }
1.948     raeburn  2858:     }
1.400     www      2859:     return %returnhash;
                   2860: }
                   2861: 
                   2862: sub get_my_roles {
1.937     raeburn  2863:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2864:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2865:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2866:     my (%dumphash,%nothide);
1.858     raeburn  2867:     if ($context eq 'userroles') { 
                   2868:         %dumphash = &dump('roles',$udom,$uname);
                   2869:     } else {
                   2870:         %dumphash=
1.400     www      2871:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2872:         if ($hidepriv) {
                   2873:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2874:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2875:                 if ($user !~ /:/) {
                   2876:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2877:                 } else {
                   2878:                     $nothide{$user} = 1;
                   2879:                 }
                   2880:             }
                   2881:         }
1.858     raeburn  2882:     }
1.400     www      2883:     my %returnhash=();
                   2884:     my $now=time;
1.999     raeburn  2885:     my %privileged;
1.800     albertel 2886:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2887:         my ($role,$tend,$tstart);
                   2888:         if ($context eq 'userroles') {
                   2889: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2890:         } else {
                   2891:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2892:         }
1.400     www      2893:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2894:         my $status = 'active';
1.939     raeburn  2895:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2896:             $status = 'previous';
                   2897:         } 
                   2898:         if (($tstart) && ($now<$tstart)) {
                   2899:             $status = 'future';
                   2900:         }
                   2901:         if (ref($types) eq 'ARRAY') {
                   2902:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2903:                 next;
                   2904:             } 
                   2905:         } else {
                   2906:             if ($status ne 'active') {
                   2907:                 next;
                   2908:             }
                   2909:         }
1.867     raeburn  2910:         my ($rolecode,$username,$domain,$section,$area);
                   2911:         if ($context eq 'userroles') {
                   2912:             ($area,$rolecode) = split(/_/,$entry);
                   2913:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2914:         } else {
                   2915:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2916:         }
1.832     raeburn  2917:         if (ref($roledoms) eq 'ARRAY') {
                   2918:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2919:                 next;
                   2920:             }
                   2921:         }
                   2922:         if (ref($roles) eq 'ARRAY') {
                   2923:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2924:                 if ($role =~ /^cr\//) {
                   2925:                     if (!grep(/^cr$/,@{$roles})) {
                   2926:                         next;
                   2927:                     }
                   2928:                 } else {
                   2929:                     next;
                   2930:                 }
1.832     raeburn  2931:             }
1.867     raeburn  2932:         }
1.937     raeburn  2933:         if ($hidepriv) {
1.999     raeburn  2934:             if ($context eq 'userroles') {
                   2935:                 if ((&privileged($username,$domain)) &&
                   2936:                     (!$nothide{$username.':'.$domain})) {
                   2937:                     next;
                   2938:                 }
                   2939:             } else {
                   2940:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   2941:                     my %dompersonnel =
                   2942:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   2943:                     $privileged{$domain} = {};
                   2944:                     if (keys(%dompersonnel)) {
                   2945:                         foreach my $server (keys(%dompersonnel)) {
                   2946:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   2947:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   2948:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   2949:                                     $privileged{$udom}{$uname} = $trole;
                   2950:                                 }
                   2951:                             }
                   2952:                         }
                   2953:                     }
                   2954:                 }
                   2955:                 if (exists($privileged{$domain}{$username})) {
                   2956:                     if (!$nothide{$username.':'.$domain}) {
                   2957:                         next;
                   2958:                     }
                   2959:                 }
1.937     raeburn  2960:             }
                   2961:         }
1.933     raeburn  2962:         if ($withsec) {
                   2963:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2964:                 $tstart.':'.$tend;
                   2965:         } else {
                   2966:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2967:         }
1.832     raeburn  2968:     }
1.373     www      2969:     return %returnhash;
1.399     www      2970: }
                   2971: 
                   2972: # ----------------------------------------------------- Frontpage Announcements
                   2973: #
                   2974: #
                   2975: 
                   2976: sub postannounce {
                   2977:     my ($server,$text)=@_;
1.844     albertel 2978:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2979:     unless ($text=~/\w/) { $text=''; }
                   2980:     return &reply('setannounce:'.&escape($text),$server);
                   2981: }
                   2982: 
                   2983: sub getannounce {
1.448     albertel 2984: 
                   2985:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2986: 	my $announcement='';
1.800     albertel 2987: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2988: 	close($fh);
1.399     www      2989: 	if ($announcement=~/\w/) { 
                   2990: 	    return 
                   2991:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2992:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2993: 	} else {
                   2994: 	    return '';
                   2995: 	}
                   2996:     } else {
                   2997: 	return '';
                   2998:     }
1.351     www      2999: }
1.353     www      3000: 
                   3001: # ---------------------------------------------------------- Course ID routines
                   3002: # Deal with domain's nohist_courseid.db files
                   3003: #
                   3004: 
                   3005: sub courseidput {
1.921     raeburn  3006:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   3007:     my $outcome;
                   3008:     if ($caller eq 'timeonly') {
                   3009:         my $cids = '';
                   3010:         foreach my $item (keys(%$storehash)) {
                   3011:             $cids.=&escape($item).'&';
                   3012:         }
                   3013:         $cids=~s/\&$//;
                   3014:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3015:                           $coursehome);       
                   3016:     } else {
                   3017:         my $items = '';
                   3018:         foreach my $item (keys(%$storehash)) {
                   3019:             $items.= &escape($item).'='.
                   3020:                      &freeze_escape($$storehash{$item}).'&';
                   3021:         }
                   3022:         $items=~s/\&$//;
                   3023:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3024:                           $coursehome);
1.918     raeburn  3025:     }
                   3026:     if ($outcome eq 'unknown_cmd') {
                   3027:         my $what;
                   3028:         foreach my $cid (keys(%$storehash)) {
                   3029:             $what .= &escape($cid).'=';
1.921     raeburn  3030:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3031:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3032:             }
                   3033:             $what =~ s/\:$/&/;
                   3034:         }
                   3035:         $what =~ s/\&$//;  
                   3036:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3037:     } else {
                   3038:         return $outcome;
                   3039:     }
1.353     www      3040: }
                   3041: 
                   3042: sub courseiddump {
1.921     raeburn  3043:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3044:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3045:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
                   3046:         $cloneonly,$createdbefore,$createdafter,$creationcontext)=@_;
1.918     raeburn  3047:     my $as_hash = 1;
                   3048:     my %returnhash;
                   3049:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3050:     my %libserv = &all_library();
                   3051:     foreach my $tryserver (keys(%libserv)) {
                   3052:         if ( (  $hostidflag == 1 
                   3053: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3054: 	     || (!defined($hostidflag)) ) {
                   3055: 
1.918     raeburn  3056: 	    if (($domfilter eq '') ||
                   3057: 		(&host_domain($tryserver) eq $domfilter)) {
                   3058:                 my $rep = 
                   3059:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3060:                          $sincefilter.':'.&escape($descfilter).':'.
                   3061:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3062:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3063:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3064:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3065:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3066:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3067:                          &escape($createdbefore).':'.&escape($createdafter).':'.
                   3068:                          &escape($creationcontext),$tryserver);
1.918     raeburn  3069:                 my @pairs=split(/\&/,$rep);
                   3070:                 foreach my $item (@pairs) {
                   3071:                     my ($key,$value)=split(/\=/,$item,2);
                   3072:                     $key = &unescape($key);
                   3073:                     next if ($key =~ /^error: 2 /);
                   3074:                     my $result = &thaw_unescape($value);
                   3075:                     if (ref($result) eq 'HASH') {
                   3076:                         $returnhash{$key}=$result;
                   3077:                     } else {
1.921     raeburn  3078:                         my @responses = split(/:/,$value);
                   3079:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3080:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3081:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3082:                         }
1.1008    raeburn  3083:                     }
1.353     www      3084:                 }
                   3085:             }
                   3086:         }
                   3087:     }
                   3088:     return %returnhash;
                   3089: }
                   3090: 
1.658     raeburn  3091: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3092: 
                   3093: sub dcmailput {
1.685     raeburn  3094:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3095:     my $status = &Apache::lonnet::critical(
1.740     www      3096:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3097:        &escape($message),$server);
1.662     raeburn  3098:     return $status;
                   3099: }
                   3100: 
1.658     raeburn  3101: sub dcmaildump {
                   3102:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3103:     my %returnhash=();
1.846     albertel 3104: 
                   3105:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3106:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3107:                                                          &escape($enddate).':';
                   3108: 	my @esc_senders=map { &escape($_)} @$senders;
                   3109: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3110: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3111:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3112:             if (($key) && ($value)) {
                   3113:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3114:             }
                   3115:         }
                   3116:     }
                   3117:     return %returnhash;
                   3118: }
1.662     raeburn  3119: # ---------------------------------------------------------- Domain roles
                   3120: 
                   3121: sub get_domain_roles {
                   3122:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3123:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3124:         $startdate = '.';
                   3125:     }
1.1018    raeburn  3126:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3127:         $enddate = '.';
                   3128:     }
1.922     raeburn  3129:     my $rolelist;
                   3130:     if (ref($roles) eq 'ARRAY') {
                   3131:         $rolelist = join(':',@{$roles});
                   3132:     }
1.662     raeburn  3133:     my %personnel = ();
1.841     albertel 3134: 
                   3135:     my %servers = &get_servers($dom,'library');
                   3136:     foreach my $tryserver (keys(%servers)) {
                   3137: 	%{$personnel{$tryserver}}=();
                   3138: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3139: 					    &escape($startdate).':'.
                   3140: 					    &escape($enddate).':'.
                   3141: 					    &escape($rolelist), $tryserver))) {
                   3142: 	    my ($key,$value) = split(/\=/,$line,2);
                   3143: 	    if (($key) && ($value)) {
                   3144: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3145: 	    }
                   3146: 	}
1.662     raeburn  3147:     }
                   3148:     return %personnel;
                   3149: }
1.658     raeburn  3150: 
1.149     www      3151: # ----------------------------------------------------------- Check out an item
                   3152: 
1.504     albertel 3153: sub get_first_access {
                   3154:     my ($type,$argsymb)=@_;
1.790     albertel 3155:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3156:     if ($argsymb) { $symb=$argsymb; }
                   3157:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3158:     if ($type eq 'course') {
                   3159: 	$res='course';
                   3160:     } elsif ($type eq 'map') {
1.588     albertel 3161: 	$res=&symbread($map);
                   3162:     } else {
                   3163: 	$res=$symb;
                   3164:     }
                   3165:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3166:     return $times{"$courseid\0$res"};
1.504     albertel 3167: }
                   3168: 
                   3169: sub set_first_access {
                   3170:     my ($type)=@_;
1.790     albertel 3171:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3172:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3173:     if ($type eq 'course') {
                   3174: 	$res='course';
                   3175:     } elsif ($type eq 'map') {
1.588     albertel 3176: 	$res=&symbread($map);
                   3177:     } else {
                   3178: 	$res=$symb;
                   3179:     }
                   3180:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3181:     if (!$firstaccess) {
1.588     albertel 3182: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3183:     }
                   3184:     return 'already_set';
1.504     albertel 3185: }
                   3186: 
1.149     www      3187: sub checkout {
                   3188:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3189:     my $now=time;
                   3190:     my $lonhost=$perlvar{'lonHostID'};
                   3191:     my $infostr=&escape(
1.234     www      3192:                  'CHECKOUTTOKEN&'.
1.149     www      3193:                  $tuname.'&'.
                   3194:                  $tudom.'&'.
                   3195:                  $tcrsid.'&'.
                   3196:                  $symb.'&'.
                   3197: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3198:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3199:     if ($token=~/^error\:/) { 
1.672     albertel 3200:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3201:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3202:                  "</font>");
                   3203:         return ''; 
                   3204:     }
                   3205: 
1.149     www      3206:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3207:     $token=~tr/a-z/A-Z/;
                   3208: 
1.153     www      3209:     my %infohash=('resource.0.outtoken' => $token,
                   3210:                   'resource.0.checkouttime' => $now,
                   3211:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3212: 
                   3213:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3214:        return '';
1.151     www      3215:     } else {
1.672     albertel 3216:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3217:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3218:                  "</font>");
1.149     www      3219:     }    
                   3220: 
                   3221:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3222:                          &escape('Checkout '.$infostr.' - '.
                   3223:                                                  $token)) ne 'ok') {
                   3224: 	return '';
1.151     www      3225:     } else {
1.672     albertel 3226:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3227:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3228:                  "</font>");
1.149     www      3229:     }
1.151     www      3230:     return $token;
1.149     www      3231: }
                   3232: 
                   3233: # ------------------------------------------------------------ Check in an item
                   3234: 
                   3235: sub checkin {
                   3236:     my $token=shift;
1.150     www      3237:     my $now=time;
                   3238:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3239:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3240:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3241:     $dtoken=~s/\W/\_/g;
1.234     www      3242:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3243:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3244: 
1.154     www      3245:     unless (($tuname) && ($tudom)) {
                   3246:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3247:         return '';
                   3248:     }
                   3249:     
                   3250:     unless (&allowed('mgr',$tcrsid)) {
                   3251:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3252:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3253:         return '';
                   3254:     }
                   3255: 
1.153     www      3256:     my %infohash=('resource.0.intoken' => $token,
                   3257:                   'resource.0.checkintime' => $now,
                   3258:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3259: 
                   3260:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3261:        return '';
                   3262:     }    
                   3263: 
                   3264:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3265:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3266: 	return '';
                   3267:     }
                   3268: 
                   3269:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3270: }
                   3271: 
                   3272: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3273: 
                   3274: sub expirespread {
                   3275:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3276:     my $cid=$env{'request.course.id'}; 
1.110     www      3277:     if ($cid) {
                   3278:        my $now=time;
                   3279:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3280:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3281:                             $env{'course.'.$cid.'.num'}.
1.110     www      3282: 	        	    ':nohist_expirationdates:'.
                   3283:                             &escape($key).'='.$now,
1.620     albertel 3284:                             $env{'course.'.$cid.'.home'})
1.110     www      3285:     }
                   3286:     return 'ok';
1.14      www      3287: }
                   3288: 
1.109     www      3289: # ----------------------------------------------------- Devalidate Spreadsheets
                   3290: 
                   3291: sub devalidate {
1.325     www      3292:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3293:     my $cid=$env{'request.course.id'}; 
1.109     www      3294:     if ($cid) {
1.391     matthew  3295:         # delete the stored spreadsheets for
                   3296:         # - the student level sheet of this user in course's homespace
                   3297:         # - the assessment level sheet for this resource 
                   3298:         #   for this user in user's homespace
1.553     albertel 3299: 	# - current conditional state info
1.325     www      3300: 	my $key=$uname.':'.$udom.':';
1.109     www      3301:         my $status=
1.299     matthew  3302: 	    &del('nohist_calculatedsheets',
1.391     matthew  3303: 		 [$key.'studentcalc:'],
1.620     albertel 3304: 		 $env{'course.'.$cid.'.domain'},
                   3305: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3306: 		.' '.
                   3307: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3308: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3309:         unless ($status eq 'ok ok') {
                   3310:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3311:                     $uname.' at '.$udom.' for '.
1.109     www      3312: 		    $symb.': '.$status);
1.133     albertel 3313:         }
1.553     albertel 3314: 	&delenv('user.state.'.$cid);
1.109     www      3315:     }
                   3316: }
                   3317: 
1.265     albertel 3318: sub get_scalar {
                   3319:     my ($string,$end) = @_;
                   3320:     my $value;
                   3321:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3322: 	$value = $1;
                   3323:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3324: 	$value = $1;
                   3325:     }
                   3326:     return &unescape($value);
                   3327: }
                   3328: 
                   3329: sub array2str {
                   3330:   my (@array) = @_;
                   3331:   my $result=&arrayref2str(\@array);
                   3332:   $result=~s/^__ARRAY_REF__//;
                   3333:   $result=~s/__END_ARRAY_REF__$//;
                   3334:   return $result;
                   3335: }
                   3336: 
1.204     albertel 3337: sub arrayref2str {
                   3338:   my ($arrayref) = @_;
1.265     albertel 3339:   my $result='__ARRAY_REF__';
1.204     albertel 3340:   foreach my $elem (@$arrayref) {
1.265     albertel 3341:     if(ref($elem) eq 'ARRAY') {
                   3342:       $result.=&arrayref2str($elem).'&';
                   3343:     } elsif(ref($elem) eq 'HASH') {
                   3344:       $result.=&hashref2str($elem).'&';
                   3345:     } elsif(ref($elem)) {
                   3346:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3347:     } else {
                   3348:       $result.=&escape($elem).'&';
                   3349:     }
                   3350:   }
                   3351:   $result=~s/\&$//;
1.265     albertel 3352:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3353:   return $result;
                   3354: }
                   3355: 
1.168     albertel 3356: sub hash2str {
1.204     albertel 3357:   my (%hash) = @_;
                   3358:   my $result=&hashref2str(\%hash);
1.265     albertel 3359:   $result=~s/^__HASH_REF__//;
                   3360:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3361:   return $result;
                   3362: }
                   3363: 
                   3364: sub hashref2str {
                   3365:   my ($hashref)=@_;
1.265     albertel 3366:   my $result='__HASH_REF__';
1.800     albertel 3367:   foreach my $key (sort(keys(%$hashref))) {
                   3368:     if (ref($key) eq 'ARRAY') {
                   3369:       $result.=&arrayref2str($key).'=';
                   3370:     } elsif (ref($key) eq 'HASH') {
                   3371:       $result.=&hashref2str($key).'=';
                   3372:     } elsif (ref($key)) {
1.265     albertel 3373:       $result.='=';
1.800     albertel 3374:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3375:     } else {
1.800     albertel 3376: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3377:     }
                   3378: 
1.800     albertel 3379:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3380:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3381:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3382:       $result.=&hashref2str($hashref->{$key}).'&';
                   3383:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3384:        $result.='&';
1.800     albertel 3385:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3386:     } else {
1.800     albertel 3387:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3388:     }
                   3389:   }
1.168     albertel 3390:   $result=~s/\&$//;
1.265     albertel 3391:   $result .= '__END_HASH_REF__';
1.168     albertel 3392:   return $result;
                   3393: }
                   3394: 
                   3395: sub str2hash {
1.265     albertel 3396:     my ($string)=@_;
                   3397:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3398:     return %$hash;
                   3399: }
                   3400: 
                   3401: sub str2hashref {
1.168     albertel 3402:   my ($string) = @_;
1.265     albertel 3403: 
                   3404:   my %hash;
                   3405: 
                   3406:   if($string !~ /^__HASH_REF__/) {
                   3407:       if (! ($string eq '' || !defined($string))) {
                   3408: 	  $hash{'error'}='Not hash reference';
                   3409:       }
                   3410:       return (\%hash, $string);
                   3411:   }
                   3412: 
                   3413:   $string =~ s/^__HASH_REF__//;
                   3414: 
                   3415:   while($string !~ /^__END_HASH_REF__/) {
                   3416:       #key
                   3417:       my $key='';
                   3418:       if($string =~ /^__HASH_REF__/) {
                   3419:           ($key, $string)=&str2hashref($string);
                   3420:           if(defined($key->{'error'})) {
                   3421:               $hash{'error'}='Bad data';
                   3422:               return (\%hash, $string);
                   3423:           }
                   3424:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3425:           ($key, $string)=&str2arrayref($string);
                   3426:           if($key->[0] eq 'Array reference error') {
                   3427:               $hash{'error'}='Bad data';
                   3428:               return (\%hash, $string);
                   3429:           }
                   3430:       } else {
                   3431:           $string =~ s/^(.*?)=//;
1.267     albertel 3432: 	  $key=&unescape($1);
1.265     albertel 3433:       }
                   3434:       $string =~ s/^=//;
                   3435: 
                   3436:       #value
                   3437:       my $value='';
                   3438:       if($string =~ /^__HASH_REF__/) {
                   3439:           ($value, $string)=&str2hashref($string);
                   3440:           if(defined($value->{'error'})) {
                   3441:               $hash{'error'}='Bad data';
                   3442:               return (\%hash, $string);
                   3443:           }
                   3444:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3445:           ($value, $string)=&str2arrayref($string);
                   3446:           if($value->[0] eq 'Array reference error') {
                   3447:               $hash{'error'}='Bad data';
                   3448:               return (\%hash, $string);
                   3449:           }
                   3450:       } else {
                   3451: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3452:       }
                   3453:       $string =~ s/^&//;
                   3454: 
                   3455:       $hash{$key}=$value;
1.204     albertel 3456:   }
1.265     albertel 3457: 
                   3458:   $string =~ s/^__END_HASH_REF__//;
                   3459: 
                   3460:   return (\%hash, $string);
1.204     albertel 3461: }
                   3462: 
                   3463: sub str2array {
1.265     albertel 3464:     my ($string)=@_;
                   3465:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3466:     return @$array;
                   3467: }
                   3468: 
                   3469: sub str2arrayref {
1.204     albertel 3470:   my ($string) = @_;
1.265     albertel 3471:   my @array;
                   3472: 
                   3473:   if($string !~ /^__ARRAY_REF__/) {
                   3474:       if (! ($string eq '' || !defined($string))) {
                   3475: 	  $array[0]='Array reference error';
                   3476:       }
                   3477:       return (\@array, $string);
                   3478:   }
                   3479: 
                   3480:   $string =~ s/^__ARRAY_REF__//;
                   3481: 
                   3482:   while($string !~ /^__END_ARRAY_REF__/) {
                   3483:       my $value='';
                   3484:       if($string =~ /^__HASH_REF__/) {
                   3485:           ($value, $string)=&str2hashref($string);
                   3486:           if(defined($value->{'error'})) {
                   3487:               $array[0] ='Array reference error';
                   3488:               return (\@array, $string);
                   3489:           }
                   3490:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3491:           ($value, $string)=&str2arrayref($string);
                   3492:           if($value->[0] eq 'Array reference error') {
                   3493:               $array[0] ='Array reference error';
                   3494:               return (\@array, $string);
                   3495:           }
                   3496:       } else {
                   3497: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3498:       }
                   3499:       $string =~ s/^&//;
                   3500: 
                   3501:       push(@array, $value);
1.191     harris41 3502:   }
1.265     albertel 3503: 
                   3504:   $string =~ s/^__END_ARRAY_REF__//;
                   3505: 
                   3506:   return (\@array, $string);
1.168     albertel 3507: }
                   3508: 
1.167     albertel 3509: # -------------------------------------------------------------------Temp Store
                   3510: 
1.168     albertel 3511: sub tmpreset {
                   3512:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3513:   if (!$symb) {
                   3514:     $symb=&symbread();
1.620     albertel 3515:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3516:   }
                   3517:   $symb=escape($symb);
                   3518: 
1.620     albertel 3519:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3520:   $namespace=~s/\//\_/g;
                   3521:   $namespace=~s/\W//g;
                   3522: 
1.620     albertel 3523:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3524:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3525:   if ($domain eq 'public' && $stuname eq 'public') {
                   3526:       $stuname=$ENV{'REMOTE_ADDR'};
                   3527:   }
1.168     albertel 3528:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3529:   my %hash;
                   3530:   if (tie(%hash,'GDBM_File',
                   3531: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3532: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  3533:     foreach my $key (keys(%hash)) {
1.180     albertel 3534:       if ($key=~ /:$symb/) {
1.168     albertel 3535: 	delete($hash{$key});
                   3536:       }
                   3537:     }
                   3538:   }
                   3539: }
                   3540: 
1.167     albertel 3541: sub tmpstore {
1.168     albertel 3542:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3543: 
                   3544:   if (!$symb) {
                   3545:     $symb=&symbread();
1.620     albertel 3546:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3547:   }
                   3548:   $symb=escape($symb);
                   3549: 
                   3550:   if (!$namespace) {
                   3551:     # I don't think we would ever want to store this for a course.
                   3552:     # it seems this will only be used if we don't have a course.
1.620     albertel 3553:     #$namespace=$env{'request.course.id'};
1.168     albertel 3554:     #if (!$namespace) {
1.620     albertel 3555:       $namespace=$env{'request.state'};
1.168     albertel 3556:     #}
                   3557:   }
                   3558:   $namespace=~s/\//\_/g;
                   3559:   $namespace=~s/\W//g;
1.620     albertel 3560:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3561:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3562:   if ($domain eq 'public' && $stuname eq 'public') {
                   3563:       $stuname=$ENV{'REMOTE_ADDR'};
                   3564:   }
1.168     albertel 3565:   my $now=time;
                   3566:   my %hash;
                   3567:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3568:   if (tie(%hash,'GDBM_File',
                   3569: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3570: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3571:     $hash{"version:$symb"}++;
                   3572:     my $version=$hash{"version:$symb"};
                   3573:     my $allkeys=''; 
                   3574:     foreach my $key (keys(%$storehash)) {
                   3575:       $allkeys.=$key.':';
1.591     albertel 3576:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3577:     }
                   3578:     $hash{"$version:$symb:timestamp"}=$now;
                   3579:     $allkeys.='timestamp';
                   3580:     $hash{"$version:keys:$symb"}=$allkeys;
                   3581:     if (untie(%hash)) {
                   3582:       return 'ok';
                   3583:     } else {
                   3584:       return "error:$!";
                   3585:     }
                   3586:   } else {
                   3587:     return "error:$!";
                   3588:   }
                   3589: }
1.167     albertel 3590: 
1.168     albertel 3591: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3592: 
1.168     albertel 3593: sub tmprestore {
                   3594:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3595: 
1.168     albertel 3596:   if (!$symb) {
                   3597:     $symb=&symbread();
1.620     albertel 3598:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3599:   }
                   3600:   $symb=escape($symb);
                   3601: 
1.620     albertel 3602:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3603: 
1.620     albertel 3604:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3605:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3606:   if ($domain eq 'public' && $stuname eq 'public') {
                   3607:       $stuname=$ENV{'REMOTE_ADDR'};
                   3608:   }
1.168     albertel 3609:   my %returnhash;
                   3610:   $namespace=~s/\//\_/g;
                   3611:   $namespace=~s/\W//g;
                   3612:   my %hash;
                   3613:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3614:   if (tie(%hash,'GDBM_File',
                   3615: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3616: 	  &GDBM_READER(),0640)) {
1.168     albertel 3617:     my $version=$hash{"version:$symb"};
                   3618:     $returnhash{'version'}=$version;
                   3619:     my $scope;
                   3620:     for ($scope=1;$scope<=$version;$scope++) {
                   3621:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3622:       my @keys=split(/:/,$vkeys);
                   3623:       my $key;
                   3624:       $returnhash{"$scope:keys"}=$vkeys;
                   3625:       foreach $key (@keys) {
1.591     albertel 3626: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3627: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3628:       }
                   3629:     }
1.168     albertel 3630:     if (!(untie(%hash))) {
                   3631:       return "error:$!";
                   3632:     }
                   3633:   } else {
                   3634:     return "error:$!";
                   3635:   }
                   3636:   return %returnhash;
1.167     albertel 3637: }
                   3638: 
1.9       www      3639: # ----------------------------------------------------------------------- Store
                   3640: 
                   3641: sub store {
1.124     www      3642:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3643:     my $home='';
                   3644: 
1.168     albertel 3645:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3646: 
1.213     www      3647:     $symb=&symbclean($symb);
1.122     albertel 3648:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3649: 
1.620     albertel 3650:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3651:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3652: 
                   3653:     &devalidate($symb,$stuname,$domain);
1.109     www      3654: 
                   3655:     $symb=escape($symb);
1.187     www      3656:     if (!$namespace) { 
1.620     albertel 3657:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3658:           return ''; 
                   3659:        } 
                   3660:     }
1.620     albertel 3661:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3662: 
                   3663:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3664:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3665: 
1.12      www      3666:     my $namevalue='';
1.800     albertel 3667:     foreach my $key (keys(%$storehash)) {
                   3668:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3669:     }
1.12      www      3670:     $namevalue=~s/\&$//;
1.187     www      3671:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3672:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3673: }
                   3674: 
1.47      www      3675: # -------------------------------------------------------------- Critical Store
                   3676: 
                   3677: sub cstore {
1.124     www      3678:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3679:     my $home='';
                   3680: 
1.168     albertel 3681:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3682: 
1.213     www      3683:     $symb=&symbclean($symb);
1.122     albertel 3684:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3685: 
1.620     albertel 3686:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3687:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3688: 
                   3689:     &devalidate($symb,$stuname,$domain);
1.109     www      3690: 
                   3691:     $symb=escape($symb);
1.187     www      3692:     if (!$namespace) { 
1.620     albertel 3693:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3694:           return ''; 
                   3695:        } 
                   3696:     }
1.620     albertel 3697:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3698: 
                   3699:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3700:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3701: 
1.47      www      3702:     my $namevalue='';
1.800     albertel 3703:     foreach my $key (keys(%$storehash)) {
                   3704:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3705:     }
1.47      www      3706:     $namevalue=~s/\&$//;
1.187     www      3707:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3708:     return critical
                   3709:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3710: }
                   3711: 
1.9       www      3712: # --------------------------------------------------------------------- Restore
                   3713: 
                   3714: sub restore {
1.124     www      3715:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3716:     my $home='';
                   3717: 
1.168     albertel 3718:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3719: 
1.122     albertel 3720:     if (!$symb) {
                   3721:       unless ($symb=escape(&symbread())) { return ''; }
                   3722:     } else {
1.213     www      3723:       $symb=&escape(&symbclean($symb));
1.122     albertel 3724:     }
1.188     www      3725:     if (!$namespace) { 
1.620     albertel 3726:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3727:           return ''; 
                   3728:        } 
                   3729:     }
1.620     albertel 3730:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3731:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3732:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3733:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3734: 
1.12      www      3735:     my %returnhash=();
1.800     albertel 3736:     foreach my $line (split(/\&/,$answer)) {
                   3737: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3738:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3739:     }
1.75      www      3740:     my $version;
                   3741:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3742:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3743:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3744:        }
1.75      www      3745:     }
1.13      www      3746:     return %returnhash;
1.34      www      3747: }
                   3748: 
                   3749: # ---------------------------------------------------------- Course Description
                   3750: 
                   3751: sub coursedescription {
1.731     albertel 3752:     my ($courseid,$args)=@_;
1.34      www      3753:     $courseid=~s/^\///;
1.49      www      3754:     $courseid=~s/\_/\//g;
1.34      www      3755:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3756:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3757:     my $normalid=$cdomain.'_'.$cnum;
                   3758:     # need to always cache even if we get errors otherwise we keep 
                   3759:     # trying and trying and trying to get the course description.
                   3760:     my %envhash=();
                   3761:     my %returnhash=();
1.731     albertel 3762:     
                   3763:     my $expiretime=600;
                   3764:     if ($env{'request.course.id'} eq $normalid) {
                   3765: 	$expiretime=120;
                   3766:     }
                   3767: 
                   3768:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3769:     if (!$args->{'freshen_cache'}
                   3770: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3771: 	foreach my $key (keys(%env)) {
                   3772: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3773: 	    my ($setting) = $1;
                   3774: 	    $returnhash{$setting} = $env{$key};
                   3775: 	}
                   3776: 	return %returnhash;
                   3777:     }
                   3778: 
                   3779:     # get the data agin
                   3780:     if (!$args->{'one_time'}) {
                   3781: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3782:     }
1.811     albertel 3783: 
1.34      www      3784:     if ($chome ne 'no_host') {
1.302     albertel 3785:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3786:        if (!exists($returnhash{'con_lost'})) {
                   3787:            $returnhash{'home'}= $chome;
                   3788: 	   $returnhash{'domain'} = $cdomain;
                   3789: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3790:            if (!defined($returnhash{'type'})) {
                   3791:                $returnhash{'type'} = 'Course';
                   3792:            }
1.130     albertel 3793:            while (my ($name,$value) = each %returnhash) {
1.53      www      3794:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3795:            }
1.270     www      3796:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3797:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3798: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3799:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3800:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3801:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3802:        }
                   3803:     }
1.731     albertel 3804:     if (!$args->{'one_time'}) {
1.949     raeburn  3805: 	&appenv(\%envhash);
1.731     albertel 3806:     }
1.302     albertel 3807:     return %returnhash;
1.461     www      3808: }
                   3809: 
                   3810: # -------------------------------------------------See if a user is privileged
                   3811: 
                   3812: sub privileged {
                   3813:     my ($username,$domain)=@_;
                   3814:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3815: 			&homeserver($username,$domain));
1.1033    raeburn  3816:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   3817:         ($rolesdump =~ /^error:/)) {
                   3818:         return 0;
                   3819:     }
1.461     www      3820:     my $now=time;
                   3821:     if ($rolesdump ne '') {
1.800     albertel 3822:         foreach my $entry (split(/&/,$rolesdump)) {
                   3823: 	    if ($entry!~/^rolesdef_/) {
                   3824: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3825: 		$area=~s/\_\w\w$//;
                   3826: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3827: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3828: 		    my $active=1;
                   3829: 		    if ($tend) {
                   3830: 			if ($tend<$now) { $active=0; }
                   3831: 		    }
                   3832: 		    if ($tstart) {
                   3833: 			if ($tstart>$now) { $active=0; }
                   3834: 		    }
                   3835: 		    if ($active) { return 1; }
                   3836: 		}
                   3837: 	    }
                   3838: 	}
                   3839:     }
                   3840:     return 0;
1.9       www      3841: }
1.1       albertel 3842: 
1.103     harris41 3843: # -------------------------------------------------------- Get user privileges
1.11      www      3844: 
                   3845: sub rolesinit {
                   3846:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  3847:     my $now=time;
                   3848:     my %userroles = ('user.login.time' => $now);
1.11      www      3849:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.1033    raeburn  3850:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   3851:         ($rolesdump =~ /^error:/)) { 
                   3852:         return \%userroles;
                   3853:     }
1.11      www      3854:     my %allroles=();
1.678     raeburn  3855:     my %allgroups=();   
                   3856:     my $group_privs;
1.11      www      3857: 
                   3858:     if ($rolesdump ne '') {
1.800     albertel 3859:         foreach my $entry (split(/&/,$rolesdump)) {
                   3860: 	  if ($entry!~/^rolesdef_/) {
                   3861:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3862: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3863:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3864: 	    if ($role=~/^cr/) { 
1.807     albertel 3865: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3866: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3867: 		    ($tend,$tstart)=split('_',$trest);
                   3868: 		} else {
                   3869: 		    $trole=$role;
                   3870: 		}
1.678     raeburn  3871:             } elsif ($role =~ m|^gr/|) {
                   3872:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3873:                 ($trole,$group_privs) = split(/\//,$trole);
                   3874:                 $group_privs = &unescape($group_privs);
1.587     albertel 3875: 	    } else {
                   3876: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3877: 	    }
1.743     albertel 3878: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3879: 					 $username);
                   3880: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3881:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3882:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3883:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3884: 		my $spec=$trole.'.'.$area;
                   3885: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3886: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3887:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3888:                 } elsif ($trole eq 'gr') {
                   3889:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3890: 		} else {
1.567     raeburn  3891:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3892: 		}
1.12      www      3893:             }
1.662     raeburn  3894:           }
1.191     harris41 3895:         }
1.743     albertel 3896:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3897:         $userroles{'user.adv'}    = $adv;
                   3898: 	$userroles{'user.author'} = $author;
1.620     albertel 3899:         $env{'user.adv'}=$adv;
1.11      www      3900:     }
1.743     albertel 3901:     return \%userroles;  
1.11      www      3902: }
                   3903: 
1.567     raeburn  3904: sub set_arearole {
                   3905:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3906: # log the associated role with the area
                   3907:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3908:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3909: }
                   3910: 
                   3911: sub custom_roleprivs {
                   3912:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3913:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3914:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3915:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3916:         my ($rdummy,$roledef)=
                   3917:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3918:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3919:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3920:             if (defined($syspriv)) {
1.1043    raeburn  3921:                 if ($trest =~ /^$match_community$/) {
                   3922:                     $syspriv =~ s/bre\&S//; 
                   3923:                 }
1.567     raeburn  3924:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3925:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3926:             }
                   3927:             if ($tdomain ne '') {
                   3928:                 if (defined($dompriv)) {
                   3929:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3930:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3931:                 }
                   3932:                 if (($trest ne '') && (defined($coursepriv))) {
                   3933:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3934:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3935:                 }
                   3936:             }
                   3937:         }
                   3938:     }
                   3939: }
                   3940: 
1.678     raeburn  3941: sub group_roleprivs {
                   3942:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3943:     my $access = 1;
                   3944:     my $now = time;
                   3945:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3946:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3947:     if ($access) {
1.811     albertel 3948:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3949:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3950:     }
                   3951: }
1.567     raeburn  3952: 
                   3953: sub standard_roleprivs {
                   3954:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3955:     if (defined($pr{$trole.':s'})) {
                   3956:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3957:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3958:     }
                   3959:     if ($tdomain ne '') {
                   3960:         if (defined($pr{$trole.':d'})) {
                   3961:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3962:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3963:         }
                   3964:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3965:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3966:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3967:         }
                   3968:     }
                   3969: }
                   3970: 
                   3971: sub set_userprivs {
1.678     raeburn  3972:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3973:     my $author=0;
                   3974:     my $adv=0;
1.678     raeburn  3975:     my %grouproles = ();
                   3976:     if (keys(%{$allgroups}) > 0) {
1.1000    raeburn  3977:         foreach my $role (keys(%{$allroles})) {
1.681     raeburn  3978:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3979:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3980:                 $trole = $1;
                   3981:                 $area = $2;
1.681     raeburn  3982:                 $sec = $3;
                   3983:                 $extendedarea = $area.$sec;
                   3984:                 if (exists($$allgroups{$area})) {
                   3985:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3986:                         my $spec = $trole.'.'.$extendedarea;
                   3987:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3988:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3989:                     }
                   3990:                 }
                   3991:             }
                   3992:         }
                   3993:     }
1.800     albertel 3994:     foreach my $group (keys(%grouproles)) {
                   3995:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3996:     }
1.800     albertel 3997:     foreach my $role (keys(%{$allroles})) {
                   3998:         my %thesepriv;
1.941     raeburn  3999:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4000:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4001:             if ($item ne '') {
                   4002:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4003:                 if ($restrictions eq '') {
                   4004:                     $thesepriv{$privilege}='F';
                   4005:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4006:                     $thesepriv{$privilege}.=$restrictions;
                   4007:                 }
                   4008:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4009:             }
                   4010:         }
                   4011:         my $thesestr='';
1.800     albertel 4012:         foreach my $priv (keys(%thesepriv)) {
                   4013: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4014: 	}
                   4015:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4016:     }
                   4017:     return ($author,$adv);
                   4018: }
                   4019: 
1.994     raeburn  4020: sub role_status {
1.1002    raeburn  4021:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4022:     my @pwhere = ();
                   4023:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4024:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4025:         unless (!defined($$role) || $$role eq '') {
                   4026:             $$where=join('.',@pwhere);
                   4027:             $$trolecode=$$role.'.'.$$where;
                   4028:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4029:             $$tstatus='is';
                   4030:             if ($$tstart && $$tstart>$then) {
                   4031:                 $$tstatus='future';
1.1034    raeburn  4032:                 if ($$tstart<$now) {
                   4033:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4034:                         if (($$where ne '') && ($$role ne '')) {
                   4035:                             my (%allroles,%allgroups,$group_privs);
                   4036:                             my %userroles = (
                   4037:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4038:                             );
                   4039:                             my $spec=$$role.'.'.$$where;
                   4040:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4041:                             if ($$role =~ /^cr\//) {
                   4042:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
                   4043:                             } elsif ($$role eq 'gr') {
                   4044:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4045:                                                     $env{'user.name'});
                   4046:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
                   4047:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4048:                                 $group_privs = &unescape($group_privs);
                   4049:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
                   4050:                             } else {
                   4051:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4052:                             }
                   4053:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4054:                             &appenv(\%userroles,[$$role,'cm']);
                   4055:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4056:                         }
                   4057:                     }
1.1034    raeburn  4058:                     $$tstatus = 'is';
1.1002    raeburn  4059:                 }
1.994     raeburn  4060:             }
                   4061:             if ($$tend) {
                   4062:                 if ($$tend<$then) {
                   4063:                     $$tstatus='expired';
                   4064:                 } elsif ($$tend<$now) {
                   4065:                     $$tstatus='will_not';
                   4066:                 }
                   4067:             }
                   4068:         }
                   4069:     }
                   4070: }
                   4071: 
1.1048.2.2  raeburn  4072: sub curr_role_status {
                   4073:     my ($start,$end,$refresh,$then) = @_;
                   4074:     if (($start) && ($start<0)) { return 'deleted' };
                   4075:     my $status = 'active';
                   4076:     if (($end) && ($end<=$then)) {
                   4077:         $status = 'previous';
                   4078:     }
                   4079:     if (($start) && ($refresh<$start)) {
                   4080:         $status = 'future';
                   4081:     }
                   4082:     return $status;
                   4083: }
                   4084: 
                   4085: sub gather_roleprivs {
                   4086:     my ($allroles,$allgroups,$userroles,$area,$role,$tstart,$tend) = @_;
                   4087:     return unless ((ref($allroles) eq 'HASH') && (ref($allgroups) eq 'HASH') && (ref($userroles) eq 'HASH'));
                   4088:     if (($area ne '') && ($role ne '')) {
                   4089:         my $spec = $role.'.'.$area;
                   4090:         my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4091:         if ($role =~ /^cr\//) {
                   4092:             &custom_roleprivs($allroles,$role,$tdomain,$trest,$spec,$area);
                   4093:         } elsif ($role eq 'gr') {
                   4094:             my %rolehash = &get('roles',[$area.'_'.$role],$env{'user.domain'},
                   4095:                                 $env{'user.name'});
                   4096:             my $trole = split('_',$rolehash{$area.'_'.$role},1);
                   4097:             (undef,my $group_privs) = split(/\//,$trole);
                   4098:             $group_privs = &unescape($group_privs);
                   4099:             &group_roleprivs($allgroups,$area,$group_privs,$tend,$tstart);
                   4100:         } else {
                   4101:             &standard_roleprivs($allroles,$role,$tdomain,$spec,$trest,$area);
                   4102:         }
                   4103:     }
                   4104:     return;
                   4105: }
                   4106: 
1.994     raeburn  4107: sub check_adhoc_privs {
1.1002    raeburn  4108:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994     raeburn  4109:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4110:     if ($env{$cckey}) {
                   4111:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002    raeburn  4112:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4113:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
                   4114:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4115:         }
                   4116:     } else {
                   4117:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
                   4118:     }
                   4119: }
                   4120: 
                   4121: sub set_adhoc_privileges {
                   4122: # role can be cc or ca
                   4123:     my ($dcdom,$pickedcourse,$role) = @_;
                   4124:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4125:     my $spec = $role.'.'.$area;
                   4126:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4127:                                   $env{'user.name'});
                   4128:     my %ccrole = ();
                   4129:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4130:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4131:     &appenv(\%userroles,[$role,'cm']);
                   4132:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4133:     &appenv( {'request.role'        => $spec,
                   4134:               'request.role.domain' => $dcdom,
                   4135:               'request.course.sec'  => ''
                   4136:              }
                   4137:            );
                   4138:     my $tadv=0;
                   4139:     if (&allowed('adv') eq 'F') { $tadv=1; }
                   4140:     &appenv({'request.role.adv'    => $tadv});
                   4141: }
                   4142: 
1.12      www      4143: # --------------------------------------------------------------- get interface
                   4144: 
                   4145: sub get {
1.131     albertel 4146:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4147:    my $items='';
1.800     albertel 4148:    foreach my $item (@$storearr) {
                   4149:        $items.=&escape($item).'&';
1.191     harris41 4150:    }
1.12      www      4151:    $items=~s/\&$//;
1.620     albertel 4152:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4153:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4154:    my $uhome=&homeserver($uname,$udomain);
                   4155: 
1.133     albertel 4156:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4157:    my @pairs=split(/\&/,$rep);
1.273     albertel 4158:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4159:      return @pairs;
                   4160:    }
1.15      www      4161:    my %returnhash=();
1.42      www      4162:    my $i=0;
1.800     albertel 4163:    foreach my $item (@$storearr) {
                   4164:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4165:       $i++;
1.191     harris41 4166:    }
1.15      www      4167:    return %returnhash;
1.27      www      4168: }
                   4169: 
                   4170: # --------------------------------------------------------------- del interface
                   4171: 
                   4172: sub del {
1.133     albertel 4173:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4174:    my $items='';
1.800     albertel 4175:    foreach my $item (@$storearr) {
                   4176:        $items.=&escape($item).'&';
1.191     harris41 4177:    }
1.984     neumanie 4178: 
1.27      www      4179:    $items=~s/\&$//;
1.620     albertel 4180:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4181:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4182:    my $uhome=&homeserver($uname,$udomain);
                   4183:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4184: }
                   4185: 
                   4186: # -------------------------------------------------------------- dump interface
                   4187: 
                   4188: sub dump {
1.755     albertel 4189:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   4190:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4191:     if (!$uname) { $uname=$env{'user.name'}; }
                   4192:     my $uhome=&homeserver($uname,$udomain);
                   4193:     if ($regexp) {
                   4194: 	$regexp=&escape($regexp);
                   4195:     } else {
                   4196: 	$regexp='.';
                   4197:     }
                   4198:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4199:     my @pairs=split(/\&/,$rep);
                   4200:     my %returnhash=();
                   4201:     foreach my $item (@pairs) {
                   4202: 	my ($key,$value)=split(/=/,$item,2);
                   4203: 	$key = &unescape($key);
                   4204: 	next if ($key =~ /^error: 2 /);
                   4205: 	$returnhash{$key}=&thaw_unescape($value);
                   4206:     }
                   4207:     return %returnhash;
1.407     www      4208: }
                   4209: 
1.717     albertel 4210: # --------------------------------------------------------- dumpstore interface
                   4211: 
                   4212: sub dumpstore {
                   4213:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4214:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4215:    if (!$uname) { $uname=$env{'user.name'}; }
                   4216:    my $uhome=&homeserver($uname,$udomain);
                   4217:    if ($regexp) {
                   4218:        $regexp=&escape($regexp);
                   4219:    } else {
                   4220:        $regexp='.';
                   4221:    }
                   4222:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4223:    my @pairs=split(/\&/,$rep);
                   4224:    my %returnhash=();
                   4225:    foreach my $item (@pairs) {
                   4226:        my ($key,$value)=split(/=/,$item,2);
                   4227:        next if ($key =~ /^error: 2 /);
                   4228:        $returnhash{$key}=&thaw_unescape($value);
                   4229:    }
                   4230:    return %returnhash;
1.717     albertel 4231: }
                   4232: 
1.407     www      4233: # -------------------------------------------------------------- keys interface
                   4234: 
                   4235: sub getkeys {
                   4236:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4237:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4238:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4239:    my $uhome=&homeserver($uname,$udomain);
                   4240:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4241:    my @keyarray=();
1.800     albertel 4242:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4243:       next if ($key =~ /^error: 2 /);
1.800     albertel 4244:       push(@keyarray,&unescape($key));
1.407     www      4245:    }
                   4246:    return @keyarray;
1.318     matthew  4247: }
                   4248: 
1.319     matthew  4249: # --------------------------------------------------------------- currentdump
                   4250: sub currentdump {
1.328     matthew  4251:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4252:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4253:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4254:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4255:    my $uhome = &homeserver($sname,$sdom);
                   4256:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4257:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4258:    #
1.318     matthew  4259:    my %returnhash=();
1.319     matthew  4260:    #
                   4261:    if ($rep eq "unknown_cmd") { 
                   4262:        # an old lond will not know currentdump
                   4263:        # Do a dump and make it look like a currentdump
1.822     albertel 4264:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4265:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4266:        my %hash = @tmp;
                   4267:        @tmp=();
1.424     matthew  4268:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4269:    } else {
                   4270:        my @pairs=split(/\&/,$rep);
1.800     albertel 4271:        foreach my $pair (@pairs) {
                   4272:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4273:            my ($symb,$param) = split(/:/,$key);
                   4274:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4275:                                                         &thaw_unescape($value);
1.319     matthew  4276:        }
1.191     harris41 4277:    }
1.12      www      4278:    return %returnhash;
1.424     matthew  4279: }
                   4280: 
                   4281: sub convert_dump_to_currentdump{
                   4282:     my %hash = %{shift()};
                   4283:     my %returnhash;
                   4284:     # Code ripped from lond, essentially.  The only difference
                   4285:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4286:     # we might run in to problems with parameter names =~ /^v\./
                   4287:     while (my ($key,$value) = each(%hash)) {
                   4288:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4289: 	$symb  = &unescape($symb);
                   4290: 	$param = &unescape($param);
1.424     matthew  4291:         next if ($v eq 'version' || $symb eq 'keys');
                   4292:         next if (exists($returnhash{$symb}) &&
                   4293:                  exists($returnhash{$symb}->{$param}) &&
                   4294:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   4295:         $returnhash{$symb}->{$param}=$value;
                   4296:         $returnhash{$symb}->{'v.'.$param}=$v;
                   4297:     }
                   4298:     #
                   4299:     # Remove all of the keys in the hashes which keep track of
                   4300:     # the version of the parameter.
                   4301:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   4302:         # use a foreach because we are going to delete from the hash.
                   4303:         foreach my $key (keys(%$param_hash)) {
                   4304:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4305:         }
                   4306:     }
                   4307:     return \%returnhash;
1.12      www      4308: }
                   4309: 
1.627     albertel 4310: # ------------------------------------------------------ critical inc interface
                   4311: 
                   4312: sub cinc {
                   4313:     return &inc(@_,'critical');
                   4314: }
                   4315: 
1.449     matthew  4316: # --------------------------------------------------------------- inc interface
                   4317: 
                   4318: sub inc {
1.627     albertel 4319:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4320:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4321:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4322:     my $uhome=&homeserver($uname,$udomain);
                   4323:     my $items='';
                   4324:     if (! ref($store)) {
                   4325:         # got a single value, so use that instead
                   4326:         $items = &escape($store).'=&';
                   4327:     } elsif (ref($store) eq 'SCALAR') {
                   4328:         $items = &escape($$store).'=&';        
                   4329:     } elsif (ref($store) eq 'ARRAY') {
                   4330:         $items = join('=&',map {&escape($_);} @{$store});
                   4331:     } elsif (ref($store) eq 'HASH') {
                   4332:         while (my($key,$value) = each(%{$store})) {
                   4333:             $items.= &escape($key).'='.&escape($value).'&';
                   4334:         }
                   4335:     }
                   4336:     $items=~s/\&$//;
1.627     albertel 4337:     if ($critical) {
                   4338: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4339:     } else {
                   4340: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4341:     }
1.449     matthew  4342: }
                   4343: 
1.12      www      4344: # --------------------------------------------------------------- put interface
                   4345: 
                   4346: sub put {
1.134     albertel 4347:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4348:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4349:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4350:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4351:    my $items='';
1.800     albertel 4352:    foreach my $item (keys(%$storehash)) {
                   4353:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4354:    }
1.12      www      4355:    $items=~s/\&$//;
1.134     albertel 4356:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4357: }
                   4358: 
1.631     albertel 4359: # ------------------------------------------------------------ newput interface
                   4360: 
                   4361: sub newput {
                   4362:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4363:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4364:    if (!$uname) { $uname=$env{'user.name'}; }
                   4365:    my $uhome=&homeserver($uname,$udomain);
                   4366:    my $items='';
                   4367:    foreach my $key (keys(%$storehash)) {
                   4368:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4369:    }
                   4370:    $items=~s/\&$//;
                   4371:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4372: }
                   4373: 
                   4374: # ---------------------------------------------------------  putstore interface
                   4375: 
1.524     raeburn  4376: sub putstore {
1.715     albertel 4377:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4378:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4379:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4380:    my $uhome=&homeserver($uname,$udomain);
                   4381:    my $items='';
1.715     albertel 4382:    foreach my $key (keys(%$storehash)) {
                   4383:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4384:    }
1.715     albertel 4385:    $items=~s/\&$//;
1.716     albertel 4386:    my $esc_symb=&escape($symb);
                   4387:    my $esc_v=&escape($version);
1.715     albertel 4388:    my $reply =
1.716     albertel 4389:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4390: 	      $uhome);
                   4391:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4392:        # gfall back to way things use to be done
1.715     albertel 4393:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4394: 			    $uname);
1.524     raeburn  4395:    }
1.715     albertel 4396:    return $reply;
                   4397: }
                   4398: 
                   4399: sub old_putstore {
1.716     albertel 4400:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4401:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4402:     if (!$uname) { $uname=$env{'user.name'}; }
                   4403:     my $uhome=&homeserver($uname,$udomain);
                   4404:     my %newstorehash;
1.800     albertel 4405:     foreach my $item (keys(%$storehash)) {
                   4406: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4407: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4408:     }
                   4409:     my $items='';
                   4410:     my %allitems = ();
1.800     albertel 4411:     foreach my $item (keys(%newstorehash)) {
                   4412: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4413: 	    my $key = $1.':keys:'.$2;
                   4414: 	    $allitems{$key} .= $3.':';
                   4415: 	}
1.800     albertel 4416: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4417:     }
1.800     albertel 4418:     foreach my $item (keys(%allitems)) {
                   4419: 	$allitems{$item} =~ s/\:$//;
                   4420: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4421:     }
                   4422:     $items=~s/\&$//;
                   4423:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4424: }
                   4425: 
1.47      www      4426: # ------------------------------------------------------ critical put interface
                   4427: 
                   4428: sub cput {
1.134     albertel 4429:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4430:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4431:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4432:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4433:    my $items='';
1.800     albertel 4434:    foreach my $item (keys(%$storehash)) {
                   4435:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4436:    }
1.47      www      4437:    $items=~s/\&$//;
1.134     albertel 4438:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4439: }
                   4440: 
                   4441: # -------------------------------------------------------------- eget interface
                   4442: 
                   4443: sub eget {
1.133     albertel 4444:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4445:    my $items='';
1.800     albertel 4446:    foreach my $item (@$storearr) {
                   4447:        $items.=&escape($item).'&';
1.191     harris41 4448:    }
1.12      www      4449:    $items=~s/\&$//;
1.620     albertel 4450:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4451:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4452:    my $uhome=&homeserver($uname,$udomain);
                   4453:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4454:    my @pairs=split(/\&/,$rep);
                   4455:    my %returnhash=();
1.42      www      4456:    my $i=0;
1.800     albertel 4457:    foreach my $item (@$storearr) {
                   4458:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4459:       $i++;
1.191     harris41 4460:    }
1.12      www      4461:    return %returnhash;
                   4462: }
                   4463: 
1.667     albertel 4464: # ------------------------------------------------------------ tmpput interface
                   4465: sub tmpput {
1.802     raeburn  4466:     my ($storehash,$server,$context)=@_;
1.667     albertel 4467:     my $items='';
1.800     albertel 4468:     foreach my $item (keys(%$storehash)) {
                   4469: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4470:     }
                   4471:     $items=~s/\&$//;
1.802     raeburn  4472:     if (defined($context)) {
                   4473:         $items .= ':'.&escape($context);
                   4474:     }
1.667     albertel 4475:     return &reply("tmpput:$items",$server);
                   4476: }
                   4477: 
                   4478: # ------------------------------------------------------------ tmpget interface
                   4479: sub tmpget {
1.688     albertel 4480:     my ($token,$server)=@_;
                   4481:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4482:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4483:     my %returnhash;
                   4484:     foreach my $item (split(/\&/,$rep)) {
                   4485: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4486:         next if ($key =~ /^error: 2 /);
1.667     albertel 4487: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4488:     }
                   4489:     return %returnhash;
                   4490: }
                   4491: 
1.688     albertel 4492: # ------------------------------------------------------------ tmpget interface
                   4493: sub tmpdel {
                   4494:     my ($token,$server)=@_;
                   4495:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4496:     return &reply("tmpdel:$token",$server);
                   4497: }
                   4498: 
1.765     albertel 4499: # -------------------------------------------------- portfolio access checking
                   4500: 
                   4501: sub portfolio_access {
1.766     albertel 4502:     my ($requrl) = @_;
1.765     albertel 4503:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4504:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4505:     if ($result) {
                   4506:         my %setters;
                   4507:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4508:             my ($startblock,$endblock) =
                   4509:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4510:             if ($startblock && $endblock) {
                   4511:                 return 'B';
                   4512:             }
                   4513:         } else {
                   4514:             my ($startblock,$endblock) =
                   4515:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4516:             if ($startblock && $endblock) {
                   4517:                 return 'B';
                   4518:             }
                   4519:         }
                   4520:     }
1.765     albertel 4521:     if ($result eq 'ok') {
1.766     albertel 4522:        return 'F';
1.765     albertel 4523:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4524:        return 'A';
1.765     albertel 4525:     }
1.766     albertel 4526:     return '';
1.765     albertel 4527: }
                   4528: 
                   4529: sub get_portfolio_access {
1.767     albertel 4530:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4531: 
                   4532:     if (!ref($access_hash)) {
                   4533: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4534: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4535: 						   $file_name);
                   4536: 	$access_hash = $access_controls{$file_name};
                   4537:     }
                   4538: 
1.765     albertel 4539:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4540:     my $now = time;
                   4541:     if (ref($access_hash) eq 'HASH') {
                   4542:         foreach my $key (keys(%{$access_hash})) {
                   4543:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4544:             if ($start > $now) {
                   4545:                 next;
                   4546:             }
                   4547:             if ($end && $end<$now) {
                   4548:                 next;
                   4549:             }
                   4550:             if ($scope eq 'public') {
                   4551:                 $public = $key;
                   4552:                 last;
                   4553:             } elsif ($scope eq 'guest') {
                   4554:                 $guest = $key;
                   4555:             } elsif ($scope eq 'domains') {
                   4556:                 push(@domains,$key);
                   4557:             } elsif ($scope eq 'users') {
                   4558:                 push(@users,$key);
                   4559:             } elsif ($scope eq 'course') {
                   4560:                 push(@courses,$key);
                   4561:             } elsif ($scope eq 'group') {
                   4562:                 push(@groups,$key);
                   4563:             }
                   4564:         }
                   4565:         if ($public) {
                   4566:             return 'ok';
                   4567:         }
                   4568:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4569:             if ($guest) {
                   4570:                 return $guest;
                   4571:             }
                   4572:         } else {
                   4573:             if (@domains > 0) {
                   4574:                 foreach my $domkey (@domains) {
                   4575:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4576:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4577:                             return 'ok';
                   4578:                         }
                   4579:                     }
                   4580:                 }
                   4581:             }
                   4582:             if (@users > 0) {
                   4583:                 foreach my $userkey (@users) {
1.865     raeburn  4584:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4585:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4586:                             if (ref($item) eq 'HASH') {
                   4587:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4588:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4589:                                     return 'ok';
                   4590:                                 }
                   4591:                             }
                   4592:                         }
                   4593:                     } 
1.765     albertel 4594:                 }
                   4595:             }
                   4596:             my %roleshash;
                   4597:             my @courses_and_groups = @courses;
                   4598:             push(@courses_and_groups,@groups); 
                   4599:             if (@courses_and_groups > 0) {
                   4600:                 my (%allgroups,%allroles); 
                   4601:                 my ($start,$end,$role,$sec,$group);
                   4602:                 foreach my $envkey (%env) {
1.811     albertel 4603:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4604:                         my $cid = $2.'_'.$3; 
                   4605:                         if ($1 eq 'gr') {
                   4606:                             $group = $4;
                   4607:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4608:                         } else {
                   4609:                             if ($4 eq '') {
                   4610:                                 $sec = 'none';
                   4611:                             } else {
                   4612:                                 $sec = $4;
                   4613:                             }
                   4614:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4615:                         }
1.811     albertel 4616:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4617:                         my $cid = $2.'_'.$3;
                   4618:                         if ($4 eq '') {
                   4619:                             $sec = 'none';
                   4620:                         } else {
                   4621:                             $sec = $4;
                   4622:                         }
                   4623:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4624:                     }
                   4625:                 }
                   4626:                 if (keys(%allroles) == 0) {
                   4627:                     return;
                   4628:                 }
                   4629:                 foreach my $key (@courses_and_groups) {
                   4630:                     my %content = %{$$access_hash{$key}};
                   4631:                     my $cnum = $content{'number'};
                   4632:                     my $cdom = $content{'domain'};
                   4633:                     my $cid = $cdom.'_'.$cnum;
                   4634:                     if (!exists($allroles{$cid})) {
                   4635:                         next;
                   4636:                     }    
                   4637:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4638:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4639:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4640:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4641:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4642:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4643:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4644:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4645:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4646:                                         if (grep/^all$/,@sections) {
                   4647:                                             return 'ok';
                   4648:                                         } else {
                   4649:                                             if (grep/^$sec$/,@sections) {
                   4650:                                                 return 'ok';
                   4651:                                             }
                   4652:                                         }
                   4653:                                     }
                   4654:                                 }
                   4655:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4656:                                     if (grep/^none$/,@groups) {
                   4657:                                         return 'ok';
                   4658:                                     }
                   4659:                                 } else {
                   4660:                                     if (grep/^all$/,@groups) {
                   4661:                                         return 'ok';
                   4662:                                     } 
                   4663:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4664:                                         if (grep/^$group$/,@groups) {
                   4665:                                             return 'ok';
                   4666:                                         }
                   4667:                                     }
                   4668:                                 } 
                   4669:                             }
                   4670:                         }
                   4671:                     }
                   4672:                 }
                   4673:             }
                   4674:             if ($guest) {
                   4675:                 return $guest;
                   4676:             }
                   4677:         }
                   4678:     }
                   4679:     return;
                   4680: }
                   4681: 
                   4682: sub course_group_datechecker {
                   4683:     my ($dates,$now,$status) = @_;
                   4684:     my ($start,$end) = split(/\./,$dates);
                   4685:     if (!$start && !$end) {
                   4686:         return 'ok';
                   4687:     }
                   4688:     if (grep/^active$/,@{$status}) {
                   4689:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4690:             return 'ok';
                   4691:         }
                   4692:     }
                   4693:     if (grep/^previous$/,@{$status}) {
                   4694:         if ($end > $now ) {
                   4695:             return 'ok';
                   4696:         }
                   4697:     }
                   4698:     if (grep/^future$/,@{$status}) {
                   4699:         if ($start > $now) {
                   4700:             return 'ok';
                   4701:         }
                   4702:     }
                   4703:     return; 
                   4704: }
                   4705: 
                   4706: sub parse_portfolio_url {
                   4707:     my ($url) = @_;
                   4708: 
                   4709:     my ($type,$udom,$unum,$group,$file_name);
                   4710:     
1.823     albertel 4711:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4712: 	$type = 1;
                   4713:         $udom = $1;
                   4714:         $unum = $2;
                   4715:         $file_name = $3;
1.823     albertel 4716:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4717: 	$type = 2;
                   4718:         $udom = $1;
                   4719:         $unum = $2;
                   4720:         $group = $3;
                   4721:         $file_name = $3.'/'.$4;
                   4722:     }
                   4723:     if (wantarray) {
                   4724: 	return ($type,$udom,$unum,$file_name,$group);
                   4725:     }
                   4726:     return $type;
                   4727: }
                   4728: 
                   4729: sub is_portfolio_url {
                   4730:     my ($url) = @_;
                   4731:     return scalar(&parse_portfolio_url($url));
                   4732: }
                   4733: 
1.798     raeburn  4734: sub is_portfolio_file {
                   4735:     my ($file) = @_;
1.820     raeburn  4736:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4737:         return 1;
                   4738:     }
                   4739:     return;
                   4740: }
                   4741: 
1.976     raeburn  4742: sub usertools_access {
1.985     raeburn  4743:     my ($uname,$udom,$tool,$action,$context) = @_;
                   4744:     my ($access,%tools);
                   4745:     if ($context eq '') {
                   4746:         $context = 'tools';
                   4747:     }
                   4748:     if ($context eq 'requestcourses') {
                   4749:         %tools = (
                   4750:                       official   => 1,
                   4751:                       unofficial => 1,
1.1006    raeburn  4752:                       community  => 1,
1.985     raeburn  4753:                  );
                   4754:     } else {
                   4755:         %tools = (
                   4756:                       aboutme   => 1,
                   4757:                       blog      => 1,
                   4758:                       portfolio => 1,
                   4759:                  );
                   4760:     }
1.976     raeburn  4761:     return if (!defined($tools{$tool}));
                   4762: 
                   4763:     if ((!defined($udom)) || (!defined($uname))) {
                   4764:         $udom = $env{'user.domain'};
                   4765:         $uname = $env{'user.name'};
                   4766:     }
                   4767: 
1.978     raeburn  4768:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4769:         if ($action ne 'reload') {
1.985     raeburn  4770:             if ($context eq 'requestcourses') {
                   4771:                 return $env{'environment.canrequest.'.$tool};
                   4772:             } else {
                   4773:                 return $env{'environment.availabletools.'.$tool};
                   4774:             }
                   4775:         }
1.976     raeburn  4776:     }
                   4777: 
                   4778:     my ($toolstatus,$inststatus);
                   4779: 
1.985     raeburn  4780:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   4781:          ($action ne 'reload')) {
                   4782:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  4783:         $inststatus = $env{'environment.inststatus'};
                   4784:     } else {
1.1025    raeburn  4785:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985     raeburn  4786:         $toolstatus = $userenv{$context.'.'.$tool};
1.976     raeburn  4787:         $inststatus = $userenv{'inststatus'};
                   4788:     }
                   4789: 
                   4790:     if ($toolstatus ne '') {
                   4791:         if ($toolstatus) {
                   4792:             $access = 1;
                   4793:         } else {
                   4794:             $access = 0;
                   4795:         }
                   4796:         return $access;
                   4797:     }
                   4798: 
                   4799:     my $is_adv = &is_advanced_user($udom,$uname);
                   4800:     my %domdef = &get_domain_defaults($udom);
                   4801:     if (ref($domdef{$tool}) eq 'HASH') {
                   4802:         if ($is_adv) {
                   4803:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4804:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4805:                     $access = 1;
                   4806:                 } else {
                   4807:                     $access = 0;
                   4808:                 }
                   4809:                 return $access;
                   4810:             }
                   4811:         }
                   4812:         if ($inststatus ne '') {
                   4813:             my ($hasaccess,$hasnoaccess);
                   4814:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4815:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4816:                     if ($domdef{$tool}{$affiliation}) {
                   4817:                         $hasaccess = 1;
                   4818:                     } else {
                   4819:                         $hasnoaccess = 1;
                   4820:                     }
                   4821:                 }
                   4822:             }
                   4823:             if ($hasaccess || $hasnoaccess) {
                   4824:                 if ($hasaccess) {
                   4825:                     $access = 1;
                   4826:                 } elsif ($hasnoaccess) {
                   4827:                     $access = 0; 
                   4828:                 }
                   4829:                 return $access;
                   4830:             }
                   4831:         } else {
                   4832:             if ($domdef{$tool}{'default'} ne '') {
                   4833:                 if ($domdef{$tool}{'default'}) {
                   4834:                     $access = 1;
                   4835:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4836:                     $access = 0;
                   4837:                 }
                   4838:                 return $access;
                   4839:             }
                   4840:         }
                   4841:     } else {
1.985     raeburn  4842:         if ($context eq 'tools') {
                   4843:             $access = 1;
                   4844:         } else {
                   4845:             $access = 0;
                   4846:         }
1.976     raeburn  4847:         return $access;
                   4848:     }
                   4849: }
                   4850: 
1.1048.2.3  raeburn  4851: sub is_course_owner {
                   4852:     my ($cdom,$cnum,$udom,$uname) = @_;
                   4853:     if (($udom eq '') || ($uname eq '')) {
                   4854:         $udom = $env{'user.domain'};
                   4855:         $uname = $env{'user.name'};
                   4856:     }
                   4857:     unless (($udom eq '') || ($uname eq '')) {
                   4858:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   4859:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   4860:                 return 1;
                   4861:             } else {
                   4862:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   4863:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   4864:                     return 1;
                   4865:                 }
                   4866:             }
                   4867:         }
                   4868:     }
                   4869:     return;
                   4870: }
                   4871: 
1.976     raeburn  4872: sub is_advanced_user {
                   4873:     my ($udom,$uname) = @_;
                   4874:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4875:     my %allroles;
                   4876:     my $is_adv;
                   4877:     foreach my $role (keys(%roleshash)) {
                   4878:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4879:         my $area = '/'.$tdomain.'/'.$trest;
                   4880:         if ($sec ne '') {
                   4881:             $area .= '/'.$sec;
                   4882:         }
                   4883:         if (($area ne '') && ($trole ne '')) {
                   4884:             my $spec=$trole.'.'.$area;
                   4885:             if ($trole =~ /^cr\//) {
                   4886:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4887:             } elsif ($trole ne 'gr') {
                   4888:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4889:             }
                   4890:         }
                   4891:     }
                   4892:     foreach my $role (keys(%allroles)) {
                   4893:         last if ($is_adv);
                   4894:         foreach my $item (split(/:/,$allroles{$role})) {
                   4895:             if ($item ne '') {
                   4896:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4897:                 if ($privilege eq 'adv') {
                   4898:                     $is_adv = 1;
                   4899:                     last;
                   4900:                 }
                   4901:             }
                   4902:         }
                   4903:     }
                   4904:     return $is_adv;
                   4905: }
1.798     raeburn  4906: 
1.1035    raeburn  4907: sub check_can_request {
1.1036    raeburn  4908:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  4909:     my $canreq = 0;
                   4910:     my ($types,$typename) = &Apache::loncommon::course_types();
                   4911:     my @options = ('approval','validate','autolimit');
                   4912:     my $optregex = join('|',@options);
                   4913:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   4914:         foreach my $type (@{$types}) {
                   4915:             if (&usertools_access($env{'user.name'},
                   4916:                                   $env{'user.domain'},
                   4917:                                   $type,undef,'requestcourses')) {
                   4918:                 $canreq ++;
1.1036    raeburn  4919:                 if (ref($request_domains) eq 'HASH') {
                   4920:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   4921:                 }
1.1035    raeburn  4922:                 if ($dom eq $env{'user.domain'}) {
                   4923:                     $can_request->{$type} = 1;
                   4924:                 }
                   4925:             }
                   4926:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   4927:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   4928:                 if (@curr > 0) {
1.1036    raeburn  4929:                     foreach my $item (@curr) {
                   4930:                         if (ref($request_domains) eq 'HASH') {
                   4931:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   4932:                             if ($otherdom ne '') {
                   4933:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   4934:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   4935:                                         push(@{$request_domains->{$type}},$otherdom);
                   4936:                                     }
                   4937:                                 } else {
                   4938:                                     push(@{$request_domains->{$type}},$otherdom);
                   4939:                                 }
                   4940:                             }
                   4941:                         }
                   4942:                     }
                   4943:                     unless($dom eq $env{'user.domain'}) {
                   4944:                         $canreq ++;
1.1035    raeburn  4945:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   4946:                             $can_request->{$type} = 1;
                   4947:                         }
                   4948:                     }
                   4949:                 }
                   4950:             }
                   4951:         }
                   4952:     }
                   4953:     return $canreq;
                   4954: }
                   4955: 
1.341     www      4956: # ---------------------------------------------- Custom access rule evaluation
                   4957: 
                   4958: sub customaccess {
                   4959:     my ($priv,$uri)=@_;
1.807     albertel 4960:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4961:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4962:     $udom = &LONCAPA::clean_domain($udom);
                   4963:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4964:     my $access=0;
1.800     albertel 4965:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4966: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4967: 	if ($type eq 'user') {
                   4968: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4969: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4970: 		if ($tdom) {
                   4971: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4972: 		}
1.896     albertel 4973: 		if ($tuname) {
                   4974: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4975: 		}
                   4976: 		$access=($effect eq 'allow');
                   4977: 		last;
                   4978: 	    }
                   4979: 	} else {
                   4980: 	    if ($role) {
                   4981: 		if ($role ne $urole) { next; }
                   4982: 	    }
                   4983: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4984: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4985: 		if ($tdom) {
                   4986: 		    if ($tdom ne $udom) { next; }
                   4987: 		}
                   4988: 		if ($tcrs) {
                   4989: 		    if ($tcrs ne $ucrs) { next; }
                   4990: 		}
                   4991: 		if ($tsec) {
                   4992: 		    if ($tsec ne $usec) { next; }
                   4993: 		}
                   4994: 		$access=($effect eq 'allow');
                   4995: 		last;
                   4996: 	    }
                   4997: 	    if ($realm eq '' && $role eq '') {
                   4998: 		$access=($effect eq 'allow');
                   4999: 	    }
1.402     bowersj2 5000: 	}
1.341     www      5001:     }
                   5002:     return $access;
                   5003: }
                   5004: 
1.103     harris41 5005: # ------------------------------------------------- Check for a user privilege
1.12      www      5006: 
                   5007: sub allowed {
1.810     raeburn  5008:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5009:     my $ver_orguri=$uri;
1.439     www      5010:     $uri=&deversion($uri);
1.152     www      5011:     my $orguri=$uri;
1.52      www      5012:     $uri=&declutter($uri);
1.809     raeburn  5013: 
1.810     raeburn  5014:     if ($priv eq 'evb') {
                   5015: # Evade communication block restrictions for specified role in a course
                   5016:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5017:             return $1;
                   5018:         } else {
                   5019:             return;
                   5020:         }
                   5021:     }
                   5022: 
1.620     albertel 5023:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5024: # Free bre access to adm and meta resources
1.775     albertel 5025:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5026: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5027: 	&& ($priv eq 'bre')) {
1.14      www      5028: 	return 'F';
1.159     www      5029:     }
                   5030: 
1.545     banghart 5031: # Free bre access to user's own portfolio contents
1.714     raeburn  5032:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5033:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5034: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5035:         my %setters;
                   5036:         my ($startblock,$endblock) = 
                   5037:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5038:         if ($startblock && $endblock) {
                   5039:             return 'B';
                   5040:         } else {
                   5041:             return 'F';
                   5042:         }
1.545     banghart 5043:     }
                   5044: 
1.762     raeburn  5045: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5046:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5047:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5048:         if (exists($env{'request.course.id'})) {
                   5049:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5050:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5051:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5052:                 my $courseprivid=$env{'request.course.id'};
                   5053:                 $courseprivid=~s/\_/\//;
                   5054:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5055:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5056:                     return $1; 
1.762     raeburn  5057:                 } else {
                   5058:                     if ($env{'request.course.sec'}) {
                   5059:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5060:                     }
                   5061:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5062:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5063:                         return $2;
                   5064:                     }
1.714     raeburn  5065:                 }
                   5066:             }
                   5067:         }
                   5068:     }
                   5069: 
1.159     www      5070: # Free bre to public access
                   5071: 
                   5072:     if ($priv eq 'bre') {
1.238     www      5073:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5074: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5075:            return 'F'; 
                   5076:         }
1.238     www      5077:         if ($copyright eq 'priv') {
                   5078:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5079: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5080: 		return '';
                   5081:             }
                   5082:         }
                   5083:         if ($copyright eq 'domain') {
                   5084:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5085: 	    unless (($env{'user.domain'} eq $1) ||
                   5086:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5087: 		return '';
                   5088:             }
1.262     matthew  5089:         }
1.620     albertel 5090:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5091:             # Library role, so allow browsing of resources in this domain.
                   5092:             return 'F';
1.238     www      5093:         }
1.341     www      5094:         if ($copyright eq 'custom') {
                   5095: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5096:         }
1.14      www      5097:     }
1.264     matthew  5098:     # Domain coordinator is trying to create a course
1.620     albertel 5099:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5100:         # uri is the requested domain in this case.
                   5101:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5102:         # a role of dc for the domain in question.
1.620     albertel 5103:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5104:     }
1.29      www      5105: 
1.52      www      5106:     my $thisallowed='';
                   5107:     my $statecond=0;
                   5108:     my $courseprivid='';
                   5109: 
1.1039    raeburn  5110:     my $ownaccess;
1.1043    raeburn  5111:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5112:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5113:         if ($uri eq '') {
                   5114:             $ownaccess = 1;
                   5115:         } else {
                   5116:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5117:                 my $udom = $env{'user.domain'};
                   5118:                 my $uname = $env{'user.name'};
                   5119:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5120:                     $ownaccess = 1;
1.1040    raeburn  5121:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5122:                     unless ($uri =~ m{\.\./}) {
                   5123:                         $ownaccess = 1;
                   5124:                     }
                   5125:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5126:                     my $now = time;
                   5127:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5128:                         my $adom = $1;
                   5129:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5130:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5131:                                 my ($start,$end) = split('.',$env{$key});
                   5132:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5133:                                     $ownaccess = 1;
                   5134:                                     last;
                   5135:                                 }
                   5136:                             }
                   5137:                         }
                   5138:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5139:                         my $adom = $1;
                   5140:                         my $aname = $2;
1.1042    raeburn  5141:                         foreach my $role ('ca','aa') { 
                   5142:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5143:                                 my ($start,$end) =
                   5144:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5145:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5146:                                     $ownaccess = 1;
                   5147:                                     last;
                   5148:                                 }
1.1039    raeburn  5149:                             }
                   5150:                         }
                   5151:                     }
                   5152:                 }
                   5153:             }
                   5154:         }
                   5155:     }
                   5156: 
1.52      www      5157: # Course
                   5158: 
1.620     albertel 5159:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5160:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5161:             $thisallowed.=$1;
                   5162:         }
1.52      www      5163:     }
1.29      www      5164: 
1.52      www      5165: # Domain
                   5166: 
1.620     albertel 5167:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5168:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5169:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5170:             $thisallowed.=$1;
                   5171:         }
1.12      www      5172:     }
1.52      www      5173: 
                   5174: # Course: uri itself is a course
1.66      www      5175:     my $courseuri=$uri;
                   5176:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5177:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5178: 
1.620     albertel 5179:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5180:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5181:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5182:             $thisallowed.=$1;
                   5183:         }
1.12      www      5184:     }
1.29      www      5185: 
1.665     albertel 5186: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5187: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5188:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5189: 	$thisallowed='';
1.671     raeburn  5190:         my ($match)=&is_on_map($uri);
                   5191:         if ($match) {
                   5192:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5193:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5194:                 $thisallowed.=$1;
                   5195:             }
                   5196:         } else {
1.705     albertel 5197:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5198:             if ($refuri) {
                   5199:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5200:                     $thisallowed='F';
1.671     raeburn  5201:                 } else {
                   5202:                     $refuri=&declutter($refuri);
                   5203:                     my ($match) = &is_on_map($refuri);
                   5204:                     if ($match) {
                   5205:                         $thisallowed='F';
                   5206:                     }
1.669     raeburn  5207:                 }
1.671     raeburn  5208:             }
                   5209:         }
1.314     www      5210:     }
1.492     albertel 5211: 
1.766     albertel 5212:     if ($priv eq 'bre'
                   5213: 	&& $thisallowed ne 'F' 
                   5214: 	&& $thisallowed ne '2'
                   5215: 	&& &is_portfolio_url($uri)) {
                   5216: 	$thisallowed = &portfolio_access($uri);
                   5217:     }
                   5218:     
1.52      www      5219: # Full access at system, domain or course-wide level? Exit.
1.29      www      5220:     if ($thisallowed=~/F/) {
                   5221: 	return 'F';
                   5222:     }
                   5223: 
1.52      www      5224: # If this is generating or modifying users, exit with special codes
1.29      www      5225: 
1.643     www      5226:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5227: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5228: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5229: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5230: 	    unless ($auname) { return $thisallowed; }
                   5231: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5232: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5233: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5234: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5235: 	}
1.52      www      5236: 	return $thisallowed;
                   5237:     }
                   5238: #
1.103     harris41 5239: # Gathered so far: system, domain and course wide privileges
1.52      www      5240: #
                   5241: # Course: See if uri or referer is an individual resource that is part of 
                   5242: # the course
                   5243: 
1.620     albertel 5244:     if ($env{'request.course.id'}) {
1.232     www      5245: 
1.620     albertel 5246:        $courseprivid=$env{'request.course.id'};
                   5247:        if ($env{'request.course.sec'}) {
                   5248:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5249:        }
                   5250:        $courseprivid=~s/\_/\//;
                   5251:        my $checkreferer=1;
1.232     www      5252:        my ($match,$cond)=&is_on_map($uri);
                   5253:        if ($match) {
                   5254:            $statecond=$cond;
1.620     albertel 5255:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5256:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5257:                $thisallowed.=$1;
                   5258:                $checkreferer=0;
                   5259:            }
1.29      www      5260:        }
1.83      www      5261:        
1.148     www      5262:        if ($checkreferer) {
1.620     albertel 5263: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      5264:             unless ($refuri) {
1.800     albertel 5265:                 foreach my $key (keys(%env)) {
                   5266: 		    if ($key=~/^httpref\..*\*/) {
                   5267: 			my $pattern=$key;
1.156     www      5268:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      5269:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   5270:                         $pattern=~s/\//\\\//g;
1.152     www      5271:                         if ($orguri=~/$pattern/) {
1.800     albertel 5272: 			    $refuri=$env{$key};
1.148     www      5273:                         }
                   5274:                     }
1.191     harris41 5275:                 }
1.148     www      5276:             }
1.232     www      5277: 
1.148     www      5278:          if ($refuri) { 
1.152     www      5279: 	  $refuri=&declutter($refuri);
1.232     www      5280:           my ($match,$cond)=&is_on_map($refuri);
                   5281:             if ($match) {
                   5282:               my $refstatecond=$cond;
1.620     albertel 5283:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5284:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5285:                   $thisallowed.=$1;
1.53      www      5286:                   $uri=$refuri;
                   5287:                   $statecond=$refstatecond;
1.52      www      5288:               }
                   5289:           }
1.148     www      5290:         }
1.29      www      5291:        }
1.52      www      5292:    }
1.29      www      5293: 
1.52      www      5294: #
1.103     harris41 5295: # Gathered now: all privileges that could apply, and condition number
1.52      www      5296: # 
                   5297: #
                   5298: # Full or no access?
                   5299: #
1.29      www      5300: 
1.52      www      5301:     if ($thisallowed=~/F/) {
                   5302: 	return 'F';
                   5303:     }
1.29      www      5304: 
1.52      www      5305:     unless ($thisallowed) {
                   5306:         return '';
                   5307:     }
1.29      www      5308: 
1.52      www      5309: # Restrictions exist, deal with them
                   5310: #
                   5311: #   C:according to course preferences
                   5312: #   R:according to resource settings
                   5313: #   L:unless locked
                   5314: #   X:according to user session state
                   5315: #
                   5316: 
                   5317: # Possibly locked functionality, check all courses
1.54      www      5318: # Locks might take effect only after 10 minutes cache expiration for other
                   5319: # courses, and 2 minutes for current course
1.52      www      5320: 
                   5321:     my $envkey;
                   5322:     if ($thisallowed=~/L/) {
1.1000    raeburn  5323:         foreach $envkey (keys(%env)) {
1.54      www      5324:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   5325:                my $courseid=$2;
                   5326:                my $roleid=$1.'.'.$2;
1.92      www      5327:                $courseid=~s/^\///;
1.54      www      5328:                my $expiretime=600;
1.620     albertel 5329:                if ($env{'request.role'} eq $roleid) {
1.54      www      5330: 		  $expiretime=120;
                   5331:                }
                   5332: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   5333:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 5334:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 5335: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      5336:                }
1.620     albertel 5337:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5338:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   5339: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   5340:                        &log($env{'user.domain'},$env{'user.name'},
                   5341:                             $env{'user.home'},
1.57      www      5342:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      5343:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5344:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5345: 		       return '';
                   5346:                    }
                   5347:                }
1.620     albertel 5348:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   5349:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   5350: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   5351:                        &log($env{'user.domain'},$env{'user.name'},
                   5352:                             $env{'user.home'},
1.57      www      5353:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      5354:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 5355:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      5356: 		       return '';
                   5357:                    }
                   5358:                }
                   5359: 	   }
1.29      www      5360:        }
1.52      www      5361:     }
                   5362:    
                   5363: #
                   5364: # Rest of the restrictions depend on selected course
                   5365: #
                   5366: 
1.620     albertel 5367:     unless ($env{'request.course.id'}) {
1.766     albertel 5368: 	if ($thisallowed eq 'A') {
                   5369: 	    return 'A';
1.814     raeburn  5370:         } elsif ($thisallowed eq 'B') {
                   5371:             return 'B';
1.766     albertel 5372: 	} else {
                   5373: 	    return '1';
                   5374: 	}
1.52      www      5375:     }
1.29      www      5376: 
1.52      www      5377: #
                   5378: # Now user is definitely in a course
                   5379: #
1.53      www      5380: 
                   5381: 
                   5382: # Course preferences
                   5383: 
                   5384:    if ($thisallowed=~/C/) {
1.620     albertel 5385:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   5386:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   5387:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 5388: 	   =~/\Q$rolecode\E/) {
1.689     albertel 5389: 	   if ($priv ne 'pch') { 
                   5390: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5391: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   5392: 			$env{'request.course.id'});
                   5393: 	   }
1.237     www      5394:            return '';
                   5395:        }
                   5396: 
1.620     albertel 5397:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 5398: 	   =~/\Q$unamedom\E/) {
1.689     albertel 5399: 	   if ($priv ne 'pch') { 
                   5400: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   5401: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   5402: 			$env{'request.course.id'});
                   5403: 	   }
1.54      www      5404:            return '';
                   5405:        }
1.53      www      5406:    }
                   5407: 
                   5408: # Resource preferences
                   5409: 
                   5410:    if ($thisallowed=~/R/) {
1.620     albertel 5411:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 5412:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 5413: 	   if ($priv ne 'pch') { 
                   5414: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   5415: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   5416: 	   }
                   5417: 	   return '';
1.54      www      5418:        }
1.53      www      5419:    }
1.30      www      5420: 
1.246     www      5421: # Restricted by state or randomout?
1.30      www      5422: 
1.52      www      5423:    if ($thisallowed=~/X/) {
1.620     albertel 5424:       if ($env{'acc.randomout'}) {
1.579     albertel 5425: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 5426:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      5427:             return ''; 
                   5428:          }
1.247     www      5429:       }
                   5430:       if (&condval($statecond)) {
1.52      www      5431: 	 return '2';
                   5432:       } else {
                   5433:          return '';
                   5434:       }
                   5435:    }
1.30      www      5436: 
1.766     albertel 5437:     if ($thisallowed eq 'A') {
                   5438: 	return 'A';
1.814     raeburn  5439:     } elsif ($thisallowed eq 'B') {
                   5440:         return 'B';
1.766     albertel 5441:     }
1.52      www      5442:    return 'F';
1.232     www      5443: }
                   5444: 
1.710     albertel 5445: sub split_uri_for_cond {
                   5446:     my $uri=&deversion(&declutter(shift));
                   5447:     my @uriparts=split(/\//,$uri);
                   5448:     my $filename=pop(@uriparts);
                   5449:     my $pathname=join('/',@uriparts);
                   5450:     return ($pathname,$filename);
                   5451: }
1.232     www      5452: # --------------------------------------------------- Is a resource on the map?
                   5453: 
                   5454: sub is_on_map {
1.710     albertel 5455:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5456:     #Trying to find the conditional for the file
1.620     albertel 5457:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5458: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5459:     if ($match) {
1.289     bowersj2 5460: 	return (1,$1);
                   5461:     } else {
1.434     www      5462: 	return (0,0);
1.289     bowersj2 5463:     }
1.12      www      5464: }
                   5465: 
1.427     www      5466: # --------------------------------------------------------- Get symb from alias
                   5467: 
                   5468: sub get_symb_from_alias {
                   5469:     my $symb=shift;
                   5470:     my ($map,$resid,$url)=&decode_symb($symb);
                   5471: # Already is a symb
                   5472:     if ($url) { return $symb; }
                   5473: # Must be an alias
                   5474:     my $aliassymb='';
                   5475:     my %bighash;
1.620     albertel 5476:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5477:                             &GDBM_READER(),0640)) {
                   5478:         my $rid=$bighash{'mapalias_'.$symb};
                   5479: 	if ($rid) {
                   5480: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5481: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5482: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5483: 	}
                   5484:         untie %bighash;
                   5485:     }
                   5486:     return $aliassymb;
                   5487: }
                   5488: 
1.12      www      5489: # ----------------------------------------------------------------- Define Role
                   5490: 
                   5491: sub definerole {
                   5492:   if (allowed('mcr','/')) {
                   5493:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5494:     foreach my $role (split(':',$sysrole)) {
                   5495: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5496:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5497:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5498: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5499:                return "refused:s:$crole&$cqual"; 
                   5500:             }
                   5501:         }
1.191     harris41 5502:     }
1.800     albertel 5503:     foreach my $role (split(':',$domrole)) {
                   5504: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5505:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5506:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5507: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5508:                return "refused:d:$crole&$cqual"; 
                   5509:             }
                   5510:         }
1.191     harris41 5511:     }
1.800     albertel 5512:     foreach my $role (split(':',$courole)) {
                   5513: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5514:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5515:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5516: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5517:                return "refused:c:$crole&$cqual"; 
                   5518:             }
                   5519:         }
1.191     harris41 5520:     }
1.620     albertel 5521:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5522:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5523: 	        "rolesdef_$rolename=".
                   5524:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5525:     return reply($command,$env{'user.home'});
1.12      www      5526:   } else {
                   5527:     return 'refused';
                   5528:   }
1.105     harris41 5529: }
                   5530: 
                   5531: # ---------------- Make a metadata query against the network of library servers
                   5532: 
                   5533: sub metadata_query {
1.244     matthew  5534:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5535:     my %rhash;
1.845     albertel 5536:     my %libserv = &all_library();
1.244     matthew  5537:     my @server_list = (defined($server_array) ? @$server_array
                   5538:                                               : keys(%libserv) );
                   5539:     for my $server (@server_list) {
1.118     harris41 5540: 	unless ($custom or $customshow) {
                   5541: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5542: 	    $rhash{$server}=$reply;
                   5543: 	}
                   5544: 	else {
                   5545: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5546: 			     &escape($custom).':'.&escape($customshow),
                   5547: 			     $server);
                   5548: 	    $rhash{$server}=$reply;
                   5549: 	}
1.112     harris41 5550:     }
1.118     harris41 5551:     return \%rhash;
1.240     www      5552: }
                   5553: 
                   5554: # ----------------------------------------- Send log queries and wait for reply
                   5555: 
                   5556: sub log_query {
                   5557:     my ($uname,$udom,$query,%filters)=@_;
                   5558:     my $uhome=&homeserver($uname,$udom);
                   5559:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5560:     my $uhost=&hostname($uhome);
1.800     albertel 5561:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5562:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5563:                        $uhome);
1.479     albertel 5564:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5565:     return get_query_reply($queryid);
                   5566: }
                   5567: 
1.818     raeburn  5568: # -------------------------- Update MySQL table for portfolio file
                   5569: 
                   5570: sub update_portfolio_table {
1.821     raeburn  5571:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5572:     if ($group ne '') {
                   5573:         $file_name =~s /^\Q$group\E//;
                   5574:     }
1.818     raeburn  5575:     my $homeserver = &homeserver($uname,$udom);
                   5576:     my $queryid=
1.821     raeburn  5577:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5578:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5579:     my $reply = &get_query_reply($queryid);
                   5580:     return $reply;
                   5581: }
                   5582: 
1.899     raeburn  5583: # -------------------------- Update MySQL allusers table
                   5584: 
                   5585: sub update_allusers_table {
                   5586:     my ($uname,$udom,$names) = @_;
                   5587:     my $homeserver = &homeserver($uname,$udom);
                   5588:     my $queryid=
                   5589:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5590:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5591:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5592:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5593:                'generation='.&escape($names->{'generation'}).'%%'.
                   5594:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5595:                'id='.&escape($names->{'id'}),$homeserver);
                   5596:     my $reply = &get_query_reply($queryid);
                   5597:     return $reply;
                   5598: }
                   5599: 
1.508     raeburn  5600: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5601: 
                   5602: sub fetch_enrollment_query {
1.511     raeburn  5603:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5604:     my $homeserver;
1.547     raeburn  5605:     my $maxtries = 1;
1.508     raeburn  5606:     if ($context eq 'automated') {
                   5607:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5608:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5609:     } else {
                   5610:         $homeserver = &homeserver($cnum,$dom);
                   5611:     }
1.838     albertel 5612:     my $host=&hostname($homeserver);
1.506     raeburn  5613:     my $cmd = '';
1.1000    raeburn  5614:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 5615:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5616:     }
                   5617:     $cmd =~ s/%%$//;
                   5618:     $cmd = &escape($cmd);
                   5619:     my $query = 'fetchenrollment';
1.620     albertel 5620:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5621:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5622:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5623:         return 'error: '.$queryid;
                   5624:     }
1.506     raeburn  5625:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5626:     my $tries = 1;
                   5627:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5628:         $reply = &get_query_reply($queryid);
                   5629:         $tries ++;
                   5630:     }
1.526     raeburn  5631:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5632:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5633:     } else {
1.901     albertel 5634:         my @responses = split(/:/,$reply);
1.515     raeburn  5635:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5636:             foreach my $line (@responses) {
                   5637:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5638:                 $$replyref{$key} = $value;
                   5639:             }
                   5640:         } else {
1.506     raeburn  5641:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5642:             foreach my $line (@responses) {
                   5643:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5644:                 $$replyref{$key} = $value;
                   5645:                 if ($value > 0) {
1.800     albertel 5646:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5647:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5648:                         my $destname = $pathname.'/'.$filename;
                   5649:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5650:                         if ($xml_classlist =~ /^error/) {
                   5651:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5652:                         } else {
1.506     raeburn  5653:                             if ( open(FILE,">$destname") ) {
                   5654:                                 print FILE &unescape($xml_classlist);
                   5655:                                 close(FILE);
1.526     raeburn  5656:                             } else {
                   5657:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5658:                             }
                   5659:                         }
                   5660:                     }
                   5661:                 }
                   5662:             }
                   5663:         }
                   5664:         return 'ok';
                   5665:     }
                   5666:     return 'error';
                   5667: }
                   5668: 
1.242     www      5669: sub get_query_reply {
                   5670:     my $queryid=shift;
1.240     www      5671:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5672:     my $reply='';
                   5673:     for (1..100) {
                   5674: 	sleep 2;
                   5675:         if (-e $replyfile.'.end') {
1.448     albertel 5676: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5677: 		$reply = join('',<$fh>);
                   5678: 		close($fh);
1.240     www      5679: 	   } else { return 'error: reply_file_error'; }
1.242     www      5680:            return &unescape($reply);
                   5681: 	}
1.240     www      5682:     }
1.242     www      5683:     return 'timeout:'.$queryid;
1.240     www      5684: }
                   5685: 
                   5686: sub courselog_query {
1.241     www      5687: #
                   5688: # possible filters:
                   5689: # url: url or symb
                   5690: # username
                   5691: # domain
                   5692: # action: view, submit, grade
                   5693: # start: timestamp
                   5694: # end: timestamp
                   5695: #
1.240     www      5696:     my (%filters)=@_;
1.620     albertel 5697:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5698:     if ($filters{'url'}) {
                   5699: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5700:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5701:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5702:     }
1.620     albertel 5703:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5704:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5705:     return &log_query($cname,$cdom,'courselog',%filters);
                   5706: }
                   5707: 
                   5708: sub userlog_query {
1.858     raeburn  5709: #
                   5710: # possible filters:
                   5711: # action: log check role
                   5712: # start: timestamp
                   5713: # end: timestamp
                   5714: #
1.240     www      5715:     my ($uname,$udom,%filters)=@_;
                   5716:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5717: }
                   5718: 
1.506     raeburn  5719: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5720: 
                   5721: sub auto_run {
1.508     raeburn  5722:     my ($cnum,$cdom) = @_;
1.876     raeburn  5723:     my $response = 0;
                   5724:     my $settings;
                   5725:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5726:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5727:         $settings = $domconfig{'autoenroll'};
                   5728:         if ($settings->{'run'} eq '1') {
                   5729:             $response = 1;
                   5730:         }
                   5731:     } else {
1.934     raeburn  5732:         my $homeserver;
                   5733:         if (&is_course($cdom,$cnum)) {
                   5734:             $homeserver = &homeserver($cnum,$cdom);
                   5735:         } else {
                   5736:             $homeserver = &domain($cdom,'primary');
                   5737:         }
                   5738:         if ($homeserver ne 'no_host') {
                   5739:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5740:         }
1.876     raeburn  5741:     }
1.506     raeburn  5742:     return $response;
                   5743: }
1.776     albertel 5744: 
1.506     raeburn  5745: sub auto_get_sections {
1.508     raeburn  5746:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  5747:     my $homeserver;
                   5748:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   5749:         $homeserver = &homeserver($cnum,$cdom);
                   5750:     }
                   5751:     if (!defined($homeserver)) { 
                   5752:         if ($cdom =~ /^$match_domain$/) {
                   5753:             $homeserver = &domain($cdom,'primary');
                   5754:         }
                   5755:     }
                   5756:     my @secs;
                   5757:     if (defined($homeserver)) {
                   5758:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   5759:         unless ($response eq 'refused') {
                   5760:             @secs = split(/:/,$response);
                   5761:         }
1.506     raeburn  5762:     }
                   5763:     return @secs;
                   5764: }
1.776     albertel 5765: 
1.506     raeburn  5766: sub auto_new_course {
1.508     raeburn  5767:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5768:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5769:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5770:     return $response;
                   5771: }
1.776     albertel 5772: 
1.506     raeburn  5773: sub auto_validate_courseID {
1.508     raeburn  5774:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5775:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5776:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5777:     return $response;
                   5778: }
1.776     albertel 5779: 
1.1007    raeburn  5780: sub auto_validate_instcode {
1.1020    raeburn  5781:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  5782:     my ($homeserver,$response);
                   5783:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5784:         $homeserver = &homeserver($cnum,$cdom);
                   5785:     }
                   5786:     if (!defined($homeserver)) {
                   5787:         if ($cdom =~ /^$match_domain$/) {
                   5788:             $homeserver = &domain($cdom,'primary');
                   5789:         }
                   5790:     }
                   5791:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
1.1020    raeburn  5792:                            &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  5793:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   5794:     return ($outcome,$description);
1.1007    raeburn  5795: }
                   5796: 
1.506     raeburn  5797: sub auto_create_password {
1.873     raeburn  5798:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5799:     my ($homeserver,$response);
1.506     raeburn  5800:     my $create_passwd = 0;
                   5801:     my $authchk = '';
1.873     raeburn  5802:     if ($udom =~ /^$match_domain$/) {
                   5803:         $homeserver = &domain($udom,'primary');
                   5804:     }
                   5805:     if ($homeserver eq '') {
                   5806:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5807:             $homeserver = &homeserver($cnum,$cdom);
                   5808:         }
                   5809:     }
                   5810:     if ($homeserver eq '') {
                   5811:         $authchk = 'nodomain';
1.506     raeburn  5812:     } else {
1.873     raeburn  5813:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5814:         if ($response eq 'refused') {
                   5815:             $authchk = 'refused';
                   5816:         } else {
1.901     albertel 5817:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5818:         }
1.506     raeburn  5819:     }
                   5820:     return ($authparam,$create_passwd,$authchk);
                   5821: }
                   5822: 
1.706     raeburn  5823: sub auto_photo_permission {
                   5824:     my ($cnum,$cdom,$students) = @_;
                   5825:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5826:     my ($outcome,$perm_reqd,$conditions) = 
                   5827: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5828:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5829: 	return (undef,undef);
                   5830:     }
1.706     raeburn  5831:     return ($outcome,$perm_reqd,$conditions);
                   5832: }
                   5833: 
                   5834: sub auto_checkphotos {
                   5835:     my ($uname,$udom,$pid) = @_;
                   5836:     my $homeserver = &homeserver($uname,$udom);
                   5837:     my ($result,$resulttype);
                   5838:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5839: 				   &escape($uname).':'.&escape($pid),
                   5840: 				   $homeserver));
1.709     albertel 5841:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5842: 	return (undef,undef);
                   5843:     }
1.706     raeburn  5844:     if ($outcome) {
                   5845:         ($result,$resulttype) = split(/:/,$outcome);
                   5846:     } 
                   5847:     return ($result,$resulttype);
                   5848: }
                   5849: 
                   5850: sub auto_photochoice {
                   5851:     my ($cnum,$cdom) = @_;
                   5852:     my $homeserver = &homeserver($cnum,$cdom);
                   5853:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5854: 						       &escape($cdom),
                   5855: 						       $homeserver)));
1.709     albertel 5856:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5857: 	return (undef,undef);
                   5858:     }
1.706     raeburn  5859:     return ($update,$comment);
                   5860: }
                   5861: 
                   5862: sub auto_photoupdate {
                   5863:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5864:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5865:     my $host=&hostname($homeserver);
1.706     raeburn  5866:     my $cmd = '';
                   5867:     my $maxtries = 1;
1.800     albertel 5868:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5869:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5870:     }
                   5871:     $cmd =~ s/%%$//;
                   5872:     $cmd = &escape($cmd);
                   5873:     my $query = 'institutionalphotos';
                   5874:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5875:     unless ($queryid=~/^\Q$host\E\_/) {
                   5876:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5877:         return 'error: '.$queryid;
                   5878:     }
                   5879:     my $reply = &get_query_reply($queryid);
                   5880:     my $tries = 1;
                   5881:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5882:         $reply = &get_query_reply($queryid);
                   5883:         $tries ++;
                   5884:     }
                   5885:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5886:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5887:     } else {
                   5888:         my @responses = split(/:/,$reply);
                   5889:         my $outcome = shift(@responses); 
                   5890:         foreach my $item (@responses) {
                   5891:             my ($key,$value) = split(/=/,$item);
                   5892:             $$photo{$key} = $value;
                   5893:         }
                   5894:         return $outcome;
                   5895:     }
                   5896:     return 'error';
                   5897: }
                   5898: 
1.521     raeburn  5899: sub auto_instcode_format {
1.793     albertel 5900:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5901: 	$cat_order) = @_;
1.521     raeburn  5902:     my $courses = '';
1.772     raeburn  5903:     my @homeservers;
1.521     raeburn  5904:     if ($caller eq 'global') {
1.841     albertel 5905: 	my %servers = &get_servers($codedom,'library');
                   5906: 	foreach my $tryserver (keys(%servers)) {
                   5907: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5908: 		push(@homeservers,$tryserver);
                   5909: 	    }
1.584     raeburn  5910:         }
1.1022    raeburn  5911:     } elsif ($caller eq 'requests') {
                   5912:         if ($codedom =~ /^$match_domain$/) {
                   5913:             my $chome = &domain($codedom,'primary');
                   5914:             unless ($chome eq 'no_host') {
                   5915:                 push(@homeservers,$chome);
                   5916:             }
                   5917:         }
1.521     raeburn  5918:     } else {
1.772     raeburn  5919:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5920:     }
1.793     albertel 5921:     foreach my $code (keys(%{$instcodes})) {
                   5922:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5923:     }
                   5924:     chop($courses);
1.772     raeburn  5925:     my $ok_response = 0;
                   5926:     my $response;
                   5927:     while (@homeservers > 0 && $ok_response == 0) {
                   5928:         my $server = shift(@homeservers); 
                   5929:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5930:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5931:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5932: 		split(/:/,$response);
1.772     raeburn  5933:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5934:             push(@{$codetitles},&str2array($codetitles_str));
                   5935:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5936:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5937:             $ok_response = 1;
                   5938:         }
                   5939:     }
                   5940:     if ($ok_response) {
1.521     raeburn  5941:         return 'ok';
1.772     raeburn  5942:     } else {
                   5943:         return $response;
1.521     raeburn  5944:     }
                   5945: }
                   5946: 
1.792     raeburn  5947: sub auto_instcode_defaults {
                   5948:     my ($domain,$returnhash,$code_order) = @_;
                   5949:     my @homeservers;
1.841     albertel 5950: 
                   5951:     my %servers = &get_servers($domain,'library');
                   5952:     foreach my $tryserver (keys(%servers)) {
                   5953: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5954: 	    push(@homeservers,$tryserver);
                   5955: 	}
1.792     raeburn  5956:     }
1.841     albertel 5957: 
1.792     raeburn  5958:     my $response;
1.841     albertel 5959:     foreach my $server (@homeservers) {
1.792     raeburn  5960:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5961:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5962: 	
                   5963: 	foreach my $pair (split(/\&/,$response)) {
                   5964: 	    my ($name,$value)=split(/\=/,$pair);
                   5965: 	    if ($name eq 'code_order') {
                   5966: 		@{$code_order} = split(/\&/,&unescape($value));
                   5967: 	    } else {
                   5968: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5969: 	    }
                   5970: 	}
                   5971: 	return 'ok';
1.792     raeburn  5972:     }
1.841     albertel 5973: 
                   5974:     return $response;
1.1003    raeburn  5975: }
                   5976: 
                   5977: sub auto_possible_instcodes {
1.1007    raeburn  5978:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   5979:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   5980:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   5981:         return;
                   5982:     }
1.1003    raeburn  5983:     my (@homeservers,$uhome);
                   5984:     if (defined(&domain($domain,'primary'))) {
                   5985:         $uhome=&domain($domain,'primary');
                   5986:         push(@homeservers,&domain($domain,'primary'));
                   5987:     } else {
                   5988:         my %servers = &get_servers($domain,'library');
                   5989:         foreach my $tryserver (keys(%servers)) {
                   5990:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5991:                 push(@homeservers,$tryserver);
                   5992:             }
                   5993:         }
                   5994:     }
                   5995:     my $response;
                   5996:     foreach my $server (@homeservers) {
                   5997:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   5998:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  5999:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6000:             split(':',$response);
                   6001:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6002:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6003:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6004:             my ($name,$value)=split('=',$item);
                   6005:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6006:         }
                   6007:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6008:             my ($name,$value)=split('=',$item);
                   6009:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6010:         }
                   6011:         return 'ok';
                   6012:     }
                   6013:     return $response;
                   6014: }
1.792     raeburn  6015: 
1.1010    raeburn  6016: sub auto_courserequest_checks {
                   6017:     my ($dom) = @_;
1.1020    raeburn  6018:     my ($homeserver,%validations);
                   6019:     if ($dom =~ /^$match_domain$/) {
                   6020:         $homeserver = &domain($dom,'primary');
                   6021:     }
                   6022:     unless ($homeserver eq 'no_host') {
                   6023:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6024:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6025:             my @items = split(/&/,$response);
                   6026:             foreach my $item (@items) {
                   6027:                 my ($key,$value) = split('=',$item);
                   6028:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6029:             }
                   6030:         }
                   6031:     }
1.1010    raeburn  6032:     return %validations; 
                   6033: }
                   6034: 
1.1020    raeburn  6035: sub auto_courserequest_validation {
                   6036:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6037:     my ($homeserver,$response);
                   6038:     if ($dom =~ /^$match_domain$/) {
                   6039:         $homeserver = &domain($dom,'primary');
                   6040:     }
                   6041:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6042:           
1.1020    raeburn  6043:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6044:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6045:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6046:                                     $homeserver));
                   6047:     }
                   6048:     return $response;
                   6049: }
                   6050: 
1.777     albertel 6051: sub auto_validate_class_sec {
1.918     raeburn  6052:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6053:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6054:     my $ownerlist;
                   6055:     if (ref($owners) eq 'ARRAY') {
                   6056:         $ownerlist = join(',',@{$owners});
                   6057:     } else {
                   6058:         $ownerlist = $owners;
                   6059:     }
1.773     raeburn  6060:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6061:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6062:     return $response;
                   6063: }
                   6064: 
1.679     raeburn  6065: # ------------------------------------------------------- Course Group routines
                   6066: 
                   6067: sub get_coursegroups {
1.809     raeburn  6068:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6069:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6070: }
                   6071: 
1.679     raeburn  6072: sub modify_coursegroup {
                   6073:     my ($cdom,$cnum,$groupsettings) = @_;
                   6074:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6075: }
                   6076: 
1.809     raeburn  6077: sub toggle_coursegroup_status {
                   6078:     my ($cdom,$cnum,$group,$action) = @_;
                   6079:     my ($from_namespace,$to_namespace);
                   6080:     if ($action eq 'delete') {
                   6081:         $from_namespace = 'coursegroups';
                   6082:         $to_namespace = 'deleted_groups';
                   6083:     } else {
                   6084:         $from_namespace = 'deleted_groups';
                   6085:         $to_namespace = 'coursegroups';
                   6086:     }
                   6087:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6088:     if (my $tmp = &error(%curr_group)) {
                   6089:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6090:         return ('read error',$tmp);
                   6091:     } else {
                   6092:         my %savedsettings = %curr_group; 
1.809     raeburn  6093:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6094:         my $deloutcome;
                   6095:         if ($result eq 'ok') {
1.809     raeburn  6096:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6097:         } else {
                   6098:             return ('write error',$result);
                   6099:         }
                   6100:         if ($deloutcome eq 'ok') {
                   6101:             return 'ok';
                   6102:         } else {
                   6103:             return ('delete error',$deloutcome);
                   6104:         }
                   6105:     }
                   6106: }
                   6107: 
1.679     raeburn  6108: sub modify_group_roles {
1.957     raeburn  6109:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6110:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6111:     my $role = 'gr/'.&escape($userprivs);
                   6112:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6113:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6114:     if ($result eq 'ok') {
                   6115:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6116:     }
1.679     raeburn  6117:     return $result;
                   6118: }
                   6119: 
                   6120: sub modify_coursegroup_membership {
                   6121:     my ($cdom,$cnum,$membership) = @_;
                   6122:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6123:     return $result;
                   6124: }
                   6125: 
1.682     raeburn  6126: sub get_active_groups {
                   6127:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6128:     my $now = time;
                   6129:     my %groups = ();
                   6130:     foreach my $key (keys(%env)) {
1.811     albertel 6131:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6132:             my ($start,$end) = split(/\./,$env{$key});
                   6133:             if (($end!=0) && ($end<$now)) { next; }
                   6134:             if (($start!=0) && ($start>$now)) { next; }
                   6135:             if ($1 eq $cdom && $2 eq $cnum) {
                   6136:                 $groups{$3} = $env{$key} ;
                   6137:             }
                   6138:         }
                   6139:     }
                   6140:     return %groups;
                   6141: }
                   6142: 
1.683     raeburn  6143: sub get_group_membership {
                   6144:     my ($cdom,$cnum,$group) = @_;
                   6145:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6146: }
                   6147: 
                   6148: sub get_users_groups {
                   6149:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6150:     my @usersgroups;
1.683     raeburn  6151:     my $cachetime=1800;
                   6152: 
                   6153:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6154:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6155:     if (defined($cached)) {
1.734     albertel 6156:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6157:     } else {  
                   6158:         $grouplist = '';
1.816     raeburn  6159:         my $courseurl = &courseid_to_courseurl($courseid);
                   6160:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  6161:         my $access_end = $env{'course.'.$courseid.
                   6162:                               '.default_enrollment_end_date'};
                   6163:         my $now = time;
                   6164:         foreach my $key (keys(%roleshash)) {
                   6165:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6166:                 my $group = $1;
                   6167:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6168:                     my $start = $2;
                   6169:                     my $end = $1;
                   6170:                     if ($start == -1) { next; } # deleted from group
                   6171:                     if (($start!=0) && ($start>$now)) { next; }
                   6172:                     if (($end!=0) && ($end<$now)) {
                   6173:                         if ($access_end && $access_end < $now) {
                   6174:                             if ($access_end - $end < 86400) {
                   6175:                                 push(@usersgroups,$group);
1.733     raeburn  6176:                             }
                   6177:                         }
1.817     raeburn  6178:                         next;
1.733     raeburn  6179:                     }
1.817     raeburn  6180:                     push(@usersgroups,$group);
1.683     raeburn  6181:                 }
                   6182:             }
                   6183:         }
1.817     raeburn  6184:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6185:         $grouplist = join(':',@usersgroups);
                   6186:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6187:     }
1.733     raeburn  6188:     return @usersgroups;
1.683     raeburn  6189: }
                   6190: 
                   6191: sub devalidate_getgroups_cache {
                   6192:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6193:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6194: 
1.683     raeburn  6195:     my $hashid="$udom:$uname:$courseid";
                   6196:     &devalidate_cache_new('getgroups',$hashid);
                   6197: }
                   6198: 
1.12      www      6199: # ------------------------------------------------------------------ Plain Text
                   6200: 
                   6201: sub plaintext {
1.988     raeburn  6202:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6203:     if ($short =~ m{^cr/}) {
1.758     albertel 6204: 	return (split('/',$short))[-1];
                   6205:     }
1.742     raeburn  6206:     if (!defined($cid)) {
                   6207:         $cid = $env{'request.course.id'};
                   6208:     }
                   6209:     my %rolenames = (
1.1008    raeburn  6210:                       Course    => 'std',
                   6211:                       Community => 'alt1',
1.742     raeburn  6212:                     );
1.1037    raeburn  6213:     if ($cid ne '') {
                   6214:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6215:             unless ($forcedefault) {
                   6216:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6217:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6218:                 return &Apache::lonlocal::mt($roletext);
                   6219:             }
                   6220:         }
                   6221:     }
                   6222:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6223:         (defined($rolenames{$type})) && 
                   6224:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6225:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6226:     } elsif ($cid ne '') {
                   6227:         my $crstype = $env{'course.'.$cid.'.type'};
                   6228:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6229:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6230:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6231:         }
1.742     raeburn  6232:     }
1.1037    raeburn  6233:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6234: }
                   6235: 
                   6236: # ----------------------------------------------------------------- Assign Role
                   6237: 
                   6238: sub assignrole {
1.957     raeburn  6239:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6240:         $context)=@_;
1.21      www      6241:     my $mrole;
                   6242:     if ($role =~ /^cr\//) {
1.393     www      6243:         my $cwosec=$url;
1.811     albertel 6244:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6245: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6246:            my $refused = 1;
                   6247:            if ($context eq 'requestcourses') {
                   6248:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6249:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6250:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6251:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6252:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6253:                            if ($crsenv{'internal.courseowner'} eq
                   6254:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6255:                                $refused = '';
                   6256:                            }
                   6257:                        }
                   6258:                    }
                   6259:                }
                   6260:            }
                   6261:            if ($refused) {
                   6262:                &logthis('Refused custom assignrole: '.
                   6263:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   6264:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   6265:                return 'refused';
                   6266:            }
1.104     www      6267:         }
1.21      www      6268:         $mrole='cr';
1.678     raeburn  6269:     } elsif ($role =~ /^gr\//) {
                   6270:         my $cwogrp=$url;
1.811     albertel 6271:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  6272:         unless (&allowed('mdg',$cwogrp)) {
                   6273:             &logthis('Refused group assignrole: '.
                   6274:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   6275:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   6276:             return 'refused';
                   6277:         }
                   6278:         $mrole='gr';
1.21      www      6279:     } else {
1.82      www      6280:         my $cwosec=$url;
1.811     albertel 6281:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  6282:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   6283:             my $refused;
                   6284:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   6285:                 if (!(&allowed('c'.$role,$url))) {
                   6286:                     $refused = 1;
                   6287:                 }
                   6288:             } else {
                   6289:                 $refused = 1;
                   6290:             }
1.947     raeburn  6291:             if ($refused) {
1.1045    raeburn  6292:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6293:                 if (!$selfenroll && $context eq 'course') {
                   6294:                     my %crsenv;
                   6295:                     if ($role eq 'cc' || $role eq 'co') {
                   6296:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6297:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   6298:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   6299:                                 if ($crsenv{'internal.courseowner'} eq 
                   6300:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6301:                                     $refused = '';
                   6302:                                 }
                   6303:                             }
                   6304:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   6305:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   6306:                                 if ($crsenv{'internal.courseowner'} eq 
                   6307:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   6308:                                     $refused = '';
                   6309:                                 }
                   6310:                             }
                   6311:                         }
                   6312:                     }
                   6313:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  6314:                     $refused = '';
1.1048.2.4! raeburn  6315:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($cdom eq 'gci') && (($cnum eq '1H96711d710194bfegcil1') || ($cnum eq '5422913620b814c90gcil1'))) {
1.1048.2.1  raeburn  6316:                     if ($env{'request.role'} eq 'cc./gci/9615072b469884921gcil1') {
                   6317:                         $refused = '';
                   6318:                     }
1.1017    raeburn  6319:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  6320:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  6321:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  6322:                         my $wrongcc;
                   6323:                         if ($cnum =~ /^$match_community$/) {
                   6324:                             $wrongcc = 1 if ($role eq 'cc');
                   6325:                         } else {
                   6326:                             $wrongcc = 1 if ($role eq 'co');
                   6327:                         }
                   6328:                         unless ($wrongcc) {
                   6329:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6330:                             if ($crsenv{'internal.courseowner'} eq 
                   6331:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   6332:                                 $refused = '';
                   6333:                             }
1.1017    raeburn  6334:                         }
                   6335:                     }
                   6336:                 }
                   6337:                 if ($refused) {
1.947     raeburn  6338:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   6339:                              ' '.$role.' '.$end.' '.$start.' by '.
                   6340: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   6341:                     return 'refused';
                   6342:                 }
1.932     raeburn  6343:             }
1.104     www      6344:         }
1.21      www      6345:         $mrole=$role;
                   6346:     }
1.620     albertel 6347:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6348:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      6349:     if ($end) { $command.='_'.$end; }
1.21      www      6350:     if ($start) {
                   6351: 	if ($end) { 
1.81      www      6352:            $command.='_'.$start; 
1.21      www      6353:         } else {
1.81      www      6354:            $command.='_0_'.$start;
1.21      www      6355:         }
                   6356:     }
1.739     raeburn  6357:     my $origstart = $start;
                   6358:     my $origend = $end;
1.957     raeburn  6359:     my $delflag;
1.357     www      6360: # actually delete
                   6361:     if ($deleteflag) {
1.373     www      6362: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      6363: # modify command to delete the role
1.620     albertel 6364:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      6365:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 6366: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      6367: # set start and finish to negative values for userrolelog
                   6368:            $start=-1;
                   6369:            $end=-1;
1.957     raeburn  6370:            $delflag = 1;
1.357     www      6371:         }
                   6372:     }
                   6373: # send command
1.349     www      6374:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      6375: # log new user role if status is ok
1.349     www      6376:     if ($answer eq 'ok') {
1.663     raeburn  6377: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  6378: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  6379:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  6380:         unless ($role =~ /^gr/) {
                   6381:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  6382:                                              $origstart,$selfenroll,$context);
1.739     raeburn  6383:         }
1.349     www      6384:     }
                   6385:     return $answer;
1.169     harris41 6386: }
                   6387: 
                   6388: # -------------------------------------------------- Modify user authentication
1.197     www      6389: # Overrides without validation
                   6390: 
1.169     harris41 6391: sub modifyuserauth {
                   6392:     my ($udom,$uname,$umode,$upass)=@_;
                   6393:     my $uhome=&homeserver($uname,$udom);
1.197     www      6394:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   6395:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 6396:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6397:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 6398:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   6399: 		     &escape($upass),$uhome);
1.620     albertel 6400:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      6401:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   6402:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   6403:     &log($udom,,$uname,$uhome,
1.620     albertel 6404:         'Authentication changed by '.$env{'user.domain'}.', '.
                   6405:                                      $env{'user.name'}.', '.$umode.
1.197     www      6406:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 6407:     unless ($reply eq 'ok') {
1.197     www      6408:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 6409: 	return 'error: '.$reply;
                   6410:     }   
1.170     harris41 6411:     return 'ok';
1.80      www      6412: }
                   6413: 
1.81      www      6414: # --------------------------------------------------------------- Modify a user
1.80      www      6415: 
1.81      www      6416: sub modifyuser {
1.206     matthew  6417:     my ($udom,    $uname, $uid,
                   6418:         $umode,   $upass, $first,
                   6419:         $middle,  $last,  $gene,
1.963     raeburn  6420:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 6421:     $udom= &LONCAPA::clean_domain($udom);
                   6422:     $uname=&LONCAPA::clean_username($uname);
1.81      www      6423:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      6424:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  6425: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   6426:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   6427:                                      ' desiredhome not specified'). 
1.620     albertel 6428:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   6429:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 6430:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      6431: # ----------------------------------------------------------------- Create User
1.406     albertel 6432:     if (($uhome eq 'no_host') && 
                   6433: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      6434:         my $unhome='';
1.844     albertel 6435:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  6436:             $unhome = $desiredhome;
1.620     albertel 6437: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   6438: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  6439:         } else { # load balancing routine for determining $unhome
1.81      www      6440:             my $loadm=10000000;
1.841     albertel 6441: 	    my %servers = &get_servers($udom,'library');
                   6442: 	    foreach my $tryserver (keys(%servers)) {
                   6443: 		my $answer=reply('load',$tryserver);
                   6444: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   6445: 		    $loadm=$answer;
                   6446: 		    $unhome=$tryserver;
                   6447: 		}
1.80      www      6448: 	    }
                   6449:         }
                   6450:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  6451: 	    return 'error: unable to find a home server for '.$uname.
                   6452:                    ' in domain '.$udom;
1.80      www      6453:         }
                   6454:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   6455:                          &escape($upass),$unhome);
                   6456: 	unless ($reply eq 'ok') {
                   6457:             return 'error: '.$reply;
                   6458:         }   
1.230     stredwic 6459:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      6460:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  6461: 	    return 'error: unable verify users home machine.';
1.80      www      6462:         }
1.209     matthew  6463:     }   # End of creation of new user
1.80      www      6464: # ---------------------------------------------------------------------- Add ID
                   6465:     if ($uid) {
                   6466:        $uid=~tr/A-Z/a-z/;
                   6467:        my %uidhash=&idrget($udom,$uname);
1.196     www      6468:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   6469:          && (!$forceid)) {
1.80      www      6470: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  6471: 	      return 'error: user id "'.$uid.'" does not match '.
                   6472:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      6473:           }
                   6474:        } else {
                   6475: 	  &idput($udom,($uname => $uid));
                   6476:        }
                   6477:     }
                   6478: # -------------------------------------------------------------- Add names, etc
1.313     matthew  6479:     my @tmp=&get('environment',
1.899     raeburn  6480: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  6481:                     'permanentemail','inststatus'],
1.134     albertel 6482: 		   $udom,$uname);
1.313     matthew  6483:     my %names;
                   6484:     if ($tmp[0] =~ m/^error:.*/) { 
                   6485:         %names=(); 
                   6486:     } else {
                   6487:         %names = @tmp;
                   6488:     }
1.388     www      6489: #
                   6490: # Make sure to not trash student environment if instructor does not bother
                   6491: # to supply name and email information
                   6492: #
                   6493:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  6494:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      6495:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  6496:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      6497:     if ($email) {
                   6498:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  6499:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      6500:     }
1.899     raeburn  6501:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  6502:     if (defined($inststatus)) {
                   6503:         $names{'inststatus'} = '';
                   6504:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   6505:         if (ref($usertypes) eq 'HASH') {
                   6506:             my @okstatuses; 
                   6507:             foreach my $item (split(/:/,$inststatus)) {
                   6508:                 if (defined($usertypes->{$item})) {
                   6509:                     push(@okstatuses,$item);  
                   6510:                 }
                   6511:             }
                   6512:             if (@okstatuses) {
                   6513:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   6514:             }
                   6515:         }
                   6516:     }
1.134     albertel 6517:     my $reply = &put('environment', \%names, $udom,$uname);
                   6518:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  6519:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      6520:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  6521:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   6522:                  $umode.', '.$first.', '.$middle.', '.
                   6523: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   6524:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   6525:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   6526:     } else {
                   6527:         $logmsg .= ' during self creation';
                   6528:     }
                   6529:     &logthis($logmsg);
1.134     albertel 6530:     return 'ok';
1.80      www      6531: }
                   6532: 
1.81      www      6533: # -------------------------------------------------------------- Modify student
1.80      www      6534: 
1.81      www      6535: sub modifystudent {
                   6536:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  6537:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  6538:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 6539:     if (!$cid) {
1.620     albertel 6540: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6541: 	    return 'not_in_class';
                   6542: 	}
1.80      www      6543:     }
                   6544: # --------------------------------------------------------------- Make the user
1.81      www      6545:     my $reply=&modifyuser
1.209     matthew  6546: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  6547:          $desiredhome,$email,$inststatus);
1.80      www      6548:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  6549:     # This will cause &modify_student_enrollment to get the uid from the
                   6550:     # students environment
                   6551:     $uid = undef if (!$forceid);
1.455     albertel 6552:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  6553: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  6554:     return $reply;
                   6555: }
                   6556: 
                   6557: sub modify_student_enrollment {
1.957     raeburn  6558:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 6559:     my ($cdom,$cnum,$chome);
                   6560:     if (!$cid) {
1.620     albertel 6561: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 6562: 	    return 'not_in_class';
                   6563: 	}
1.620     albertel 6564: 	$cdom=$env{'course.'.$cid.'.domain'};
                   6565: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 6566:     } else {
                   6567: 	($cdom,$cnum)=split(/_/,$cid);
                   6568:     }
1.620     albertel 6569:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 6570:     if (!$chome) {
1.457     raeburn  6571: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  6572:     }
1.455     albertel 6573:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  6574:     # Make sure the user exists
1.81      www      6575:     my $uhome=&homeserver($uname,$udom);
                   6576:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6577: 	return 'error: no such user';
                   6578:     }
1.297     matthew  6579:     # Get student data if we were not given enough information
                   6580:     if (!defined($first)  || $first  eq '' || 
                   6581:         !defined($last)   || $last   eq '' || 
                   6582:         !defined($uid)    || $uid    eq '' || 
                   6583:         !defined($middle) || $middle eq '' || 
                   6584:         !defined($gene)   || $gene   eq '') {
1.294     matthew  6585:         # They did not supply us with enough data to enroll the student, so
                   6586:         # we need to pick up more information.
1.297     matthew  6587:         my %tmp = &get('environment',
1.294     matthew  6588:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  6589:                        ,$udom,$uname);
                   6590: 
1.800     albertel 6591:         #foreach my $key (keys(%tmp)) {
                   6592:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 6593:         #}
1.294     matthew  6594:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   6595:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   6596:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  6597:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  6598:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   6599:     }
1.556     albertel 6600:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 6601:     my $reply=cput('classlist',
                   6602: 		   {"$uname:$udom" => 
1.515     raeburn  6603: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 6604: 		   $cdom,$cnum);
1.81      www      6605:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   6606: 	return 'error: '.$reply;
1.652     albertel 6607:     } else {
                   6608: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      6609:     }
1.297     matthew  6610:     # Add student role to user
1.83      www      6611:     my $uurl='/'.$cid;
1.81      www      6612:     $uurl=~s/\_/\//g;
                   6613:     if ($usec) {
                   6614: 	$uurl.='/'.$usec;
                   6615:     }
1.957     raeburn  6616:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      6617: }
                   6618: 
1.556     albertel 6619: sub format_name {
                   6620:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   6621:     my $name;
                   6622:     if ($first ne 'lastname') {
                   6623: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   6624:     } else {
                   6625: 	if ($lastname=~/\S/) {
                   6626: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   6627: 	    $name=~s/\s+,/,/;
                   6628: 	} else {
                   6629: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   6630: 	}
                   6631:     }
                   6632:     $name=~s/^\s+//;
                   6633:     $name=~s/\s+$//;
                   6634:     $name=~s/\s+/ /g;
                   6635:     return $name;
                   6636: }
                   6637: 
1.84      www      6638: # ------------------------------------------------- Write to course preferences
                   6639: 
                   6640: sub writecoursepref {
                   6641:     my ($courseid,%prefs)=@_;
                   6642:     $courseid=~s/^\///;
                   6643:     $courseid=~s/\_/\//g;
                   6644:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6645:     my $chome=homeserver($cnum,$cdomain);
                   6646:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6647: 	return 'error: no such course';
                   6648:     }
                   6649:     my $cstring='';
1.800     albertel 6650:     foreach my $pref (keys(%prefs)) {
                   6651: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6652:     }
1.84      www      6653:     $cstring=~s/\&$//;
                   6654:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6655: }
                   6656: 
                   6657: # ---------------------------------------------------------- Make/modify course
                   6658: 
                   6659: sub createcourse {
1.741     raeburn  6660:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  6661:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      6662:     $url=&declutter($url);
                   6663:     my $cid='';
1.1028    raeburn  6664:     if ($context eq 'requestcourses') {
                   6665:         my $can_create = 0;
                   6666:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   6667:         if ($udom eq $ownerdom) {
                   6668:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   6669:                                   $context)) {
                   6670:                 $can_create = 1;
                   6671:             }
                   6672:         } else {
                   6673:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   6674:                                            $category);
                   6675:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   6676:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   6677:                 if (@curr > 0) {
                   6678:                     my @options = qw(approval validate autolimit);
                   6679:                     my $optregex = join('|',@options);
                   6680:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   6681:                         $can_create = 1;
                   6682:                     }
                   6683:                 }
                   6684:             }
                   6685:         }
                   6686:         if ($can_create) {
                   6687:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   6688:                 unless (&allowed('ccc',$udom)) {
                   6689:                     return 'refused'; 
                   6690:                 }
1.1017    raeburn  6691:             }
                   6692:         } else {
                   6693:             return 'refused';
                   6694:         }
1.1028    raeburn  6695:     } elsif (!&allowed('ccc',$udom)) {
                   6696:         return 'refused';
1.84      www      6697:     }
1.1011    raeburn  6698: # --------------------------------------------------------------- Get Unique ID
                   6699:     my $uname;
                   6700:     if ($cnum =~ /^$match_courseid$/) {
                   6701:         my $chome=&homeserver($cnum,$udom,'true');
                   6702:         if (($chome eq '') || ($chome eq 'no_host')) {
                   6703:             $uname = $cnum;
                   6704:         } else {
1.1038    raeburn  6705:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  6706:         }
                   6707:     } else {
1.1038    raeburn  6708:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  6709:     }
                   6710:     return $uname if ($uname =~ /^error/);
                   6711: # -------------------------------------------------- Check supplied server name
1.620     albertel 6712:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6713:     if (! &is_library($course_server)) {
1.264     matthew  6714:         return 'error:bad server name '.$course_server;
                   6715:     }
1.84      www      6716: # ------------------------------------------------------------- Make the course
                   6717:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6718:                       $course_server);
1.84      www      6719:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  6720:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6721:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6722: 	return 'error: no such course';
                   6723:     }
1.271     www      6724: # ----------------------------------------------------------------- Course made
1.516     raeburn  6725: # log existence
1.1029    raeburn  6726:     my $now = time;
1.918     raeburn  6727:     my $newcourse = {
                   6728:                     $udom.'_'.$uname => {
1.921     raeburn  6729:                                      description => $description,
                   6730:                                      inst_code   => $inst_code,
                   6731:                                      owner       => $course_owner,
                   6732:                                      type        => $crstype,
1.1029    raeburn  6733:                                      creator     => $env{'user.name'}.':'.
                   6734:                                                     $env{'user.domain'},
                   6735:                                      created     => $now,
                   6736:                                      context     => $context,
1.918     raeburn  6737:                                                 },
                   6738:                     };
1.921     raeburn  6739:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6740: # set toplevel url
1.271     www      6741:     my $topurl=$url;
                   6742:     unless ($nonstandard) {
                   6743: # ------------------------------------------ For standard courses, make top url
                   6744:         my $mapurl=&clutter($url);
1.278     www      6745:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6746:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6747: <map>
                   6748: <resource id="1" type="start"></resource>
                   6749: <resource id="2" src="$mapurl"></resource>
                   6750: <resource id="3" type="finish"></resource>
                   6751: <link index="1" from="1" to="2"></link>
                   6752: <link index="2" from="2" to="3"></link>
                   6753: </map>
                   6754: ENDINITMAP
                   6755:         $topurl=&declutter(
1.638     albertel 6756:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6757:                           );
                   6758:     }
                   6759: # ----------------------------------------------------------- Write preferences
1.84      www      6760:     &writecoursepref($udom.'_'.$uname,
                   6761:                      ('description' => $description,
1.271     www      6762:                       'url'         => $topurl));
1.84      www      6763:     return '/'.$udom.'/'.$uname;
                   6764: }
                   6765: 
1.1011    raeburn  6766: # ------------------------------------------------------------------- Create ID
                   6767: sub generate_coursenum {
1.1038    raeburn  6768:     my ($udom,$crstype) = @_;
1.1011    raeburn  6769:     my $domdesc = &domain($udom);
                   6770:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  6771:     my $first;
                   6772:     if ($crstype eq 'Community') {
                   6773:         $first = '0';
                   6774:     } else {
                   6775:         $first = int(1+rand(9)); 
                   6776:     } 
                   6777:     my $uname=$first.
1.1011    raeburn  6778:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6779:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6780:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6781: # ----------------------------------------------- Make sure that does not exist
                   6782:     my $uhome=&homeserver($uname,$udom,'true');
                   6783:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  6784:         if ($crstype eq 'Community') {
                   6785:             $first = '0';
                   6786:         } else {
                   6787:             $first = int(1+rand(9));
                   6788:         }
                   6789:         $uname=$first.
1.1011    raeburn  6790:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6791:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6792:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6793:         $uhome=&homeserver($uname,$udom,'true');
                   6794:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6795:             return 'error: unable to generate unique course-ID';
                   6796:         }
                   6797:     }
                   6798:     return $uname;
                   6799: }
                   6800: 
1.813     albertel 6801: sub is_course {
                   6802:     my ($cdom,$cnum) = @_;
                   6803:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6804: 				undef,'.');
1.813     albertel 6805:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6806:         return 1;
                   6807:     }
                   6808:     return 0;
                   6809: }
                   6810: 
1.1015    raeburn  6811: sub store_userdata {
                   6812:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  6813:     my $result;
1.1016    raeburn  6814:     if ($datakey ne '') {
1.1013    raeburn  6815:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  6816:             if ($udom eq '' || $uname eq '') {
                   6817:                 $udom = $env{'user.domain'};
                   6818:                 $uname = $env{'user.name'};
                   6819:             }
                   6820:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  6821:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   6822:                 $result = 'error: no_host';
                   6823:             } else {
                   6824:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   6825:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   6826: 
                   6827:                 my $namevalue='';
                   6828:                 foreach my $key (keys(%{$storehash})) {
                   6829:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6830:                 }
                   6831:                 $namevalue=~s/\&$//;
                   6832:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015    raeburn  6833:                                   "$namespace:$datakey:$namevalue",$uhome);
1.1013    raeburn  6834:             }
                   6835:         } else {
                   6836:             $result = 'error: data to store was not a hash reference'; 
                   6837:         }
                   6838:     } else {
                   6839:         $result= 'error: invalid requestkey'; 
                   6840:     }
                   6841:     return $result;
                   6842: }
                   6843: 
1.21      www      6844: # ---------------------------------------------------------- Assign Custom Role
                   6845: 
                   6846: sub assigncustomrole {
1.957     raeburn  6847:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6848:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6849:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6850: }
                   6851: 
                   6852: # ----------------------------------------------------------------- Revoke Role
                   6853: 
                   6854: sub revokerole {
1.957     raeburn  6855:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6856:     my $now=time;
1.965     raeburn  6857:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6858: }
                   6859: 
                   6860: # ---------------------------------------------------------- Revoke Custom Role
                   6861: 
                   6862: sub revokecustomrole {
1.957     raeburn  6863:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6864:     my $now=time;
1.357     www      6865:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6866:            $deleteflag,$selfenroll,$context);
1.17      www      6867: }
                   6868: 
1.533     banghart 6869: # ------------------------------------------------------------ Disk usage
1.535     albertel 6870: sub diskusage {
1.955     raeburn  6871:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6872:     $directorypath =~ s/\/$//;
                   6873:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6874:                        .&escape($getpropath).':'.&escape($uname).':'
                   6875:                        .&escape($udom),homeserver($uname,$udom));
                   6876:     if ($listing eq 'unknown_cmd') {
                   6877:         if ($getpropath) {
                   6878:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6879:         }
                   6880:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6881:     }
1.514     albertel 6882:     return $listing;
1.512     banghart 6883: }
                   6884: 
1.566     banghart 6885: sub is_locked {
                   6886:     my ($file_name, $domain, $user) = @_;
                   6887:     my @check;
                   6888:     my $is_locked;
                   6889:     push @check, $file_name;
1.613     albertel 6890:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6891: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6892:     my ($tmp)=keys(%locked);
                   6893:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6894:     
1.566     banghart 6895:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6896:         $is_locked = 'false';
                   6897:         foreach my $entry (@{$locked{$file_name}}) {
                   6898:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6899:                $is_locked = 'true';
                   6900:                last;
1.745     raeburn  6901:            }
                   6902:        }
1.566     banghart 6903:     } else {
                   6904:         $is_locked = 'false';
                   6905:     }
                   6906: }
                   6907: 
1.759     albertel 6908: sub declutter_portfile {
                   6909:     my ($file) = @_;
1.833     albertel 6910:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6911:     return $file;
                   6912: }
                   6913: 
1.559     banghart 6914: # ------------------------------------------------------------- Mark as Read Only
                   6915: 
                   6916: sub mark_as_readonly {
                   6917:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6918:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6919:     my ($tmp)=keys(%current_permissions);
                   6920:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6921:     foreach my $file (@{$files}) {
1.759     albertel 6922: 	$file = &declutter_portfile($file);
1.561     banghart 6923:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6924:     }
1.613     albertel 6925:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6926:     return;
                   6927: }
                   6928: 
1.572     banghart 6929: # ------------------------------------------------------------Save Selected Files
                   6930: 
                   6931: sub save_selected_files {
                   6932:     my ($user, $path, @files) = @_;
                   6933:     my $filename = $user."savedfiles";
1.573     banghart 6934:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6935:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6936:     foreach my $file (@files) {
1.620     albertel 6937:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6938:     }
                   6939:     foreach my $file (@other_files) {
1.574     banghart 6940:         print (OUT $file."\n");
1.572     banghart 6941:     }
1.574     banghart 6942:     close (OUT);
1.572     banghart 6943:     return 'ok';
                   6944: }
                   6945: 
1.574     banghart 6946: sub clear_selected_files {
                   6947:     my ($user) = @_;
                   6948:     my $filename = $user."savedfiles";
                   6949:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6950:     print (OUT undef);
                   6951:     close (OUT);
                   6952:     return ("ok");    
                   6953: }
                   6954: 
1.572     banghart 6955: sub files_in_path {
                   6956:     my ($user, $path) = @_;
                   6957:     my $filename = $user."savedfiles";
                   6958:     my %return_files;
1.574     banghart 6959:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6960:     while (my $line_in = <IN>) {
1.574     banghart 6961:         chomp ($line_in);
                   6962:         my @paths_and_file = split (m!/!, $line_in);
                   6963:         my $file_part = pop (@paths_and_file);
                   6964:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6965:         $path_part.='/';
                   6966:         my $path_and_file = $path_part.$file_part;
                   6967:         if ($path_part eq $path) {
                   6968:             $return_files{$file_part}= 'selected';
                   6969:         }
                   6970:     }
1.574     banghart 6971:     close (IN);
                   6972:     return (\%return_files);
1.572     banghart 6973: }
                   6974: 
                   6975: # called in portfolio select mode, to show files selected NOT in current directory
                   6976: sub files_not_in_path {
                   6977:     my ($user, $path) = @_;
                   6978:     my $filename = $user."savedfiles";
                   6979:     my @return_files;
                   6980:     my $path_part;
1.800     albertel 6981:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6982:     while (my $line = <IN>) {
1.572     banghart 6983:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6984:         my @paths_and_file = split(m|/|, $line);
                   6985:         my $file_part = pop(@paths_and_file);
                   6986:         chomp($file_part);
                   6987:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6988:         $path_part .= '/';
                   6989:         my $path_and_file = $path_part.$file_part;
                   6990:         if ($path_part ne $path) {
1.800     albertel 6991:             push(@return_files, ($path_and_file));
1.572     banghart 6992:         }
                   6993:     }
1.800     albertel 6994:     close(OUT);
1.574     banghart 6995:     return (@return_files);
1.572     banghart 6996: }
                   6997: 
1.745     raeburn  6998: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6999: 
1.745     raeburn  7000: sub get_portfile_permissions {
                   7001:     my ($domain,$user) = @_;
1.613     albertel 7002:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7003:     my ($tmp)=keys(%current_permissions);
                   7004:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7005:     return \%current_permissions;
                   7006: }
                   7007: 
                   7008: #---------------------------------------------Get portfolio file access controls
                   7009: 
1.749     raeburn  7010: sub get_access_controls {
1.745     raeburn  7011:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7012:     my %access;
                   7013:     my $real_file = $file;
                   7014:     $file =~ s/\.meta$//;
1.745     raeburn  7015:     if (defined($file)) {
1.749     raeburn  7016:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7017:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7018:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7019:             }
                   7020:         }
1.745     raeburn  7021:     } else {
1.749     raeburn  7022:         foreach my $key (keys(%{$current_permissions})) {
                   7023:             if ($key =~ /\0accesscontrol$/) {
                   7024:                 if (defined($group)) {
                   7025:                     if ($key !~ m-^\Q$group\E/-) {
                   7026:                         next;
                   7027:                     }
                   7028:                 }
                   7029:                 my ($fullpath) = split(/\0/,$key);
                   7030:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7031:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7032:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7033:                     }
                   7034:                 }
                   7035:             }
                   7036:         }
                   7037:     }
                   7038:     return %access;
                   7039: }
                   7040: 
                   7041: sub modify_access_controls {
                   7042:     my ($file_name,$changes,$domain,$user)=@_;
                   7043:     my ($outcome,$deloutcome);
                   7044:     my %store_permissions;
                   7045:     my %new_values;
                   7046:     my %new_control;
                   7047:     my %translation;
                   7048:     my @deletions = ();
                   7049:     my $now = time;
                   7050:     if (exists($$changes{'activate'})) {
                   7051:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7052:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7053:             my $numnew = scalar(@newitems);
                   7054:             for (my $i=0; $i<$numnew; $i++) {
                   7055:                 my $newkey = $newitems[$i];
                   7056:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7057:                 if ($newkey =~ /^\d+:/) { 
                   7058:                     $newkey =~ s/^(\d+)/$newid/;
                   7059:                     $translation{$1} = $newid;
                   7060:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7061:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7062:                     $translation{$1} = $newid;
                   7063:                 }
1.749     raeburn  7064:                 $new_values{$file_name."\0".$newkey} = 
                   7065:                                           $$changes{'activate'}{$newitems[$i]};
                   7066:                 $new_control{$newkey} = $now;
                   7067:             }
                   7068:         }
                   7069:     }
                   7070:     my %todelete;
                   7071:     my %changed_items;
                   7072:     foreach my $action ('delete','update') {
                   7073:         if (exists($$changes{$action})) {
                   7074:             if (ref($$changes{$action}) eq 'HASH') {
                   7075:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7076:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7077:                     if ($action eq 'delete') { 
                   7078:                         $todelete{$itemnum} = 1;
                   7079:                     } else {
                   7080:                         $changed_items{$itemnum} = $key;
                   7081:                     }
                   7082:                 }
1.745     raeburn  7083:             }
                   7084:         }
1.749     raeburn  7085:     }
                   7086:     # get lock on access controls for file.
                   7087:     my $lockhash = {
                   7088:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7089:                                                        ':'.$env{'user.domain'},
                   7090:                    }; 
                   7091:     my $tries = 0;
                   7092:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7093:    
                   7094:     while (($gotlock ne 'ok') && $tries <3) {
                   7095:         $tries ++;
                   7096:         sleep 1;
                   7097:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7098:     }
                   7099:     if ($gotlock eq 'ok') {
                   7100:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   7101:         my ($tmp)=keys(%curr_permissions);
                   7102:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   7103:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   7104:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   7105:             if (ref($curr_controls) eq 'HASH') {
                   7106:                 foreach my $control_item (keys(%{$curr_controls})) {
                   7107:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   7108:                     if (defined($todelete{$itemnum})) {
                   7109:                         push(@deletions,$file_name."\0".$control_item);
                   7110:                     } else {
                   7111:                         if (defined($changed_items{$itemnum})) {
                   7112:                             $new_control{$changed_items{$itemnum}} = $now;
                   7113:                             push(@deletions,$file_name."\0".$control_item);
                   7114:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   7115:                         } else {
                   7116:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   7117:                         }
                   7118:                     }
1.745     raeburn  7119:                 }
                   7120:             }
                   7121:         }
1.970     raeburn  7122:         my ($group);
                   7123:         if (&is_course($domain,$user)) {
                   7124:             ($group,my $file) = split(/\//,$file_name,2);
                   7125:         }
1.749     raeburn  7126:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   7127:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   7128:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   7129:         #  remove lock
                   7130:         my @del_lock = ($file_name."\0".'locked_access_records');
                   7131:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  7132:         my $sqlresult =
1.970     raeburn  7133:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  7134:                                     $group);
1.749     raeburn  7135:     } else {
                   7136:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  7137:     }
1.749     raeburn  7138:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  7139: }
                   7140: 
1.827     raeburn  7141: sub make_public_indefinitely {
                   7142:     my ($requrl) = @_;
                   7143:     my $now = time;
                   7144:     my $action = 'activate';
                   7145:     my $aclnum = 0;
                   7146:     if (&is_portfolio_url($requrl)) {
                   7147:         my (undef,$udom,$unum,$file_name,$group) =
                   7148:             &parse_portfolio_url($requrl);
                   7149:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   7150:         my %access_controls = &get_access_controls($current_perms,
                   7151:                                                    $group,$file_name);
                   7152:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   7153:             my ($num,$scope,$end,$start) = 
                   7154:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7155:             if ($scope eq 'public') {
                   7156:                 if ($start <= $now && $end == 0) {
                   7157:                     $action = 'none';
                   7158:                 } else {
                   7159:                     $action = 'update';
                   7160:                     $aclnum = $num;
                   7161:                 }
                   7162:                 last;
                   7163:             }
                   7164:         }
                   7165:         if ($action eq 'none') {
                   7166:              return 'ok';
                   7167:         } else {
                   7168:             my %changes;
                   7169:             my $newend = 0;
                   7170:             my $newstart = $now;
                   7171:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   7172:             $changes{$action}{$newkey} = {
                   7173:                 type => 'public',
                   7174:                 time => {
                   7175:                     start => $newstart,
                   7176:                     end   => $newend,
                   7177:                 },
                   7178:             };
                   7179:             my ($outcome,$deloutcome,$new_values,$translation) =
                   7180:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   7181:             return $outcome;
                   7182:         }
                   7183:     } else {
                   7184:         return 'invalid';
                   7185:     }
                   7186: }
                   7187: 
1.745     raeburn  7188: #------------------------------------------------------Get Marked as Read Only
                   7189: 
                   7190: sub get_marked_as_readonly {
                   7191:     my ($domain,$user,$what,$group) = @_;
                   7192:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 7193:     my @readonly_files;
1.629     banghart 7194:     my $cmp1=$what;
                   7195:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  7196:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7197:         if (defined($group)) {
                   7198:             if ($file_name !~ m-^\Q$group\E/-) {
                   7199:                 next;
                   7200:             }
                   7201:         }
1.561     banghart 7202:         if (ref($value) eq "ARRAY"){
                   7203:             foreach my $stored_what (@{$value}) {
1.629     banghart 7204:                 my $cmp2=$stored_what;
1.759     albertel 7205:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  7206:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  7207:                 }
1.629     banghart 7208:                 if ($cmp1 eq $cmp2) {
1.561     banghart 7209:                     push(@readonly_files, $file_name);
1.745     raeburn  7210:                     last;
1.563     banghart 7211:                 } elsif (!defined($what)) {
                   7212:                     push(@readonly_files, $file_name);
1.745     raeburn  7213:                     last;
1.561     banghart 7214:                 }
                   7215:             }
1.745     raeburn  7216:         }
1.561     banghart 7217:     }
                   7218:     return @readonly_files;
                   7219: }
1.577     banghart 7220: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 7221: 
1.577     banghart 7222: sub get_marked_as_readonly_hash {
1.745     raeburn  7223:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 7224:     my %readonly_files;
1.745     raeburn  7225:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   7226:         if (defined($group)) {
                   7227:             if ($file_name !~ m-^\Q$group\E/-) {
                   7228:                 next;
                   7229:             }
                   7230:         }
1.577     banghart 7231:         if (ref($value) eq "ARRAY"){
                   7232:             foreach my $stored_what (@{$value}) {
1.745     raeburn  7233:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 7234:                     foreach my $lock_descriptor(@{$stored_what}) {
                   7235:                         if ($lock_descriptor eq 'graded') {
                   7236:                             $readonly_files{$file_name} = 'graded';
                   7237:                         } elsif ($lock_descriptor eq 'handback') {
                   7238:                             $readonly_files{$file_name} = 'handback';
                   7239:                         } else {
                   7240:                             if (!exists($readonly_files{$file_name})) {
                   7241:                                 $readonly_files{$file_name} = 'locked';
                   7242:                             }
                   7243:                         }
1.745     raeburn  7244:                     }
1.750     banghart 7245:                 } 
1.577     banghart 7246:             }
                   7247:         } 
                   7248:     }
                   7249:     return %readonly_files;
                   7250: }
1.559     banghart 7251: # ------------------------------------------------------------ Unmark as Read Only
                   7252: 
                   7253: sub unmark_as_readonly {
1.629     banghart 7254:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   7255:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  7256:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 7257:     $file_name = &declutter_portfile($file_name);
1.634     albertel 7258:     my $symb_crs = $what;
                   7259:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  7260:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 7261:     my ($tmp)=keys(%current_permissions);
                   7262:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7263:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 7264:     foreach my $file (@readonly_files) {
1.759     albertel 7265: 	my $clean_file = &declutter_portfile($file);
                   7266: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 7267: 	my $current_locks = $current_permissions{$file};
1.563     banghart 7268:         my @new_locks;
                   7269:         my @del_keys;
                   7270:         if (ref($current_locks) eq "ARRAY"){
                   7271:             foreach my $locker (@{$current_locks}) {
1.632     albertel 7272:                 my $compare=$locker;
1.749     raeburn  7273:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  7274:                     $compare=join('',@{$locker});
1.746     raeburn  7275:                     if ($compare ne $symb_crs) {
                   7276:                         push(@new_locks, $locker);
                   7277:                     }
1.563     banghart 7278:                 }
                   7279:             }
1.650     albertel 7280:             if (scalar(@new_locks) > 0) {
1.563     banghart 7281:                 $current_permissions{$file} = \@new_locks;
                   7282:             } else {
                   7283:                 push(@del_keys, $file);
1.613     albertel 7284:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 7285:                 delete($current_permissions{$file});
1.563     banghart 7286:             }
                   7287:         }
1.561     banghart 7288:     }
1.613     albertel 7289:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7290:     return;
                   7291: }
1.512     banghart 7292: 
1.17      www      7293: # ------------------------------------------------------------ Directory lister
                   7294: 
                   7295: sub dirlist {
1.955     raeburn  7296:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      7297:     $uri=~s/^\///;
                   7298:     $uri=~s/\/$//;
1.253     stredwic 7299:     my ($udom, $uname);
1.955     raeburn  7300:     if ($getuserdir) {
1.253     stredwic 7301:         $udom = $userdomain;
                   7302:         $uname = $username;
1.955     raeburn  7303:     } else {
                   7304:         (undef,$udom,$uname)=split(/\//,$uri);
                   7305:         if(defined($userdomain)) {
                   7306:             $udom = $userdomain;
                   7307:         }
                   7308:         if(defined($username)) {
                   7309:             $uname = $username;
                   7310:         }
1.253     stredwic 7311:     }
1.955     raeburn  7312:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 7313: 
1.955     raeburn  7314:     $dirRoot = $perlvar{'lonDocRoot'};
                   7315:     if (defined($getpropath)) {
                   7316:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 7317:         $dirRoot =~ s/\/$//;
1.955     raeburn  7318:     } elsif (defined($getuserdir)) {
                   7319:         my $subdir=$uname.'__';
                   7320:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   7321:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   7322:                    ."/$udom/$subdir/$uname";
                   7323:     } elsif (defined($alternateRoot)) {
                   7324:         $dirRoot = $alternateRoot;
1.751     banghart 7325:     }
1.253     stredwic 7326: 
                   7327:     if($udom) {
                   7328:         if($uname) {
1.955     raeburn  7329:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  7330:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  7331:                               .':'.&escape($uname).':'.&escape($udom),
                   7332:                               &homeserver($uname,$udom));
                   7333:             if ($listing eq 'unknown_cmd') {
                   7334:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   7335:                                   &homeserver($uname,$udom));
                   7336:             } else {
                   7337:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7338:             }
1.605     matthew  7339:             if ($listing eq 'unknown_cmd') {
1.800     albertel 7340:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   7341: 				  &homeserver($uname,$udom));
1.605     matthew  7342:                 @listing_results = split(/:/,$listing);
                   7343:             } else {
                   7344:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7345:             }
                   7346:             return @listing_results;
1.955     raeburn  7347:         } elsif(!$alternateRoot) {
1.800     albertel 7348:             my %allusers;
1.841     albertel 7349: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  7350:  	    foreach my $tryserver (keys(%servers)) {
                   7351:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   7352:                                   &escape($udom),$tryserver);
                   7353:                 if ($listing eq 'unknown_cmd') {
                   7354: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7355: 				      $udom, $tryserver);
                   7356:                 } else {
                   7357:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   7358:                 }
1.841     albertel 7359: 		if ($listing eq 'unknown_cmd') {
                   7360: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   7361: 				      $udom, $tryserver);
                   7362: 		    @listing_results = split(/:/,$listing);
                   7363: 		} else {
                   7364: 		    @listing_results =
                   7365: 			map { &unescape($_); } split(/:/,$listing);
                   7366: 		}
                   7367: 		if ($listing_results[0] ne 'no_such_dir' && 
                   7368: 		    $listing_results[0] ne 'empty'       &&
                   7369: 		    $listing_results[0] ne 'con_lost') {
                   7370: 		    foreach my $line (@listing_results) {
                   7371: 			my ($entry) = split(/&/,$line,2);
                   7372: 			$allusers{$entry} = 1;
                   7373: 		    }
                   7374: 		}
1.253     stredwic 7375:             }
                   7376:             my $alluserstr='';
1.800     albertel 7377:             foreach my $user (sort(keys(%allusers))) {
                   7378:                 $alluserstr.=$user.'&user:';
1.253     stredwic 7379:             }
                   7380:             $alluserstr=~s/:$//;
                   7381:             return split(/:/,$alluserstr);
                   7382:         } else {
1.800     albertel 7383:             return ('missing user name');
1.253     stredwic 7384:         }
1.955     raeburn  7385:     } elsif(!defined($getpropath)) {
1.841     albertel 7386:         my @all_domains = sort(&all_domains());
1.955     raeburn  7387:         foreach my $domain (@all_domains) {
                   7388:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   7389:         }
                   7390:         return @all_domains;
                   7391:     } else {
1.800     albertel 7392:         return ('missing domain');
1.275     stredwic 7393:     }
                   7394: }
                   7395: 
                   7396: # --------------------------------------------- GetFileTimestamp
                   7397: # This function utilizes dirlist and returns the date stamp for
                   7398: # when it was last modified.  It will also return an error of -1
                   7399: # if an error occurs
                   7400: 
                   7401: sub GetFileTimestamp {
1.955     raeburn  7402:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 7403:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   7404:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  7405:     my ($fileStat) = 
                   7406:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   7407:                                  undef,$getuserdir);
1.275     stredwic 7408:     my @stats = split('&', $fileStat);
                   7409:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  7410:         # @stats contains first the filename, then the stat output
                   7411:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 7412:     } else {
                   7413:         return -1;
1.253     stredwic 7414:     }
1.26      www      7415: }
                   7416: 
1.712     albertel 7417: sub stat_file {
                   7418:     my ($uri) = @_;
1.787     albertel 7419:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 7420: 
1.955     raeburn  7421:     my ($udom,$uname,$file);
1.712     albertel 7422:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   7423: 	($udom,$uname,$file) =
1.811     albertel 7424: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 7425: 	$file = 'userfiles/'.$file;
                   7426:     }
                   7427:     if ($uri =~ m-^/res/-) {
                   7428: 	($udom,$uname) = 
1.807     albertel 7429: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 7430: 	$file = $uri;
                   7431:     }
                   7432: 
                   7433:     if (!$udom || !$uname || !$file) {
                   7434: 	# unable to handle the uri
                   7435: 	return ();
                   7436:     }
1.956     raeburn  7437:     my $getpropath;
                   7438:     if ($file =~ /^userfiles\//) {
                   7439:         $getpropath = 1;
                   7440:     }
1.955     raeburn  7441:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 7442:     my @stats = split('&', $result);
1.721     banghart 7443:     
1.712     albertel 7444:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   7445: 	shift(@stats); #filename is first
                   7446: 	return @stats;
                   7447:     }
                   7448:     return ();
                   7449: }
                   7450: 
1.26      www      7451: # -------------------------------------------------------- Value of a Condition
                   7452: 
1.713     albertel 7453: # gets the value of a specific preevaluated condition
                   7454: #    stored in the string  $env{user.state.<cid>}
                   7455: # or looks up a condition reference in the bighash and if if hasn't
                   7456: # already been evaluated recurses into docondval to get the value of
                   7457: # the condition, then memoizing it to 
                   7458: #   $env{user.state.<cid>.<condition>}
1.40      www      7459: sub directcondval {
                   7460:     my $number=shift;
1.620     albertel 7461:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 7462: 	&Apache::lonuserstate::evalstate();
                   7463:     }
1.713     albertel 7464:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   7465: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   7466:     } elsif ($number =~ /^_/) {
                   7467: 	my $sub_condition;
                   7468: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7469: 		&GDBM_READER(),0640)) {
                   7470: 	    $sub_condition=$bighash{'conditions'.$number};
                   7471: 	    untie(%bighash);
                   7472: 	}
                   7473: 	my $value = &docondval($sub_condition);
1.949     raeburn  7474: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 7475: 	return $value;
                   7476:     }
1.620     albertel 7477:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   7478:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      7479:     } else {
                   7480:        return 2;
                   7481:     }
                   7482: }
                   7483: 
1.713     albertel 7484: # get the collection of conditions for this resource
1.26      www      7485: sub condval {
                   7486:     my $condidx=shift;
1.54      www      7487:     my $allpathcond='';
1.713     albertel 7488:     foreach my $cond (split(/\|/,$condidx)) {
                   7489: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   7490: 	    $allpathcond.=
                   7491: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   7492: 	}
1.191     harris41 7493:     }
1.54      www      7494:     $allpathcond=~s/\|$//;
1.713     albertel 7495:     return &docondval($allpathcond);
                   7496: }
                   7497: 
                   7498: #evaluates an expression of conditions
                   7499: sub docondval {
                   7500:     my ($allpathcond) = @_;
                   7501:     my $result=0;
                   7502:     if ($env{'request.course.id'}
                   7503: 	&& defined($allpathcond)) {
                   7504: 	my $operand='|';
                   7505: 	my @stack;
                   7506: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   7507: 	    if ($chunk eq '(') {
                   7508: 		push @stack,($operand,$result);
                   7509: 	    } elsif ($chunk eq ')') {
                   7510: 		my $before=pop @stack;
                   7511: 		if (pop @stack eq '&') {
                   7512: 		    $result=$result>$before?$before:$result;
                   7513: 		} else {
                   7514: 		    $result=$result>$before?$result:$before;
                   7515: 		}
                   7516: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   7517: 		$operand=$chunk;
                   7518: 	    } else {
                   7519: 		my $new=directcondval($chunk);
                   7520: 		if ($operand eq '&') {
                   7521: 		    $result=$result>$new?$new:$result;
                   7522: 		} else {
                   7523: 		    $result=$result>$new?$result:$new;
                   7524: 		}
                   7525: 	    }
                   7526: 	}
1.26      www      7527:     }
                   7528:     return $result;
1.421     albertel 7529: }
                   7530: 
                   7531: # ---------------------------------------------------- Devalidate courseresdata
                   7532: 
                   7533: sub devalidatecourseresdata {
                   7534:     my ($coursenum,$coursedomain)=@_;
                   7535:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7536:     &devalidate_cache_new('courseres',$hashid);
1.28      www      7537: }
                   7538: 
1.763     www      7539: 
1.200     www      7540: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     7541: #
                   7542: #  Parameters:
                   7543: #      $coursenum    - Number of the course.
                   7544: #      $coursedomain - Domain at which the course was created.
                   7545: #  Returns:
                   7546: #     A hash of the course parameters along (I think) with timestamps
                   7547: #     and version info.
1.877     foxr     7548: 
1.624     albertel 7549: sub get_courseresdata {
                   7550:     my ($coursenum,$coursedomain)=@_;
1.200     www      7551:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   7552:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 7553:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 7554:     my %dumpreply;
1.417     albertel 7555:     unless (defined($cached)) {
1.624     albertel 7556: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 7557: 	$result=\%dumpreply;
1.251     albertel 7558: 	my ($tmp) = keys(%dumpreply);
                   7559: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 7560: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 7561: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   7562: 	    return $tmp;
1.416     albertel 7563: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 7564: 	    $result=undef;
1.599     albertel 7565: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 7566: 	}
                   7567:     }
1.624     albertel 7568:     return $result;
                   7569: }
                   7570: 
1.633     albertel 7571: sub devalidateuserresdata {
                   7572:     my ($uname,$udom)=@_;
                   7573:     my $hashid="$udom:$uname";
                   7574:     &devalidate_cache_new('userres',$hashid);
                   7575: }
                   7576: 
1.624     albertel 7577: sub get_userresdata {
                   7578:     my ($uname,$udom)=@_;
                   7579:     #most student don\'t have any data set, check if there is some data
                   7580:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   7581: 
                   7582:     my $hashid="$udom:$uname";
                   7583:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   7584:     if (!defined($cached)) {
                   7585: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   7586: 	$result=\%resourcedata;
                   7587: 	&do_cache_new('userres',$hashid,$result,600);
                   7588:     }
                   7589:     my ($tmp)=keys(%$result);
                   7590:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   7591: 	return $result;
                   7592:     }
                   7593:     #error 2 occurs when the .db doesn't exist
                   7594:     if ($tmp!~/error: 2 /) {
1.672     albertel 7595: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 7596: 		 " Trying to get resource data for ".
                   7597: 		 $uname." at ".$udom.": ".
                   7598: 		 $tmp."</font>");
                   7599:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 7600: 	#&EXT_cache_set($udom,$uname);
                   7601: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 7602: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 7603:     }
                   7604:     return $tmp;
                   7605: }
1.879     foxr     7606: #----------------------------------------------- resdata - return resource data
                   7607: #  Purpose:
                   7608: #    Return resource data for either users or for a course.
                   7609: #  Parameters:
                   7610: #     $name      - Course/user name.
                   7611: #     $domain    - Name of the domain the user/course is registered on.
                   7612: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   7613: #     @which     - Array of names of resources desired.
                   7614: #  Returns:
                   7615: #     The value of the first reasource in @which that is found in the
                   7616: #     resource hash.
                   7617: #  Exceptional Conditions:
                   7618: #     If the $type passed in is not valid (not the string 'course' or 
                   7619: #     'user', an undefined  reference is returned.
                   7620: #     If none of the resources are found, an undef is returned
1.624     albertel 7621: sub resdata {
                   7622:     my ($name,$domain,$type,@which)=@_;
                   7623:     my $result;
                   7624:     if ($type eq 'course') {
                   7625: 	$result=&get_courseresdata($name,$domain);
                   7626:     } elsif ($type eq 'user') {
                   7627: 	$result=&get_userresdata($name,$domain);
                   7628:     }
                   7629:     if (!ref($result)) { return $result; }    
1.251     albertel 7630:     foreach my $item (@which) {
1.927     albertel 7631: 	if (defined($result->{$item->[0]})) {
                   7632: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 7633: 	}
1.250     albertel 7634:     }
1.291     albertel 7635:     return undef;
1.200     www      7636: }
                   7637: 
1.379     matthew  7638: #
                   7639: # EXT resource caching routines
                   7640: #
                   7641: 
                   7642: sub clear_EXT_cache_status {
1.383     albertel 7643:     &delenv('cache.EXT.');
1.379     matthew  7644: }
                   7645: 
                   7646: sub EXT_cache_status {
                   7647:     my ($target_domain,$target_user) = @_;
1.383     albertel 7648:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 7649:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  7650:         # We know already the user has no data
                   7651:         return 1;
                   7652:     } else {
                   7653:         return 0;
                   7654:     }
                   7655: }
                   7656: 
                   7657: sub EXT_cache_set {
                   7658:     my ($target_domain,$target_user) = @_;
1.383     albertel 7659:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  7660:     #&appenv({$cachename => time});
1.379     matthew  7661: }
                   7662: 
1.28      www      7663: # --------------------------------------------------------- Value of a Variable
1.58      www      7664: sub EXT {
1.715     albertel 7665: 
1.395     albertel 7666:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      7667:     unless ($varname) { return ''; }
1.218     albertel 7668:     #get real user name/domain, courseid and symb
                   7669:     my $courseid;
1.359     albertel 7670:     my $publicuser;
1.427     www      7671:     if ($symbparm) {
                   7672: 	$symbparm=&get_symb_from_alias($symbparm);
                   7673:     }
1.218     albertel 7674:     if (!($uname && $udom)) {
1.790     albertel 7675:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 7676:       if (!$symbparm) {	$symbparm=$cursymb; }
                   7677:     } else {
1.620     albertel 7678: 	$courseid=$env{'request.course.id'};
1.218     albertel 7679:     }
1.48      www      7680:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   7681:     my $rest;
1.320     albertel 7682:     if (defined($therest[0])) {
1.48      www      7683:        $rest=join('.',@therest);
                   7684:     } else {
                   7685:        $rest='';
                   7686:     }
1.320     albertel 7687: 
1.57      www      7688:     my $qualifierrest=$qualifier;
                   7689:     if ($rest) { $qualifierrest.='.'.$rest; }
                   7690:     my $spacequalifierrest=$space;
                   7691:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      7692:     if ($realm eq 'user') {
1.48      www      7693: # --------------------------------------------------------------- user.resource
                   7694: 	if ($space eq 'resource') {
1.651     albertel 7695: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   7696: 		  || defined($Apache::lonhomework::parsing_a_task))
                   7697: 		 &&
1.744     albertel 7698: 		 ($symbparm eq &symbread()) ) {	
                   7699: 		# if we are in the middle of processing the resource the
                   7700: 		# get the value we are planning on committing
                   7701:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   7702:                     return $Apache::lonhomework::results{$qualifierrest};
                   7703:                 } else {
                   7704:                     return $Apache::lonhomework::history{$qualifierrest};
                   7705:                 }
1.335     albertel 7706: 	    } else {
1.359     albertel 7707: 		my %restored;
1.620     albertel 7708: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 7709: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   7710: 		} else {
                   7711: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   7712: 		}
1.335     albertel 7713: 		return $restored{$qualifierrest};
                   7714: 	    }
1.48      www      7715: # ----------------------------------------------------------------- user.access
                   7716:         } elsif ($space eq 'access') {
1.218     albertel 7717: 	    # FIXME - not supporting calls for a specific user
1.48      www      7718:             return &allowed($qualifier,$rest);
                   7719: # ------------------------------------------ user.preferences, user.environment
                   7720:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 7721: 	    if (($uname eq $env{'user.name'}) &&
                   7722: 		($udom eq $env{'user.domain'})) {
                   7723: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 7724: 	    } else {
1.359     albertel 7725: 		my %returnhash;
                   7726: 		if (!$publicuser) {
                   7727: 		    %returnhash=&userenvironment($udom,$uname,
                   7728: 						 $qualifierrest);
                   7729: 		}
1.218     albertel 7730: 		return $returnhash{$qualifierrest};
                   7731: 	    }
1.48      www      7732: # ----------------------------------------------------------------- user.course
                   7733:         } elsif ($space eq 'course') {
1.218     albertel 7734: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7735:             return $env{join('.',('request.course',$qualifier))};
1.48      www      7736: # ------------------------------------------------------------------- user.role
                   7737:         } elsif ($space eq 'role') {
1.218     albertel 7738: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 7739:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7740:             if ($qualifier eq 'value') {
                   7741: 		return $role;
                   7742:             } elsif ($qualifier eq 'extent') {
                   7743:                 return $where;
                   7744:             }
                   7745: # ----------------------------------------------------------------- user.domain
                   7746:         } elsif ($space eq 'domain') {
1.218     albertel 7747:             return $udom;
1.48      www      7748: # ------------------------------------------------------------------- user.name
                   7749:         } elsif ($space eq 'name') {
1.218     albertel 7750:             return $uname;
1.48      www      7751: # ---------------------------------------------------- Any other user namespace
1.29      www      7752:         } else {
1.359     albertel 7753: 	    my %reply;
                   7754: 	    if (!$publicuser) {
                   7755: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7756: 	    }
                   7757: 	    return $reply{$qualifierrest};
1.48      www      7758:         }
1.236     www      7759:     } elsif ($realm eq 'query') {
                   7760: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7761:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7762: 						[$spacequalifierrest]);
1.620     albertel 7763: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7764:    } elsif ($realm eq 'request') {
1.48      www      7765: # ------------------------------------------------------------- request.browser
                   7766:         if ($space eq 'browser') {
1.430     www      7767: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7768: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7769: 		    return 1;
                   7770: 		} else {
                   7771: 		    return 0;
                   7772: 		}
                   7773: 	    } else {
1.620     albertel 7774: 		return $env{'browser.'.$qualifier};
1.430     www      7775: 	    }
1.57      www      7776: # ------------------------------------------------------------ request.filename
                   7777:         } else {
1.620     albertel 7778:             return $env{'request.'.$spacequalifierrest};
1.29      www      7779:         }
1.28      www      7780:     } elsif ($realm eq 'course') {
1.48      www      7781: # ---------------------------------------------------------- course.description
1.620     albertel 7782:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7783:     } elsif ($realm eq 'resource') {
1.165     www      7784: 
1.620     albertel 7785: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7786: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7787: 	}
1.693     albertel 7788: 
                   7789: 	if ($space eq 'title') {
                   7790: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7791: 	    return &gettitle($symbparm);
                   7792: 	}
                   7793: 	
                   7794: 	if ($space eq 'map') {
                   7795: 	    my ($map) = &decode_symb($symbparm);
                   7796: 	    return &symbread($map);
                   7797: 	}
1.905     albertel 7798: 	if ($space eq 'filename') {
                   7799: 	    if ($symbparm) {
                   7800: 		return &clutter((&decode_symb($symbparm))[2]);
                   7801: 	    }
                   7802: 	    return &hreflocation('',$env{'request.filename'});
                   7803: 	}
1.693     albertel 7804: 
                   7805: 	my ($section, $group, @groups);
1.593     albertel 7806: 	my ($courselevelm,$courselevel);
1.539     albertel 7807: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7808: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7809: 
1.218     albertel 7810: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7811: 
1.60      www      7812: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7813: 	    my $symbp=$symbparm;
1.735     albertel 7814: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7815: 
                   7816: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7817: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7818: 
1.620     albertel 7819: 	    if (($env{'user.name'} eq $uname) &&
                   7820: 		($env{'user.domain'} eq $udom)) {
                   7821: 		$section=$env{'request.course.sec'};
1.733     raeburn  7822:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7823:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7824: 	    } else {
1.539     albertel 7825: 		if (! defined($usection)) {
1.551     albertel 7826: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7827: 		} else {
                   7828: 		    $section = $usection;
                   7829: 		}
1.733     raeburn  7830:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7831: 	    }
                   7832: 
                   7833: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7834: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7835: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7836: 
1.593     albertel 7837: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7838: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7839: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7840: 
1.60      www      7841: # ----------------------------------------------------------- first, check user
1.624     albertel 7842: 
                   7843: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7844: 				       ([$courselevelr,'resource'],
                   7845: 					[$courselevelm,'map'     ],
                   7846: 					[$courselevel, 'course'  ]));
1.931     albertel 7847: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7848: 
1.594     albertel 7849: # ------------------------------------------------ second, check some of course
1.684     raeburn  7850:             my $coursereply;
1.691     raeburn  7851:             if (@groups > 0) {
                   7852:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7853:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7854:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7855:             }
1.96      www      7856: 
1.684     raeburn  7857: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7858: 				  $env{'course.'.$courseid.'.domain'},
                   7859: 				  'course',
                   7860: 				  ([$seclevelr,   'resource'],
                   7861: 				   [$seclevelm,   'map'     ],
                   7862: 				   [$seclevel,    'course'  ],
                   7863: 				   [$courselevelr,'resource']));
                   7864: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7865: 
1.60      www      7866: # ------------------------------------------------------ third, check map parms
1.218     albertel 7867: 	    my %parmhash=();
                   7868: 	    my $thisparm='';
                   7869: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7870: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7871: 		    &GDBM_READER(),0640)) {
1.218     albertel 7872: 		$thisparm=$parmhash{$symbparm};
                   7873: 		untie(%parmhash);
                   7874: 	    }
1.927     albertel 7875: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7876: 	}
1.594     albertel 7877: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7878: 
1.218     albertel 7879: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7880: 	my $filename;
                   7881: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7882: 	if ($symbparm) {
1.409     www      7883: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7884: 	} else {
1.620     albertel 7885: 	    $filename=$env{'request.filename'};
1.282     albertel 7886: 	}
                   7887: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7888: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7889: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7890: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7891: 
1.927     albertel 7892: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7893: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7894: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7895: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7896: 				     $env{'course.'.$courseid.'.domain'},
                   7897: 				     'course',
1.927     albertel 7898: 				     ([$courselevelm,'map'   ],
                   7899: 				      [$courselevel, 'course']));
                   7900: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7901: 	}
1.145     www      7902: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7903: 	unless ($space eq '0') {
1.336     albertel 7904: 	    my @parts=split(/_/,$space);
                   7905: 	    my $id=pop(@parts);
                   7906: 	    my $part=join('_',@parts);
                   7907: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7908: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7909: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7910: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7911: 	}
1.395     albertel 7912: 	if ($recurse) { return undef; }
                   7913: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7914: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7915: # ---------------------------------------------------- Any other user namespace
                   7916:     } elsif ($realm eq 'environment') {
                   7917: # ----------------------------------------------------------------- environment
1.620     albertel 7918: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7919: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7920: 	} else {
1.770     albertel 7921: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7922: 		return '';
                   7923: 	    }
1.219     albertel 7924: 	    my %returnhash=&userenvironment($udom,$uname,
                   7925: 					    $spacequalifierrest);
                   7926: 	    return $returnhash{$spacequalifierrest};
                   7927: 	}
1.28      www      7928:     } elsif ($realm eq 'system') {
1.48      www      7929: # ----------------------------------------------------------------- system.time
                   7930: 	if ($space eq 'time') {
                   7931: 	    return time;
                   7932:         }
1.696     albertel 7933:     } elsif ($realm eq 'server') {
                   7934: # ----------------------------------------------------------------- system.time
                   7935: 	if ($space eq 'name') {
                   7936: 	    return $ENV{'SERVER_NAME'};
                   7937:         }
1.28      www      7938:     }
1.48      www      7939:     return '';
1.61      www      7940: }
                   7941: 
1.927     albertel 7942: sub get_reply {
                   7943:     my ($reply_value) = @_;
1.940     raeburn  7944:     if (ref($reply_value) eq 'ARRAY') {
                   7945:         if (wantarray) {
                   7946: 	    return @$reply_value;
                   7947:         }
                   7948:         return $reply_value->[0];
                   7949:     } else {
                   7950:         return $reply_value;
1.927     albertel 7951:     }
                   7952: }
                   7953: 
1.691     raeburn  7954: sub check_group_parms {
                   7955:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7956:     my @groupitems = ();
                   7957:     my $resultitem;
1.927     albertel 7958:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7959:     foreach my $group (@{$groups}) {
                   7960:         foreach my $level (@levels) {
1.927     albertel 7961:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7962:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7963:         }
                   7964:     }
                   7965:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7966:                             $env{'course.'.$courseid.'.domain'},
                   7967:                                      'course',@groupitems);
                   7968:     return $coursereply;
                   7969: }
                   7970: 
                   7971: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7972:     my ($courseid,@groups) = @_;
                   7973:     @groups = sort(@groups);
1.691     raeburn  7974:     return @groups;
                   7975: }
                   7976: 
1.395     albertel 7977: sub packages_tab_default {
                   7978:     my ($uri,$varname)=@_;
                   7979:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7980: 
                   7981:     my (@extension,@specifics,$do_default);
                   7982:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7983: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7984: 	if ($pack_type eq 'default') {
                   7985: 	    $do_default=1;
                   7986: 	} elsif ($pack_type eq 'extension') {
                   7987: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7988: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7989: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7990: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7991: 	}
                   7992:     }
                   7993:     # first look for a package that matches the requested part id
                   7994:     foreach my $package (@specifics) {
                   7995: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7996: 	next if ($pack_part ne $part);
                   7997: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7998: 	    return $packagetab{"$pack_type&$name&default"};
                   7999: 	}
                   8000:     }
                   8001:     # look for any possible matching non extension_ package
                   8002:     foreach my $package (@specifics) {
                   8003: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8004: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8005: 	    return $packagetab{"$pack_type&$name&default"};
                   8006: 	}
1.585     albertel 8007: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8008: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8009: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8010: 	}
                   8011:     }
1.738     albertel 8012:     # look for any posible extension_ match
                   8013:     foreach my $package (@extension) {
                   8014: 	my ($package,$pack_type)=@{$package};
                   8015: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8016: 	    return $packagetab{"$pack_type&$name&default"};
                   8017: 	}
                   8018: 	if (defined($packagetab{$package."&$name&default"})) {
                   8019: 	    return $packagetab{$package."&$name&default"};
                   8020: 	}
                   8021:     }
                   8022:     # look for a global default setting
                   8023:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8024: 	return $packagetab{"default&$name&default"};
                   8025:     }
1.395     albertel 8026:     return undef;
                   8027: }
                   8028: 
1.334     albertel 8029: sub add_prefix_and_part {
                   8030:     my ($prefix,$part)=@_;
                   8031:     my $keyroot;
                   8032:     if (defined($prefix) && $prefix !~ /^__/) {
                   8033: 	# prefix that has a part already
                   8034: 	$keyroot=$prefix;
                   8035:     } elsif (defined($prefix)) {
                   8036: 	# prefix that is missing a part
                   8037: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8038:     } else {
                   8039: 	# no prefix at all
                   8040: 	if (defined($part)) { $keyroot='_'.$part; }
                   8041:     }
                   8042:     return $keyroot;
                   8043: }
                   8044: 
1.71      www      8045: # ---------------------------------------------------------------- Get metadata
                   8046: 
1.599     albertel 8047: my %metaentry;
1.71      www      8048: sub metadata {
1.176     www      8049:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8050:     $uri=&declutter($uri);
1.288     albertel 8051:     # if it is a non metadata possible uri return quickly
1.529     albertel 8052:     if (($uri eq '') || 
                   8053: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8054: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 8055:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   8056: 	return undef;
                   8057:     }
                   8058:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8059: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8060: 	return undef;
1.288     albertel 8061:     }
1.73      www      8062:     my $filename=$uri;
                   8063:     $uri=~s/\.meta$//;
1.172     www      8064: #
                   8065: # Is the metadata already cached?
1.177     www      8066: # Look at timestamp of caching
1.172     www      8067: # Everything is cached by the main uri, libraries are never directly cached
                   8068: #
1.428     albertel 8069:     if (!defined($liburi)) {
1.599     albertel 8070: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8071: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8072:     }
                   8073:     {
1.172     www      8074: #
                   8075: # Is this a recursive call for a library?
                   8076: #
1.599     albertel 8077: #	if (! exists($metacache{$uri})) {
                   8078: #	    $metacache{$uri}={};
                   8079: #	}
1.924     albertel 8080: 	my $cachetime = 60*60;
1.171     www      8081:         if ($liburi) {
                   8082: 	    $liburi=&declutter($liburi);
                   8083:             $filename=$liburi;
1.401     bowersj2 8084:         } else {
1.599     albertel 8085: 	    &devalidate_cache_new('meta',$uri);
                   8086: 	    undef(%metaentry);
1.401     bowersj2 8087: 	}
1.140     www      8088:         my %metathesekeys=();
1.73      www      8089:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8090: 	my $metastring;
1.924     albertel 8091: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 8092: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 8093: 	    $metastring = 
1.929     albertel 8094: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 8095: 					  ('grade_target' => 'meta'));
                   8096: 	    $cachetime = 1; # only want this cached in the child not long term
                   8097: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 8098: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 8099: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 8100: 	    $metastring=&getfile($file);
1.489     albertel 8101: 	}
1.208     albertel 8102:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      8103:         my $token;
1.140     www      8104:         undef %metathesekeys;
1.71      www      8105:         while ($token=$parser->get_token) {
1.339     albertel 8106: 	    if ($token->[0] eq 'S') {
                   8107: 		if (defined($token->[2]->{'package'})) {
1.172     www      8108: #
                   8109: # This is a package - get package info
                   8110: #
1.339     albertel 8111: 		    my $package=$token->[2]->{'package'};
                   8112: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8113: 		    if (defined($token->[2]->{'id'})) { 
                   8114: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   8115: 		    }
1.599     albertel 8116: 		    if ($metaentry{':packages'}) {
                   8117: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 8118: 		    } else {
1.599     albertel 8119: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 8120: 		    }
1.736     albertel 8121: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 8122: 			my $part=$keyroot;
                   8123: 			$part=~s/^\_//;
1.736     albertel 8124: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   8125: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   8126: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 8127: 			    # ignore package.tab specified default values
                   8128:                             # here &package_tab_default() will fetch those
                   8129: 			    if ($subp eq 'default') { next; }
1.736     albertel 8130: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 8131: 			    my $unikey;
                   8132: 			    if ($pack =~ /_0$/) {
                   8133: 				$unikey='parameter_0_'.$name;
                   8134: 				$part=0;
                   8135: 			    } else {
                   8136: 				$unikey='parameter'.$keyroot.'_'.$name;
                   8137: 			    }
1.339     albertel 8138: 			    if ($subp eq 'display') {
                   8139: 				$value.=' [Part: '.$part.']';
                   8140: 			    }
1.599     albertel 8141: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 8142: 			    $metathesekeys{$unikey}=1;
1.599     albertel 8143: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8144: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 8145: 			    }
1.599     albertel 8146: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   8147: 				$metaentry{':'.$unikey}=
                   8148: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 8149: 			    }
1.339     albertel 8150: 			}
                   8151: 		    }
                   8152: 		} else {
1.172     www      8153: #
                   8154: # This is not a package - some other kind of start tag
1.339     albertel 8155: #
                   8156: 		    my $entry=$token->[1];
                   8157: 		    my $unikey;
                   8158: 		    if ($entry eq 'import') {
                   8159: 			$unikey='';
                   8160: 		    } else {
                   8161: 			$unikey=$entry;
                   8162: 		    }
                   8163: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   8164: 
                   8165: 		    if (defined($token->[2]->{'id'})) { 
                   8166: 			$unikey.='_'.$token->[2]->{'id'}; 
                   8167: 		    }
1.175     www      8168: 
1.339     albertel 8169: 		    if ($entry eq 'import') {
1.175     www      8170: #
                   8171: # Importing a library here
1.339     albertel 8172: #
                   8173: 			if ($depthcount<20) {
                   8174: 			    my $location=$parser->get_text('/import');
                   8175: 			    my $dir=$filename;
                   8176: 			    $dir=~s|[^/]*$||;
                   8177: 			    $location=&filelocation($dir,$location);
1.736     albertel 8178: 			    my $metadata = 
                   8179: 				&metadata($uri,'keys', $location,$unikey,
                   8180: 					  $depthcount+1);
                   8181: 			    foreach my $meta (split(',',$metadata)) {
                   8182: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   8183: 				$metathesekeys{$meta}=1;
1.339     albertel 8184: 			    }
                   8185: 			}
                   8186: 		    } else { 
                   8187: 			
                   8188: 			if (defined($token->[2]->{'name'})) { 
                   8189: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   8190: 			}
                   8191: 			$metathesekeys{$unikey}=1;
1.736     albertel 8192: 			foreach my $param (@{$token->[3]}) {
                   8193: 			    $metaentry{':'.$unikey.'.'.$param} =
                   8194: 				$token->[2]->{$param};
1.339     albertel 8195: 			}
                   8196: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 8197: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 8198: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   8199: 		 # only ws inside the tag, and not in default, so use default
                   8200: 		 # as value
1.599     albertel 8201: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 8202: 			} elsif ( $internaltext =~ /\S/ ) {
                   8203: 		  # something interesting inside the tag
                   8204: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 8205: 			} else {
1.908     albertel 8206: 		  # no interesting values, don't set a default
1.339     albertel 8207: 			}
1.172     www      8208: # end of not-a-package not-a-library import
1.339     albertel 8209: 		    }
1.172     www      8210: # end of not-a-package start tag
1.339     albertel 8211: 		}
1.172     www      8212: # the next is the end of "start tag"
1.339     albertel 8213: 	    }
                   8214: 	}
1.483     albertel 8215: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 8216: 	$extension = lc($extension);
                   8217: 	if ($extension eq 'htm') { $extension='html'; }
                   8218: 
1.737     albertel 8219: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 8220: 	    #no specific packages #how's our extension
                   8221: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 8222: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 8223: 					 \%metathesekeys);
                   8224: 	}
1.883     albertel 8225: 
                   8226: 	if (!exists($metaentry{':packages'})
                   8227: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 8228: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 8229: 		#no specific packages well let's get default then
                   8230: 		if ($key!~/^default&/) { next; }
1.488     albertel 8231: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 8232: 					     \%metathesekeys);
                   8233: 	    }
                   8234: 	}
1.338     www      8235: # are there custom rights to evaluate
1.599     albertel 8236: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 8237: 
1.338     www      8238:     #
                   8239:     # Importing a rights file here
1.339     albertel 8240:     #
                   8241: 	    unless ($depthcount) {
1.599     albertel 8242: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 8243: 		my $dir=$filename;
                   8244: 		$dir=~s|[^/]*$||;
                   8245: 		$location=&filelocation($dir,$location);
1.736     albertel 8246: 		my $rights_metadata =
                   8247: 		    &metadata($uri,'keys',$location,'_rights',
                   8248: 			      $depthcount+1);
                   8249: 		foreach my $rights (split(',',$rights_metadata)) {
                   8250: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   8251: 		    $metathesekeys{$rights}=1;
1.339     albertel 8252: 		}
                   8253: 	    }
                   8254: 	}
1.737     albertel 8255: 	# uniqifiy package listing
                   8256: 	my %seen;
                   8257: 	my @uniq_packages =
                   8258: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   8259: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   8260: 
                   8261: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 8262: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   8263: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 8264: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      8265: # this is the end of "was not already recently cached
1.71      www      8266:     }
1.599     albertel 8267:     return $metaentry{':'.$what};
1.261     albertel 8268: }
                   8269: 
1.488     albertel 8270: sub metadata_create_package_def {
1.483     albertel 8271:     my ($uri,$key,$package,$metathesekeys)=@_;
                   8272:     my ($pack,$name,$subp)=split(/\&/,$key);
                   8273:     if ($subp eq 'default') { next; }
                   8274:     
1.599     albertel 8275:     if (defined($metaentry{':packages'})) {
                   8276: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 8277:     } else {
1.599     albertel 8278: 	$metaentry{':packages'}=$package;
1.483     albertel 8279:     }
                   8280:     my $value=$packagetab{$key};
                   8281:     my $unikey;
                   8282:     $unikey='parameter_0_'.$name;
1.599     albertel 8283:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 8284:     $$metathesekeys{$unikey}=1;
1.599     albertel 8285:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   8286: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 8287:     }
1.599     albertel 8288:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   8289: 	$metaentry{':'.$unikey}=
                   8290: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 8291:     }
                   8292: }
                   8293: 
1.261     albertel 8294: sub metadata_generate_part0 {
                   8295:     my ($metadata,$metacache,$uri) = @_;
                   8296:     my %allnames;
1.737     albertel 8297:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 8298: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 8299: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   8300: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 8301: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 8302: 	    $allnames{$name}=$part;
                   8303: 	  }
                   8304: 	}
                   8305:     }
                   8306:     foreach my $name (keys(%allnames)) {
                   8307:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 8308:       my $key=":parameter_0_$name";
1.261     albertel 8309:       $$metacache{"$key.part"}='0';
                   8310:       $$metacache{"$key.name"}=$name;
1.428     albertel 8311:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 8312: 					   $allnames{$name}.'_'.$name.
                   8313: 					   '.type'};
1.428     albertel 8314:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 8315: 			     '.display'};
1.644     www      8316:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 8317:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 8318:       $$metacache{"$key.display"}=$olddis;
                   8319:     }
1.71      www      8320: }
                   8321: 
1.764     albertel 8322: # ------------------------------------------------------ Devalidate title cache
                   8323: 
                   8324: sub devalidate_title_cache {
                   8325:     my ($url)=@_;
                   8326:     if (!$env{'request.course.id'}) { return; }
                   8327:     my $symb=&symbread($url);
                   8328:     if (!$symb) { return; }
                   8329:     my $key=$env{'request.course.id'}."\0".$symb;
                   8330:     &devalidate_cache_new('title',$key);
                   8331: }
                   8332: 
1.1014    droeschl 8333: # ------------------------------------------------- Get the title of a course
                   8334: 
                   8335: sub current_course_title {
                   8336:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   8337: }
1.301     www      8338: # ------------------------------------------------- Get the title of a resource
                   8339: 
                   8340: sub gettitle {
                   8341:     my $urlsymb=shift;
                   8342:     my $symb=&symbread($urlsymb);
1.534     albertel 8343:     if ($symb) {
1.620     albertel 8344: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 8345: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 8346: 	if (defined($cached)) { 
                   8347: 	    return $result;
                   8348: 	}
1.534     albertel 8349: 	my ($map,$resid,$url)=&decode_symb($symb);
                   8350: 	my $title='';
1.907     albertel 8351: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   8352: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   8353: 	} else {
                   8354: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8355: 		    &GDBM_READER(),0640)) {
                   8356: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   8357: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   8358: 		untie(%bighash);
                   8359: 	    }
1.534     albertel 8360: 	}
                   8361: 	$title=~s/\&colon\;/\:/gs;
                   8362: 	if ($title) {
1.599     albertel 8363: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 8364: 	}
                   8365: 	$urlsymb=$url;
                   8366:     }
                   8367:     my $title=&metadata($urlsymb,'title');
                   8368:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   8369:     return $title;
1.301     www      8370: }
1.613     albertel 8371: 
1.614     albertel 8372: sub get_slot {
                   8373:     my ($which,$cnum,$cdom)=@_;
                   8374:     if (!$cnum || !$cdom) {
1.790     albertel 8375: 	(undef,my $courseid)=&whichuser();
1.620     albertel 8376: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   8377: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 8378:     }
1.703     albertel 8379:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   8380:     my %slotinfo;
                   8381:     if (exists($remembered{$key})) {
                   8382: 	$slotinfo{$which} = $remembered{$key};
                   8383:     } else {
                   8384: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   8385: 	&Apache::lonhomework::showhash(%slotinfo);
                   8386: 	my ($tmp)=keys(%slotinfo);
                   8387: 	if ($tmp=~/^error:/) { return (); }
                   8388: 	$remembered{$key} = $slotinfo{$which};
                   8389:     }
1.616     albertel 8390:     if (ref($slotinfo{$which}) eq 'HASH') {
                   8391: 	return %{$slotinfo{$which}};
                   8392:     }
                   8393:     return $slotinfo{$which};
1.614     albertel 8394: }
1.31      www      8395: # ------------------------------------------------- Update symbolic store links
                   8396: 
                   8397: sub symblist {
                   8398:     my ($mapname,%newhash)=@_;
1.438     www      8399:     $mapname=&deversion(&declutter($mapname));
1.31      www      8400:     my %hash;
1.620     albertel 8401:     if (($env{'request.course.fn'}) && (%newhash)) {
                   8402:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8403:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  8404: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 8405: 		next if ($url eq 'last_known'
                   8406: 			 && $env{'form.no_update_last_known'});
                   8407: 		$hash{declutter($url)}=&encode_symb($mapname,
                   8408: 						    $newhash{$url}->[1],
                   8409: 						    $newhash{$url}->[0]);
1.191     harris41 8410:             }
1.31      www      8411:             if (untie(%hash)) {
                   8412: 		return 'ok';
                   8413:             }
                   8414:         }
                   8415:     }
                   8416:     return 'error';
1.212     www      8417: }
                   8418: 
                   8419: # --------------------------------------------------------------- Verify a symb
                   8420: 
                   8421: sub symbverify {
1.510     www      8422:     my ($symb,$thisurl)=@_;
                   8423:     my $thisfn=$thisurl;
1.439     www      8424:     $thisfn=&declutter($thisfn);
1.215     www      8425: # direct jump to resource in page or to a sequence - will construct own symbs
                   8426:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   8427: # check URL part
1.409     www      8428:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      8429: 
1.431     www      8430:     unless ($url eq $thisfn) { return 0; }
1.213     www      8431: 
1.216     www      8432:     $symb=&symbclean($symb);
1.510     www      8433:     $thisurl=&deversion($thisurl);
1.439     www      8434:     $thisfn=&deversion($thisfn);
1.213     www      8435: 
                   8436:     my %bighash;
                   8437:     my $okay=0;
1.431     www      8438: 
1.620     albertel 8439:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8440:                             &GDBM_READER(),0640)) {
1.1032    raeburn  8441:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   8442:             $thisurl =~ s/\?.+$//;
                   8443:         }
1.510     www      8444:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      8445:         unless ($ids) { 
1.510     www      8446:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      8447:         }
                   8448:         if ($ids) {
                   8449: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 8450: 	    foreach my $id (split(/\,/,$ids)) {
                   8451: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  8452:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   8453:                    $symb =~ s/\?.+$//;
                   8454:                }
1.216     www      8455:                if (
                   8456:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   8457:    eq $symb) { 
1.620     albertel 8458: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 8459: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 8460: 		       $okay=1; 
                   8461: 		   }
                   8462: 	       }
1.216     www      8463: 	   }
                   8464:         }
1.213     www      8465: 	untie(%bighash);
                   8466:     }
                   8467:     return $okay;
1.31      www      8468: }
                   8469: 
1.210     www      8470: # --------------------------------------------------------------- Clean-up symb
                   8471: 
                   8472: sub symbclean {
                   8473:     my $symb=shift;
1.568     albertel 8474:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      8475: # remove version from map
                   8476:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      8477: 
1.210     www      8478: # remove version from URL
                   8479:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      8480: 
1.507     www      8481: # remove wrapper
                   8482: 
1.510     www      8483:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 8484:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      8485:     return $symb;
1.409     www      8486: }
                   8487: 
                   8488: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 8489: 
                   8490: sub encode_symb {
                   8491:     my ($map,$resid,$url)=@_;
                   8492:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   8493: }
1.409     www      8494: 
                   8495: sub decode_symb {
1.568     albertel 8496:     my $symb=shift;
                   8497:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   8498:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      8499:     return (&fixversion($map),$resid,&fixversion($url));
                   8500: }
                   8501: 
                   8502: sub fixversion {
                   8503:     my $fn=shift;
1.609     banghart 8504:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      8505:     my %bighash;
                   8506:     my $uri=&clutter($fn);
1.620     albertel 8507:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      8508: # is this cached?
1.599     albertel 8509:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      8510:     if (defined($cached)) { return $result; }
                   8511: # unfortunately not cached, or expired
1.620     albertel 8512:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      8513: 	    &GDBM_READER(),0640)) {
                   8514:  	if ($bighash{'version_'.$uri}) {
                   8515:  	    my $version=$bighash{'version_'.$uri};
1.444     www      8516:  	    unless (($version eq 'mostrecent') || 
                   8517: 		    ($version==&getversion($uri))) {
1.440     www      8518:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   8519:  	    }
                   8520:  	}
                   8521:  	untie %bighash;
1.413     www      8522:     }
1.599     albertel 8523:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      8524: }
                   8525: 
                   8526: sub deversion {
                   8527:     my $url=shift;
                   8528:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   8529:     return $url;
1.210     www      8530: }
                   8531: 
1.31      www      8532: # ------------------------------------------------------ Return symb list entry
                   8533: 
                   8534: sub symbread {
1.249     www      8535:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 8536:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 8537:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      8538: # no filename provided? try from environment
1.44      www      8539:     unless ($thisfn) {
1.620     albertel 8540:         if ($env{'request.symb'}) {
                   8541: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 8542: 	}
1.620     albertel 8543: 	$thisfn=$env{'request.filename'};
1.44      www      8544:     }
1.569     albertel 8545:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      8546: # is that filename actually a symb? Verify, clean, and return
                   8547:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 8548: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 8549: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 8550: 	}
1.242     www      8551:     }
1.44      www      8552:     $thisfn=declutter($thisfn);
1.31      www      8553:     my %hash;
1.37      www      8554:     my %bighash;
                   8555:     my $syval='';
1.620     albertel 8556:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  8557:         my $targetfn = $thisfn;
1.609     banghart 8558:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  8559:             $targetfn = 'adm/wrapper/'.$thisfn;
                   8560:         }
1.687     albertel 8561: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   8562: 	    $targetfn=$1;
                   8563: 	}
1.620     albertel 8564:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 8565:                       &GDBM_READER(),0640)) {
1.481     raeburn  8566: 	    $syval=$hash{$targetfn};
1.37      www      8567:             untie(%hash);
                   8568:         }
                   8569: # ---------------------------------------------------------- There was an entry
                   8570:         if ($syval) {
1.601     albertel 8571: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 8572: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  8573: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8574: 		    #return $env{$cache_str}='';
1.601     albertel 8575: 		#}    
                   8576: 		#$syval.=$1;
                   8577: 	    #}
1.37      www      8578:         } else {
                   8579: # ------------------------------------------------------- Was not in symb table
1.620     albertel 8580:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 8581:                             &GDBM_READER(),0640)) {
1.37      www      8582: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      8583:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      8584:               unless ($ids) { 
                   8585:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      8586:               }
                   8587:               unless ($ids) {
                   8588: # alias?
                   8589: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      8590:               }
1.37      www      8591:               if ($ids) {
                   8592: # ------------------------------------------------------------------- Has ID(s)
                   8593:                  my @possibilities=split(/\,/,$ids);
1.39      www      8594:                  if ($#possibilities==0) {
                   8595: # ----------------------------------------------- There is only one possibility
1.37      www      8596: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 8597: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8598: 						    $resid,$thisfn);
1.249     www      8599:                  } elsif (!$donotrecurse) {
1.39      www      8600: # ------------------------------------------ There is more than one possibility
                   8601:                      my $realpossible=0;
1.800     albertel 8602:                      foreach my $id (@possibilities) {
                   8603: 			 my $file=$bighash{'src_'.$id};
1.39      www      8604:                          if (&allowed('bre',$file)) {
1.800     albertel 8605:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      8606:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   8607: 				$realpossible++;
1.626     albertel 8608:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   8609: 						    $resid,$thisfn);
1.39      www      8610:                             }
                   8611: 			 }
1.191     harris41 8612:                      }
1.39      www      8613: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      8614:                  } else {
                   8615:                      $syval='';
1.37      www      8616:                  }
                   8617: 	      }
                   8618:               untie(%bighash)
1.481     raeburn  8619:            }
1.31      www      8620:         }
1.62      www      8621:         if ($syval) {
1.620     albertel 8622: 	    return $env{$cache_str}=$syval;
1.62      www      8623:         }
1.31      www      8624:     }
1.949     raeburn  8625:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 8626:     return $env{$cache_str}='';
1.31      www      8627: }
                   8628: 
                   8629: # ---------------------------------------------------------- Return random seed
                   8630: 
1.32      www      8631: sub numval {
                   8632:     my $txt=shift;
                   8633:     $txt=~tr/A-J/0-9/;
                   8634:     $txt=~tr/a-j/0-9/;
                   8635:     $txt=~tr/K-T/0-9/;
                   8636:     $txt=~tr/k-t/0-9/;
                   8637:     $txt=~tr/U-Z/0-5/;
                   8638:     $txt=~tr/u-z/0-5/;
                   8639:     $txt=~s/\D//g;
1.564     albertel 8640:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      8641:     return int($txt);
1.368     albertel 8642: }
                   8643: 
1.484     albertel 8644: sub numval2 {
                   8645:     my $txt=shift;
                   8646:     $txt=~tr/A-J/0-9/;
                   8647:     $txt=~tr/a-j/0-9/;
                   8648:     $txt=~tr/K-T/0-9/;
                   8649:     $txt=~tr/k-t/0-9/;
                   8650:     $txt=~tr/U-Z/0-5/;
                   8651:     $txt=~tr/u-z/0-5/;
                   8652:     $txt=~s/\D//g;
                   8653:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8654:     my $total;
                   8655:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 8656:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 8657:     return int($total);
                   8658: }
                   8659: 
1.575     albertel 8660: sub numval3 {
                   8661:     use integer;
                   8662:     my $txt=shift;
                   8663:     $txt=~tr/A-J/0-9/;
                   8664:     $txt=~tr/a-j/0-9/;
                   8665:     $txt=~tr/K-T/0-9/;
                   8666:     $txt=~tr/k-t/0-9/;
                   8667:     $txt=~tr/U-Z/0-5/;
                   8668:     $txt=~tr/u-z/0-5/;
                   8669:     $txt=~s/\D//g;
                   8670:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   8671:     my $total;
                   8672:     foreach my $val (@txts) { $total+=$val; }
                   8673:     if ($_64bit) { $total=(($total<<32)>>32); }
                   8674:     return $total;
                   8675: }
                   8676: 
1.675     albertel 8677: sub digest {
                   8678:     my ($data)=@_;
                   8679:     my $digest=&Digest::MD5::md5($data);
                   8680:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   8681:     my ($e,$f);
                   8682:     {
                   8683:         use integer;
                   8684:         $e=($a+$b);
                   8685:         $f=($c+$d);
                   8686:         if ($_64bit) {
                   8687:             $e=(($e<<32)>>32);
                   8688:             $f=(($f<<32)>>32);
                   8689:         }
                   8690:     }
                   8691:     if (wantarray) {
                   8692: 	return ($e,$f);
                   8693:     } else {
                   8694: 	my $g;
                   8695: 	{
                   8696: 	    use integer;
                   8697: 	    $g=($e+$f);
                   8698: 	    if ($_64bit) {
                   8699: 		$g=(($g<<32)>>32);
                   8700: 	    }
                   8701: 	}
                   8702: 	return $g;
                   8703:     }
                   8704: }
                   8705: 
1.368     albertel 8706: sub latest_rnd_algorithm_id {
1.675     albertel 8707:     return '64bit5';
1.366     albertel 8708: }
1.32      www      8709: 
1.503     albertel 8710: sub get_rand_alg {
                   8711:     my ($courseid)=@_;
1.790     albertel 8712:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 8713:     if ($courseid) {
1.620     albertel 8714: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 8715:     }
                   8716:     return &latest_rnd_algorithm_id();
                   8717: }
                   8718: 
1.562     albertel 8719: sub validCODE {
                   8720:     my ($CODE)=@_;
                   8721:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   8722:     return 0;
                   8723: }
                   8724: 
1.491     albertel 8725: sub getCODE {
1.620     albertel 8726:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 8727:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   8728: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   8729: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 8730: 	return $Apache::lonhomework::history{'resource.CODE'};
                   8731:     }
                   8732:     return undef;
                   8733: }
                   8734: 
1.31      www      8735: sub rndseed {
1.155     albertel 8736:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 8737:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 8738:     if (!defined($symb)) {
1.366     albertel 8739: 	unless ($symb=$wsymb) { return time; }
                   8740:     }
                   8741:     if (!$courseid) { $courseid=$wcourseid; }
                   8742:     if (!$domain) { $domain=$wdomain; }
                   8743:     if (!$username) { $username=$wusername }
1.503     albertel 8744:     my $which=&get_rand_alg();
1.803     albertel 8745: 
1.491     albertel 8746:     if (defined(&getCODE())) {
1.675     albertel 8747: 	if ($which eq '64bit5') {
                   8748: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   8749: 	} elsif ($which eq '64bit4') {
1.575     albertel 8750: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   8751: 	} else {
                   8752: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   8753: 	}
1.675     albertel 8754:     } elsif ($which eq '64bit5') {
                   8755: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 8756:     } elsif ($which eq '64bit4') {
                   8757: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 8758:     } elsif ($which eq '64bit3') {
                   8759: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 8760:     } elsif ($which eq '64bit2') {
                   8761: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 8762:     } elsif ($which eq '64bit') {
                   8763: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   8764:     }
                   8765:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   8766: }
                   8767: 
                   8768: sub rndseed_32bit {
                   8769:     my ($symb,$courseid,$domain,$username)=@_;
                   8770:     {
                   8771: 	use integer;
                   8772: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8773: 	my $symbseed=numval($symb) << 22;
                   8774: 	my $namechck=unpack("%32C*",$username) << 17;
                   8775: 	my $nameseed=numval($username) << 12;
                   8776: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8777: 	my $courseseed=unpack("%32C*",$courseid);
                   8778: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8779: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8780: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8781: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8782: 	return $num;
                   8783:     }
                   8784: }
                   8785: 
                   8786: sub rndseed_64bit {
                   8787:     my ($symb,$courseid,$domain,$username)=@_;
                   8788:     {
                   8789: 	use integer;
                   8790: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8791: 	my $symbseed=numval($symb) << 10;
                   8792: 	my $namechck=unpack("%32S*",$username);
                   8793: 	
                   8794: 	my $nameseed=numval($username) << 21;
                   8795: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8796: 	my $courseseed=unpack("%32S*",$courseid);
                   8797: 	
                   8798: 	my $num1=$symbchck+$symbseed+$namechck;
                   8799: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8800: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8801: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8802: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8803: 	return "$num1,$num2";
1.155     albertel 8804:     }
1.366     albertel 8805: }
                   8806: 
1.443     albertel 8807: sub rndseed_64bit2 {
                   8808:     my ($symb,$courseid,$domain,$username)=@_;
                   8809:     {
                   8810: 	use integer;
                   8811: 	# strings need to be an even # of cahracters long, it it is odd the
                   8812:         # last characters gets thrown away
                   8813: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8814: 	my $symbseed=numval($symb) << 10;
                   8815: 	my $namechck=unpack("%32S*",$username.' ');
                   8816: 	
                   8817: 	my $nameseed=numval($username) << 21;
1.501     albertel 8818: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8819: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8820: 	
                   8821: 	my $num1=$symbchck+$symbseed+$namechck;
                   8822: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8823: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8824: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8825: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8826: 	return "$num1,$num2";
                   8827:     }
                   8828: }
                   8829: 
                   8830: sub rndseed_64bit3 {
                   8831:     my ($symb,$courseid,$domain,$username)=@_;
                   8832:     {
                   8833: 	use integer;
                   8834: 	# strings need to be an even # of cahracters long, it it is odd the
                   8835:         # last characters gets thrown away
                   8836: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8837: 	my $symbseed=numval2($symb) << 10;
                   8838: 	my $namechck=unpack("%32S*",$username.' ');
                   8839: 	
                   8840: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8841: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8842: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8843: 	
                   8844: 	my $num1=$symbchck+$symbseed+$namechck;
                   8845: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8846: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8847: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8848: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8849: 	
1.503     albertel 8850: 	return "$num1:$num2";
1.443     albertel 8851:     }
                   8852: }
                   8853: 
1.575     albertel 8854: sub rndseed_64bit4 {
                   8855:     my ($symb,$courseid,$domain,$username)=@_;
                   8856:     {
                   8857: 	use integer;
                   8858: 	# strings need to be an even # of cahracters long, it it is odd the
                   8859:         # last characters gets thrown away
                   8860: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8861: 	my $symbseed=numval3($symb) << 10;
                   8862: 	my $namechck=unpack("%32S*",$username.' ');
                   8863: 	
                   8864: 	my $nameseed=numval3($username) << 21;
                   8865: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8866: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8867: 	
                   8868: 	my $num1=$symbchck+$symbseed+$namechck;
                   8869: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8870: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8871: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8872: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8873: 	
                   8874: 	return "$num1:$num2";
                   8875:     }
                   8876: }
                   8877: 
1.675     albertel 8878: sub rndseed_64bit5 {
                   8879:     my ($symb,$courseid,$domain,$username)=@_;
                   8880:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8881:     return "$num1:$num2";
                   8882: }
                   8883: 
1.366     albertel 8884: sub rndseed_CODE_64bit {
                   8885:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8886:     {
1.366     albertel 8887: 	use integer;
1.443     albertel 8888: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8889: 	my $symbseed=numval2($symb);
1.491     albertel 8890: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8891: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8892: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8893: 	my $num1=$symbseed+$CODEchck;
                   8894: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8895: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8896: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8897: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8898: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8899: 	return "$num1:$num2";
1.366     albertel 8900:     }
                   8901: }
                   8902: 
1.575     albertel 8903: sub rndseed_CODE_64bit4 {
                   8904:     my ($symb,$courseid,$domain,$username)=@_;
                   8905:     {
                   8906: 	use integer;
                   8907: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8908: 	my $symbseed=numval3($symb);
                   8909: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8910: 	my $CODEseed=numval3(&getCODE());
                   8911: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8912: 	my $num1=$symbseed+$CODEchck;
                   8913: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8914: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8915: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8916: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8917: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8918: 	return "$num1:$num2";
                   8919:     }
                   8920: }
                   8921: 
1.675     albertel 8922: sub rndseed_CODE_64bit5 {
                   8923:     my ($symb,$courseid,$domain,$username)=@_;
                   8924:     my $code = &getCODE();
                   8925:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8926:     return "$num1:$num2";
                   8927: }
                   8928: 
1.366     albertel 8929: sub setup_random_from_rndseed {
                   8930:     my ($rndseed)=@_;
1.503     albertel 8931:     if ($rndseed =~/([,:])/) {
                   8932: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8933: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8934:     } else {
                   8935: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8936:     }
1.36      albertel 8937: }
                   8938: 
1.474     albertel 8939: sub latest_receipt_algorithm_id {
1.835     albertel 8940:     return 'receipt3';
1.474     albertel 8941: }
                   8942: 
1.480     www      8943: sub recunique {
                   8944:     my $fucourseid=shift;
                   8945:     my $unique;
1.835     albertel 8946:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8947: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8948: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8949:     } else {
                   8950: 	$unique=$perlvar{'lonReceipt'};
                   8951:     }
                   8952:     return unpack("%32C*",$unique);
                   8953: }
                   8954: 
                   8955: sub recprefix {
                   8956:     my $fucourseid=shift;
                   8957:     my $prefix;
1.835     albertel 8958:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8959: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8960: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8961:     } else {
                   8962: 	$prefix=$perlvar{'lonHostID'};
                   8963:     }
                   8964:     return unpack("%32C*",$prefix);
                   8965: }
                   8966: 
1.76      www      8967: sub ireceipt {
1.474     albertel 8968:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8969: 
                   8970:     my $return =&recprefix($fucourseid).'-';
                   8971: 
                   8972:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8973: 	$env{'request.state'} eq 'construct') {
                   8974: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8975: 	return $return;
                   8976:     }
                   8977: 
1.76      www      8978:     my $cuname=unpack("%32C*",$funame);
                   8979:     my $cudom=unpack("%32C*",$fudom);
                   8980:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8981:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8982:     my $cunique=&recunique($fucourseid);
1.474     albertel 8983:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8984:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8985: 
1.790     albertel 8986: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8987: 			       
                   8988: 	$return.= ($cunique%$cuname+
                   8989: 		   $cunique%$cudom+
                   8990: 		   $cusymb%$cuname+
                   8991: 		   $cusymb%$cudom+
                   8992: 		   $cucourseid%$cuname+
                   8993: 		   $cucourseid%$cudom+
                   8994: 		   $cpart%$cuname+
                   8995: 		   $cpart%$cudom);
                   8996:     } else {
                   8997: 	$return.= ($cunique%$cuname+
                   8998: 		   $cunique%$cudom+
                   8999: 		   $cusymb%$cuname+
                   9000: 		   $cusymb%$cudom+
                   9001: 		   $cucourseid%$cuname+
                   9002: 		   $cucourseid%$cudom);
                   9003:     }
                   9004:     return $return;
1.76      www      9005: }
                   9006: 
                   9007: sub receipt {
1.474     albertel 9008:     my ($part)=@_;
1.790     albertel 9009:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9010:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9011: }
1.260     ng       9012: 
1.790     albertel 9013: sub whichuser {
                   9014:     my ($passedsymb)=@_;
                   9015:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9016:     if (defined($env{'form.grade_symb'})) {
                   9017: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9018: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9019: 	if (!$allowed &&
                   9020: 	    exists($env{'request.course.sec'}) &&
                   9021: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9022: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9023: 			      '/'.$env{'request.course.sec'});
                   9024: 	}
                   9025: 	if ($allowed) {
                   9026: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9027: 	    $courseid=$tmp_courseid;
                   9028: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9029: 	    ($name)=&get_env_multiple('form.grade_username');
                   9030: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9031: 	}
                   9032:     }
                   9033:     if (!$passedsymb) {
                   9034: 	$symb=&symbread();
                   9035:     } else {
                   9036: 	$symb=$passedsymb;
                   9037:     }
                   9038:     $courseid=$env{'request.course.id'};
                   9039:     $domain=$env{'user.domain'};
                   9040:     $name=$env{'user.name'};
                   9041:     if ($name eq 'public' && $domain eq 'public') {
                   9042: 	if (!defined($env{'form.username'})) {
                   9043: 	    $env{'form.username'}.=time.rand(10000000);
                   9044: 	}
                   9045: 	$name.=$env{'form.username'};
                   9046:     }
                   9047:     return ($symb,$courseid,$domain,$name,$publicuser);
                   9048: 
                   9049: }
                   9050: 
1.36      albertel 9051: # ------------------------------------------------------------ Serves up a file
1.472     albertel 9052: # returns either the contents of the file or 
                   9053: # -1 if the file doesn't exist
1.481     raeburn  9054: #
                   9055: # if the target is a file that was uploaded via DOCS, 
                   9056: # a check will be made to see if a current copy exists on the local server,
                   9057: # if it does this will be served, otherwise a copy will be retrieved from
                   9058: # the home server for the course and stored in /home/httpd/html/userfiles on
                   9059: # the local server.   
1.472     albertel 9060: 
1.36      albertel 9061: sub getfile {
1.538     albertel 9062:     my ($file) = @_;
1.609     banghart 9063:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 9064:     &repcopy($file);
                   9065:     return &readfile($file);
                   9066: }
                   9067: 
                   9068: sub repcopy_userfile {
                   9069:     my ($file)=@_;
1.609     banghart 9070:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 9071:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 9072:     my ($cdom,$cnum,$filename) = 
1.811     albertel 9073: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 9074:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   9075:     if (-e "$file") {
1.828     www      9076: # we already have a local copy, check it out
1.538     albertel 9077: 	my @fileinfo = stat($file);
1.828     www      9078: 	my $rtncode;
                   9079: 	my $info;
1.538     albertel 9080: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 9081: 	if ($lwpresp ne 'ok') {
1.828     www      9082: # there is no such file anymore, even though we had a local copy
1.482     albertel 9083: 	    if ($rtncode eq '404') {
1.538     albertel 9084: 		unlink($file);
1.482     albertel 9085: 	    }
                   9086: 	    return -1;
                   9087: 	}
                   9088: 	if ($info < $fileinfo[9]) {
1.828     www      9089: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  9090: 	    return 'ok';
1.828     www      9091: 	} else {
                   9092: # the file is outdated, get rid of it
                   9093: 	    unlink($file);
1.482     albertel 9094: 	}
1.828     www      9095:     }
                   9096: # one way or the other, at this point, we don't have the file
                   9097: # construct the correct path for the file
                   9098:     my @parts = ($cdom,$cnum); 
                   9099:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   9100: 	push @parts, split(/\//,$1);
                   9101:     }
                   9102:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   9103:     foreach my $part (@parts) {
                   9104: 	$path .= '/'.$part;
                   9105: 	if (!-e $path) {
                   9106: 	    mkdir($path,0770);
1.482     albertel 9107: 	}
                   9108:     }
1.828     www      9109: # now the path exists for sure
                   9110: # get a user agent
                   9111:     my $ua=new LWP::UserAgent;
                   9112:     my $transferfile=$file.'.in.transfer';
                   9113: # FIXME: this should flock
                   9114:     if (-e $transferfile) { return 'ok'; }
                   9115:     my $request;
                   9116:     $uri=~s/^\///;
1.980     raeburn  9117:     my $homeserver = &homeserver($cnum,$cdom);
                   9118:     my $protocol = $protocol{$homeserver};
                   9119:     $protocol = 'http' if ($protocol ne 'https');
                   9120:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      9121:     my $response=$ua->request($request,$transferfile);
                   9122: # did it work?
                   9123:     if ($response->is_error()) {
                   9124: 	unlink($transferfile);
                   9125: 	&logthis("Userfile repcopy failed for $uri");
                   9126: 	return -1;
                   9127:     }
                   9128: # worked, rename the transfer file
                   9129:     rename($transferfile,$file);
1.607     raeburn  9130:     return 'ok';
1.481     raeburn  9131: }
                   9132: 
1.517     albertel 9133: sub tokenwrapper {
                   9134:     my $uri=shift;
1.980     raeburn  9135:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 9136:     $uri=~s|^/||;
1.620     albertel 9137:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 9138:     my $token=$1;
1.552     albertel 9139:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   9140:     if ($udom && $uname && $file) {
                   9141: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  9142:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  9143:         my $homeserver = &homeserver($uname,$udom);
                   9144:         my $protocol = $protocol{$homeserver};
                   9145:         $protocol = 'http' if ($protocol ne 'https');
                   9146:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 9147:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   9148:                                '&tokenissued='.$perlvar{'lonHostID'};
                   9149:     } else {
                   9150:         return '/adm/notfound.html';
                   9151:     }
                   9152: }
                   9153: 
1.828     www      9154: # call with reqtype HEAD: get last modification time
                   9155: # call with reqtype GET: get the file contents
                   9156: # Do not call this with reqtype GET for large files! It loads everything into memory
                   9157: #
1.481     raeburn  9158: sub getuploaded {
                   9159:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   9160:     $uri=~s/^\///;
1.980     raeburn  9161:     my $homeserver = &homeserver($cnum,$cdom);
                   9162:     my $protocol = $protocol{$homeserver};
                   9163:     $protocol = 'http' if ($protocol ne 'https');
                   9164:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  9165:     my $ua=new LWP::UserAgent;
                   9166:     my $request=new HTTP::Request($reqtype,$uri);
                   9167:     my $response=$ua->request($request);
                   9168:     $$rtncode = $response->code;
1.482     albertel 9169:     if (! $response->is_success()) {
                   9170: 	return 'failed';
                   9171:     }      
                   9172:     if ($reqtype eq 'HEAD') {
1.486     www      9173: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 9174:     } elsif ($reqtype eq 'GET') {
                   9175: 	$$info = $response->content;
1.472     albertel 9176:     }
1.482     albertel 9177:     return 'ok';
1.36      albertel 9178: }
                   9179: 
1.481     raeburn  9180: sub readfile {
                   9181:     my $file = shift;
                   9182:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   9183:     my $fh;
                   9184:     open($fh,"<$file");
                   9185:     my $a='';
1.800     albertel 9186:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  9187:     return $a;
                   9188: }
                   9189: 
1.36      albertel 9190: sub filelocation {
1.590     banghart 9191:     my ($dir,$file) = @_;
                   9192:     my $location;
                   9193:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 9194: 
                   9195:     if ($file =~ m-^/adm/-) {
                   9196: 	$file=~s-^/adm/wrapper/-/-;
                   9197: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   9198:     }
1.882     albertel 9199: 
1.590     banghart 9200:     if ($file=~m:^/~:) { # is a contruction space reference
                   9201:         $location = $file;
                   9202:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 9203:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 9204: 	# is a correct contruction space reference
                   9205:         $location = $file;
1.956     raeburn  9206:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   9207:         $location = $file;
1.609     banghart 9208:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 9209:         my ($udom,$uname,$filename)=
1.811     albertel 9210:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 9211:         my $home=&homeserver($uname,$udom);
                   9212:         my $is_me=0;
                   9213:         my @ids=&current_machine_ids();
                   9214:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   9215:         if ($is_me) {
1.955     raeburn  9216:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 9217:         } else {
                   9218:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   9219:   	      $udom.'/'.$uname.'/'.$filename;
                   9220:         }
1.882     albertel 9221:     } elsif ($file =~ m-^/adm/-) {
                   9222: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 9223:     } else {
                   9224:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   9225:         $file=~s:^/res/:/:;
                   9226:         if ( !( $file =~ m:^/:) ) {
                   9227:             $location = $dir. '/'.$file;
                   9228:         } else {
                   9229:             $location = '/home/httpd/html/res'.$file;
                   9230:         }
1.59      albertel 9231:     }
1.590     banghart 9232:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 9233:     while ($location=~m{/\.\./}) {
                   9234: 	if ($location =~ m{/[^/]+/\.\./}) {
                   9235: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   9236: 	} else {
                   9237: 	    $location=~ s{/\.\./}{/}g;
                   9238: 	}
                   9239:     } #remove dir/..
1.590     banghart 9240:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   9241:     return $location;
1.46      www      9242: }
1.36      albertel 9243: 
1.46      www      9244: sub hreflocation {
                   9245:     my ($dir,$file)=@_;
1.980     raeburn  9246:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 9247: 	$file=filelocation($dir,$file);
1.700     albertel 9248:     } elsif ($file=~m-^/adm/-) {
                   9249: 	$file=~s-^/adm/wrapper/-/-;
                   9250: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 9251:     }
                   9252:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   9253: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 9254:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   9255: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 9256:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 9257: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 9258: 	    -/uploaded/$1/$2/-x;
1.46      www      9259:     }
1.913     albertel 9260:     if ($file=~ m{^/userfiles/}) {
                   9261: 	$file =~ s{^/userfiles/}{/uploaded/};
                   9262:     }
1.462     albertel 9263:     return $file;
1.465     albertel 9264: }
                   9265: 
                   9266: sub current_machine_domains {
1.853     albertel 9267:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   9268: }
                   9269: 
                   9270: sub machine_domains {
                   9271:     my ($hostname) = @_;
1.465     albertel 9272:     my @domains;
1.838     albertel 9273:     my %hostname = &all_hostnames();
1.465     albertel 9274:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  9275: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 9276: 	if ($hostname eq $name) {
1.844     albertel 9277: 	    push(@domains,&host_domain($id));
1.465     albertel 9278: 	}
                   9279:     }
                   9280:     return @domains;
                   9281: }
                   9282: 
                   9283: sub current_machine_ids {
1.853     albertel 9284:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   9285: }
                   9286: 
                   9287: sub machine_ids {
                   9288:     my ($hostname) = @_;
                   9289:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 9290:     my @ids;
1.888     albertel 9291:     my %name_to_host = &all_names();
1.889     albertel 9292:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   9293: 	return @{ $name_to_host{$hostname} };
                   9294:     }
                   9295:     return;
1.31      www      9296: }
                   9297: 
1.824     raeburn  9298: sub additional_machine_domains {
                   9299:     my @domains;
                   9300:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   9301:     while( my $line = <$fh>) {
                   9302:         $line =~ s/\s//g;
                   9303:         push(@domains,$line);
                   9304:     }
                   9305:     return @domains;
                   9306: }
                   9307: 
                   9308: sub default_login_domain {
                   9309:     my $domain = $perlvar{'lonDefDomain'};
                   9310:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   9311:     foreach my $posdom (&current_machine_domains(),
                   9312:                         &additional_machine_domains()) {
                   9313:         if (lc($posdom) eq lc($testdomain)) {
                   9314:             $domain=$posdom;
                   9315:             last;
                   9316:         }
                   9317:     }
                   9318:     return $domain;
                   9319: }
                   9320: 
1.31      www      9321: # ------------------------------------------------------------- Declutters URLs
                   9322: 
                   9323: sub declutter {
                   9324:     my $thisfn=shift;
1.569     albertel 9325:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 9326:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      9327:     $thisfn=~s/^\///;
1.697     albertel 9328:     $thisfn=~s|^adm/wrapper/||;
                   9329:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      9330:     $thisfn=~s/^res\///;
1.1032    raeburn  9331:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   9332:         $thisfn=~s/\?.+$//;
                   9333:     }
1.268     www      9334:     return $thisfn;
                   9335: }
                   9336: 
                   9337: # ------------------------------------------------------------- Clutter up URLs
                   9338: 
                   9339: sub clutter {
                   9340:     my $thisfn='/'.&declutter(shift);
1.887     albertel 9341:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 9342: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      9343:        $thisfn='/res'.$thisfn; 
                   9344:     }
1.1031    raeburn  9345:     if ($thisfn !~m|^/adm|) {
                   9346: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 9347: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 9348: 	} else {
                   9349: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   9350: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 9351: 	    if ($embstyle eq 'ssi'
                   9352: 		|| ($embstyle eq 'hdn')
                   9353: 		|| ($embstyle eq 'rat')
                   9354: 		|| ($embstyle eq 'prv')
                   9355: 		|| ($embstyle eq 'ign')) {
                   9356: 		#do nothing with these
                   9357: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 9358: 		|| ($embstyle eq 'emb')
                   9359: 		|| ($embstyle eq 'wrp')) {
                   9360: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 9361: 	    } elsif ($embstyle eq 'unk'
                   9362: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 9363: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 9364: 	    } else {
1.718     www      9365: #		&logthis("Got a blank emb style");
1.695     albertel 9366: 	    }
1.694     albertel 9367: 	}
                   9368:     }
1.31      www      9369:     return $thisfn;
1.12      www      9370: }
                   9371: 
1.787     albertel 9372: sub clutter_with_no_wrapper {
                   9373:     my $uri = &clutter(shift);
                   9374:     if ($uri =~ m-^/adm/-) {
                   9375: 	$uri =~ s-^/adm/wrapper/-/-;
                   9376: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   9377:     }
                   9378:     return $uri;
                   9379: }
                   9380: 
1.557     albertel 9381: sub freeze_escape {
                   9382:     my ($value)=@_;
                   9383:     if (ref($value)) {
                   9384: 	$value=&nfreeze($value);
                   9385: 	return '__FROZEN__'.&escape($value);
                   9386:     }
                   9387:     return &escape($value);
                   9388: }
                   9389: 
1.11      www      9390: 
1.557     albertel 9391: sub thaw_unescape {
                   9392:     my ($value)=@_;
                   9393:     if ($value =~ /^__FROZEN__/) {
                   9394: 	substr($value,0,10,undef);
                   9395: 	$value=&unescape($value);
                   9396: 	return &thaw($value);
                   9397:     }
                   9398:     return &unescape($value);
                   9399: }
                   9400: 
1.436     albertel 9401: sub correct_line_ends {
                   9402:     my ($result)=@_;
                   9403:     $$result =~s/\r\n/\n/mg;
                   9404:     $$result =~s/\r/\n/mg;
1.415     albertel 9405: }
1.1       albertel 9406: # ================================================================ Main Program
                   9407: 
1.184     www      9408: sub goodbye {
1.204     albertel 9409:    &logthis("Starting Shut down");
1.443     albertel 9410: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 9411:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 9412: #converted
1.599     albertel 9413: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 9414:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   9415: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   9416: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 9417: #1.1 only
1.870     albertel 9418: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   9419: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   9420: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   9421: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   9422:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 9423:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   9424:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      9425:    &flushcourselogs();
                   9426:    &logthis("Shutting down");
                   9427: }
                   9428: 
1.852     albertel 9429: sub get_dns {
1.869     albertel 9430:     my ($url,$func,$ignore_cache) = @_;
                   9431:     if (!$ignore_cache) {
                   9432: 	my ($content,$cached)=
                   9433: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   9434: 	if ($cached) {
                   9435: 	    &$func($content);
                   9436: 	    return;
                   9437: 	}
                   9438:     }
                   9439: 
                   9440:     my %alldns;
1.852     albertel 9441:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9442:     foreach my $dns (<$config>) {
                   9443: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  9444:         my $line = $1;
                   9445:         my ($host,$protocol) = split(/:/,$line);
                   9446:         if ($protocol ne 'https') {
                   9447:             $protocol = 'http';
                   9448:         }
                   9449: 	$alldns{$host} = $protocol;
1.869     albertel 9450:     }
                   9451:     while (%alldns) {
                   9452: 	my ($dns) = keys(%alldns);
1.852     albertel 9453: 	my $ua=new LWP::UserAgent;
1.979     raeburn  9454: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 9455: 	my $response=$ua->request($request);
1.979     raeburn  9456:         delete($alldns{$dns});
1.852     albertel 9457: 	next if ($response->is_error());
                   9458: 	my @content = split("\n",$response->content);
1.869     albertel 9459: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 9460: 	&$func(\@content);
1.869     albertel 9461: 	return;
1.852     albertel 9462:     }
                   9463:     close($config);
1.871     albertel 9464:     my $which = (split('/',$url))[3];
                   9465:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   9466:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 9467:     my @content = <$config>;
                   9468:     &$func(\@content);
                   9469:     return;
1.852     albertel 9470: }
1.327     albertel 9471: # ------------------------------------------------------------ Read domain file
                   9472: {
1.852     albertel 9473:     my $loaded;
1.846     albertel 9474:     my %domain;
                   9475: 
1.852     albertel 9476:     sub parse_domain_tab {
                   9477: 	my ($lines) = @_;
                   9478: 	foreach my $line (@$lines) {
                   9479: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      9480: 
1.846     albertel 9481: 	    chomp($line);
1.852     albertel 9482: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 9483: 	    my %this_domain;
                   9484: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   9485: 			       'lang_def', 'city', 'longi', 'lati',
                   9486: 			       'primary') {
                   9487: 		$this_domain{$field} = shift(@elements);
                   9488: 	    }
                   9489: 	    $domain{$name} = \%this_domain;
1.852     albertel 9490: 	}
                   9491:     }
1.864     albertel 9492: 
                   9493:     sub reset_domain_info {
                   9494: 	undef($loaded);
                   9495: 	undef(%domain);
                   9496:     }
                   9497: 
1.852     albertel 9498:     sub load_domain_tab {
1.869     albertel 9499: 	my ($ignore_cache) = @_;
                   9500: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 9501: 	my $fh;
                   9502: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   9503: 	    my @lines = <$fh>;
                   9504: 	    &parse_domain_tab(\@lines);
1.448     albertel 9505: 	}
1.852     albertel 9506: 	close($fh);
                   9507: 	$loaded = 1;
1.327     albertel 9508:     }
1.846     albertel 9509: 
                   9510:     sub domain {
1.852     albertel 9511: 	&load_domain_tab() if (!$loaded);
                   9512: 
1.846     albertel 9513: 	my ($name,$what) = @_;
                   9514: 	return if ( !exists($domain{$name}) );
                   9515: 
                   9516: 	if (!$what) {
                   9517: 	    return $domain{$name}{'description'};
                   9518: 	}
                   9519: 	return $domain{$name}{$what};
                   9520:     }
1.974     raeburn  9521: 
                   9522:     sub domain_info {
                   9523:         &load_domain_tab() if (!$loaded);
                   9524:         return %domain;
                   9525:     }
                   9526: 
1.327     albertel 9527: }
                   9528: 
                   9529: 
1.1       albertel 9530: # ------------------------------------------------------------- Read hosts file
                   9531: {
1.838     albertel 9532:     my %hostname;
1.844     albertel 9533:     my %hostdom;
1.845     albertel 9534:     my %libserv;
1.852     albertel 9535:     my $loaded;
1.888     albertel 9536:     my %name_to_host;
1.852     albertel 9537: 
                   9538:     sub parse_hosts_tab {
                   9539: 	my ($file) = @_;
                   9540: 	foreach my $configline (@$file) {
                   9541: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   9542: 	    next if ($configline =~ /^\^/);
                   9543: 	    chomp($configline);
1.968     raeburn  9544: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 9545: 	    $name=~s/\s//g;
                   9546: 	    if ($id && $domain && $role && $name) {
                   9547: 		$hostname{$id}=$name;
1.888     albertel 9548: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 9549: 		$hostdom{$id}=$domain;
                   9550: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  9551:                 if (defined($protocol)) {
                   9552:                     if ($protocol eq 'https') {
                   9553:                         $protocol{$id} = $protocol;
                   9554:                     } else {
                   9555:                         $protocol{$id} = 'http'; 
                   9556:                     }
1.968     raeburn  9557:                 } else {
1.969     raeburn  9558:                     $protocol{$id} = 'http';
1.968     raeburn  9559:                 }
1.852     albertel 9560: 	    }
                   9561: 	}
                   9562:     }
1.864     albertel 9563:     
                   9564:     sub reset_hosts_info {
1.897     albertel 9565: 	&purge_remembered();
1.864     albertel 9566: 	&reset_domain_info();
                   9567: 	&reset_hosts_ip_info();
1.892     albertel 9568: 	undef(%name_to_host);
1.864     albertel 9569: 	undef(%hostname);
                   9570: 	undef(%hostdom);
                   9571: 	undef(%libserv);
                   9572: 	undef($loaded);
                   9573:     }
1.1       albertel 9574: 
1.852     albertel 9575:     sub load_hosts_tab {
1.869     albertel 9576: 	my ($ignore_cache) = @_;
                   9577: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 9578: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   9579: 	my @config = <$config>;
                   9580: 	&parse_hosts_tab(\@config);
                   9581: 	close($config);
                   9582: 	$loaded=1;
1.1       albertel 9583:     }
1.852     albertel 9584: 
1.838     albertel 9585:     sub hostname {
1.852     albertel 9586: 	&load_hosts_tab() if (!$loaded);
                   9587: 
1.838     albertel 9588: 	my ($lonid) = @_;
                   9589: 	return $hostname{$lonid};
                   9590:     }
1.845     albertel 9591: 
1.838     albertel 9592:     sub all_hostnames {
1.852     albertel 9593: 	&load_hosts_tab() if (!$loaded);
                   9594: 
1.838     albertel 9595: 	return %hostname;
                   9596:     }
1.845     albertel 9597: 
1.888     albertel 9598:     sub all_names {
                   9599: 	&load_hosts_tab() if (!$loaded);
                   9600: 
                   9601: 	return %name_to_host;
                   9602:     }
                   9603: 
1.974     raeburn  9604:     sub all_host_domain {
                   9605:         &load_hosts_tab() if (!$loaded);
                   9606:         return %hostdom;
                   9607:     }
                   9608: 
1.845     albertel 9609:     sub is_library {
1.852     albertel 9610: 	&load_hosts_tab() if (!$loaded);
                   9611: 
1.845     albertel 9612: 	return exists($libserv{$_[0]});
                   9613:     }
                   9614: 
                   9615:     sub all_library {
1.852     albertel 9616: 	&load_hosts_tab() if (!$loaded);
                   9617: 
1.845     albertel 9618: 	return %libserv;
                   9619:     }
                   9620: 
1.841     albertel 9621:     sub get_servers {
1.852     albertel 9622: 	&load_hosts_tab() if (!$loaded);
                   9623: 
1.841     albertel 9624: 	my ($domain,$type) = @_;
                   9625: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   9626: 	                                          : %hostname;
                   9627: 	my %result;
1.842     albertel 9628: 	if (ref($domain) eq 'ARRAY') {
                   9629: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 9630: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 9631: 		    $result{$host} = $hostname;
                   9632: 		}
                   9633: 	    }
                   9634: 	} else {
                   9635: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   9636: 		if ($hostdom{$host} eq $domain) {
                   9637: 		    $result{$host} = $hostname;
                   9638: 		}
1.841     albertel 9639: 	    }
                   9640: 	}
                   9641: 	return %result;
                   9642:     }
1.845     albertel 9643: 
1.844     albertel 9644:     sub host_domain {
1.852     albertel 9645: 	&load_hosts_tab() if (!$loaded);
                   9646: 
1.844     albertel 9647: 	my ($lonid) = @_;
                   9648: 	return $hostdom{$lonid};
                   9649:     }
                   9650: 
1.841     albertel 9651:     sub all_domains {
1.852     albertel 9652: 	&load_hosts_tab() if (!$loaded);
                   9653: 
1.841     albertel 9654: 	my %seen;
                   9655: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   9656: 	return @uniq;
                   9657:     }
1.1       albertel 9658: }
                   9659: 
1.847     albertel 9660: { 
                   9661:     my %iphost;
1.856     albertel 9662:     my %name_to_ip;
                   9663:     my %lonid_to_ip;
1.869     albertel 9664: 
1.847     albertel 9665:     sub get_hosts_from_ip {
                   9666: 	my ($ip) = @_;
                   9667: 	my %iphosts = &get_iphost();
                   9668: 	if (ref($iphosts{$ip})) {
                   9669: 	    return @{$iphosts{$ip}};
                   9670: 	}
                   9671: 	return;
1.839     albertel 9672:     }
1.864     albertel 9673:     
                   9674:     sub reset_hosts_ip_info {
                   9675: 	undef(%iphost);
                   9676: 	undef(%name_to_ip);
                   9677: 	undef(%lonid_to_ip);
                   9678:     }
1.856     albertel 9679: 
                   9680:     sub get_host_ip {
                   9681: 	my ($lonid) = @_;
                   9682: 	if (exists($lonid_to_ip{$lonid})) {
                   9683: 	    return $lonid_to_ip{$lonid};
                   9684: 	}
                   9685: 	my $name=&hostname($lonid);
                   9686:    	my $ip = gethostbyname($name);
                   9687: 	return if (!$ip || length($ip) ne 4);
                   9688: 	$ip=inet_ntoa($ip);
                   9689: 	$name_to_ip{$name}   = $ip;
                   9690: 	$lonid_to_ip{$lonid} = $ip;
                   9691: 	return $ip;
                   9692:     }
1.847     albertel 9693:     
                   9694:     sub get_iphost {
1.869     albertel 9695: 	my ($ignore_cache) = @_;
1.894     albertel 9696: 
1.869     albertel 9697: 	if (!$ignore_cache) {
                   9698: 	    if (%iphost) {
                   9699: 		return %iphost;
                   9700: 	    }
                   9701: 	    my ($ip_info,$cached)=
                   9702: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   9703: 	    if ($cached) {
                   9704: 		%iphost      = %{$ip_info->[0]};
                   9705: 		%name_to_ip  = %{$ip_info->[1]};
                   9706: 		%lonid_to_ip = %{$ip_info->[2]};
                   9707: 		return %iphost;
                   9708: 	    }
                   9709: 	}
1.894     albertel 9710: 
                   9711: 	# get yesterday's info for fallback
                   9712: 	my %old_name_to_ip;
                   9713: 	my ($ip_info,$cached)=
                   9714: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   9715: 	if ($cached) {
                   9716: 	    %old_name_to_ip = %{$ip_info->[1]};
                   9717: 	}
                   9718: 
1.888     albertel 9719: 	my %name_to_host = &all_names();
                   9720: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 9721: 	    my $ip;
                   9722: 	    if (!exists($name_to_ip{$name})) {
                   9723: 		$ip = gethostbyname($name);
                   9724: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 9725: 		    if (defined($old_name_to_ip{$name})) {
                   9726: 			$ip = $old_name_to_ip{$name};
                   9727: 			&logthis("Can't find $name defaulting to old $ip");
                   9728: 		    } else {
                   9729: 			&logthis("Name $name no IP found");
                   9730: 			next;
                   9731: 		    }
                   9732: 		} else {
                   9733: 		    $ip=inet_ntoa($ip);
1.847     albertel 9734: 		}
                   9735: 		$name_to_ip{$name} = $ip;
                   9736: 	    } else {
                   9737: 		$ip = $name_to_ip{$name};
1.653     albertel 9738: 	    }
1.888     albertel 9739: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   9740: 		$lonid_to_ip{$id} = $ip;
                   9741: 	    }
                   9742: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 9743: 	}
1.869     albertel 9744: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   9745: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 9746: 				      48*60*60);
1.869     albertel 9747: 
1.847     albertel 9748: 	return %iphost;
1.598     albertel 9749:     }
                   9750: 
1.992     raeburn  9751:     #
                   9752:     #  Given a DNS returns the loncapa host name for that DNS 
                   9753:     # 
                   9754:     sub host_from_dns {
                   9755:         my ($dns) = @_;
                   9756:         my @hosts;
                   9757:         my $ip;
                   9758: 
1.993     raeburn  9759:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  9760:             $ip = $name_to_ip{$dns};
                   9761:         }
                   9762:         if (!$ip) {
                   9763:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   9764:             if (length($ip) == 4) { 
                   9765: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   9766:             }
                   9767:         }
                   9768:         if ($ip) {
                   9769: 	    @hosts = get_hosts_from_ip($ip);
                   9770: 	    return $hosts[0];
                   9771:         }
                   9772:         return undef;
1.986     foxr     9773:     }
1.992     raeburn  9774: 
1.986     foxr     9775: }
                   9776: 
1.862     albertel 9777: BEGIN {
                   9778: 
                   9779: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   9780:     unless ($readit) {
                   9781: {
                   9782:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   9783:     %perlvar = (%perlvar,%{$configvars});
                   9784: }
                   9785: 
                   9786: 
1.1       albertel 9787: # ------------------------------------------------------ Read spare server file
                   9788: {
1.448     albertel 9789:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 9790: 
                   9791:     while (my $configline=<$config>) {
                   9792:        chomp($configline);
1.284     matthew  9793:        if ($configline) {
1.784     albertel 9794: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9795: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9796: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9797:        }
                   9798:     }
1.448     albertel 9799:     close($config);
1.1       albertel 9800: }
1.11      www      9801: # ------------------------------------------------------------ Read permissions
                   9802: {
1.448     albertel 9803:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9804: 
                   9805:     while (my $configline=<$config>) {
1.448     albertel 9806: 	chomp($configline);
                   9807: 	if ($configline) {
                   9808: 	    my ($role,$perm)=split(/ /,$configline);
                   9809: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9810: 	}
1.11      www      9811:     }
1.448     albertel 9812:     close($config);
1.11      www      9813: }
                   9814: 
                   9815: # -------------------------------------------- Read plain texts for permissions
                   9816: {
1.448     albertel 9817:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9818: 
                   9819:     while (my $configline=<$config>) {
1.448     albertel 9820: 	chomp($configline);
                   9821: 	if ($configline) {
1.742     raeburn  9822: 	    my ($short,@plain)=split(/:/,$configline);
                   9823:             %{$prp{$short}} = ();
                   9824: 	    if (@plain > 0) {
                   9825:                 $prp{$short}{'std'} = $plain[0];
                   9826:                 for (my $i=1; $i<@plain; $i++) {
                   9827:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9828:                 }
                   9829:             }
1.448     albertel 9830: 	}
1.135     www      9831:     }
1.448     albertel 9832:     close($config);
1.135     www      9833: }
                   9834: 
                   9835: # ---------------------------------------------------------- Read package table
                   9836: {
1.448     albertel 9837:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9838: 
                   9839:     while (my $configline=<$config>) {
1.483     albertel 9840: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9841: 	chomp($configline);
                   9842: 	my ($short,$plain)=split(/:/,$configline);
                   9843: 	my ($pack,$name)=split(/\&/,$short);
                   9844: 	if ($plain ne '') {
                   9845: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9846: 	    $packagetab{$short}=$plain; 
                   9847: 	}
1.11      www      9848:     }
1.448     albertel 9849:     close($config);
1.329     matthew  9850: }
                   9851: 
                   9852: # ------------- set up temporary directory
                   9853: {
                   9854:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9855: 
1.11      www      9856: }
                   9857: 
1.794     albertel 9858: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9859: 				'compress_threshold'=> 20_000,
                   9860:  			        });
1.185     www      9861: 
1.281     www      9862: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9863: $dumpcount=0;
1.958     www      9864: $locknum=0;
1.22      www      9865: 
1.163     harris41 9866: &logtouch();
1.672     albertel 9867: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9868: $readit=1;
1.564     albertel 9869:     {
                   9870: 	use integer;
                   9871: 	my $test=(2**32)+1;
1.568     albertel 9872: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9873: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9874:     }
1.195     www      9875: }
1.1       albertel 9876: }
1.179     www      9877: 
1.1       albertel 9878: 1;
1.191     harris41 9879: __END__
                   9880: 
1.243     albertel 9881: =pod
                   9882: 
1.191     harris41 9883: =head1 NAME
                   9884: 
1.243     albertel 9885: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9886: 
                   9887: =head1 SYNOPSIS
                   9888: 
1.243     albertel 9889: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9890: 
                   9891:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9892: 
1.243     albertel 9893: Common parameters:
                   9894: 
                   9895: =over 4
                   9896: 
                   9897: =item *
                   9898: 
                   9899: $uname : an internal username (if $cname expecting a course Id specifically)
                   9900: 
                   9901: =item *
                   9902: 
                   9903: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9904: 
                   9905: =item *
                   9906: 
                   9907: $symb : a resource instance identifier
                   9908: 
                   9909: =item *
                   9910: 
                   9911: $namespace : the name of a .db file that contains the data needed or
                   9912: being set.
                   9913: 
                   9914: =back
                   9915: 
1.394     bowersj2 9916: =head1 OVERVIEW
1.191     harris41 9917: 
1.394     bowersj2 9918: lonnet provides subroutines which interact with the
                   9919: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9920: about classes, users, and resources.
1.243     albertel 9921: 
                   9922: For many of these objects you can also use this to store data about
                   9923: them or modify them in various ways.
1.191     harris41 9924: 
1.394     bowersj2 9925: =head2 Symbs
1.191     harris41 9926: 
1.394     bowersj2 9927: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9928: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9929: map, the resource number of the resource in the map, and the URL of
                   9930: the resource itself. The latter is somewhat redundant, but might help
                   9931: if maps change.
                   9932: 
                   9933: An example is
                   9934: 
                   9935:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9936: 
                   9937: The respective map entry is
                   9938: 
                   9939:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9940:   title="Problem 2">
                   9941:  </resource>
                   9942: 
                   9943: Symbs are used by the random number generator, as well as to store and
                   9944: restore data specific to a certain instance of for example a problem.
                   9945: 
                   9946: =head2 Storing And Retrieving Data
                   9947: 
                   9948: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9949: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9950: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9951: is is the non-critical message twin of cstore. These functions are for
                   9952: handlers to store a perl hash to a user's permanent data space in an
                   9953: easy manner, and to retrieve it again on another call. It is expected
                   9954: that a handler would use this once at the beginning to retrieve data,
                   9955: and then again once at the end to send only the new data back.
                   9956: 
                   9957: The data is stored in the user's data directory on the user's
                   9958: homeserver under the ID of the course.
                   9959: 
                   9960: The hash that is returned by restore will have all of the previous
                   9961: value for all of the elements of the hash.
                   9962: 
                   9963: Example:
                   9964: 
                   9965:  #creating a hash
                   9966:  my %hash;
                   9967:  $hash{'foo'}='bar';
                   9968: 
                   9969:  #storing it
                   9970:  &Apache::lonnet::cstore(\%hash);
                   9971: 
                   9972:  #changing a value
                   9973:  $hash{'foo'}='notbar';
                   9974: 
                   9975:  #adding a new value
                   9976:  $hash{'bar'}='foo';
                   9977:  &Apache::lonnet::cstore(\%hash);
                   9978: 
                   9979:  #retrieving the hash
                   9980:  my %history=&Apache::lonnet::restore();
                   9981: 
                   9982:  #print the hash
                   9983:  foreach my $key (sort(keys(%history))) {
                   9984:    print("\%history{$key} = $history{$key}");
                   9985:  }
                   9986: 
                   9987: Will print out:
1.191     harris41 9988: 
1.394     bowersj2 9989:  %history{1:foo} = bar
                   9990:  %history{1:keys} = foo:timestamp
                   9991:  %history{1:timestamp} = 990455579
                   9992:  %history{2:bar} = foo
                   9993:  %history{2:foo} = notbar
                   9994:  %history{2:keys} = foo:bar:timestamp
                   9995:  %history{2:timestamp} = 990455580
                   9996:  %history{bar} = foo
                   9997:  %history{foo} = notbar
                   9998:  %history{timestamp} = 990455580
                   9999:  %history{version} = 2
                   10000: 
                   10001: Note that the special hash entries C<keys>, C<version> and
                   10002: C<timestamp> were added to the hash. C<version> will be equal to the
                   10003: total number of versions of the data that have been stored. The
                   10004: C<timestamp> attribute will be the UNIX time the hash was
                   10005: stored. C<keys> is available in every historical section to list which
                   10006: keys were added or changed at a specific historical revision of a
                   10007: hash.
                   10008: 
                   10009: B<Warning>: do not store the hash that restore returns directly. This
                   10010: will cause a mess since it will restore the historical keys as if the
                   10011: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 10012: 
1.394     bowersj2 10013: Calling convention:
1.191     harris41 10014: 
1.394     bowersj2 10015:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   10016:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 10017: 
1.394     bowersj2 10018: For more detailed information, see lonnet specific documentation.
1.191     harris41 10019: 
1.394     bowersj2 10020: =head1 RETURN MESSAGES
1.191     harris41 10021: 
1.394     bowersj2 10022: =over 4
1.191     harris41 10023: 
1.394     bowersj2 10024: =item * B<con_lost>: unable to contact remote host
1.191     harris41 10025: 
1.394     bowersj2 10026: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   10027: when the connection is brought back up
1.191     harris41 10028: 
1.394     bowersj2 10029: =item * B<con_failed>: unable to contact remote host and unable to save message
                   10030: for later delivery
1.191     harris41 10031: 
1.967     bisitz   10032: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 10033: 
1.394     bowersj2 10034: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 10035: that was requested
1.191     harris41 10036: 
1.243     albertel 10037: =back
1.191     harris41 10038: 
1.243     albertel 10039: =head1 PUBLIC SUBROUTINES
1.191     harris41 10040: 
1.243     albertel 10041: =head2 Session Environment Functions
1.191     harris41 10042: 
1.243     albertel 10043: =over 4
1.191     harris41 10044: 
1.394     bowersj2 10045: =item * 
                   10046: X<appenv()>
1.949     raeburn  10047: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 10048: the user envirnoment file, and will be restored for each access this
1.620     albertel 10049: user makes during this session, also modifies the %env for the current
1.949     raeburn  10050: process. Optional rolesarrayref - if defined contains a reference to an array
                   10051: of roles which are exempt from the restriction on modifying user.role entries 
                   10052: in the user's environment.db and in %env.    
1.191     harris41 10053: 
                   10054: =item *
1.394     bowersj2 10055: X<delenv()>
1.987     raeburn  10056: B<delenv($delthis,$regexp)>: removes all items from the session
                   10057: environment file that begin with $delthis. If the 
                   10058: optional second arg - $regexp - is true, $delthis is treated as a 
                   10059: regular expression, otherwise \Q$delthis\E is used. 
                   10060: The values are also deleted from the current processes %env.
1.191     harris41 10061: 
1.795     albertel 10062: =item * get_env_multiple($name) 
                   10063: 
                   10064: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   10065: values may be defined and end up as an array ref.
                   10066: 
                   10067: returns an array of values
                   10068: 
1.243     albertel 10069: =back
                   10070: 
                   10071: =head2 User Information
1.191     harris41 10072: 
1.243     albertel 10073: =over 4
1.191     harris41 10074: 
                   10075: =item *
1.394     bowersj2 10076: X<queryauthenticate()>
                   10077: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 10078: authentication scheme
                   10079: 
                   10080: =item *
1.394     bowersj2 10081: X<authenticate()>
                   10082: B<authenticate($uname,$upass,$udom)>: try to
                   10083: authenticate user from domain's lib servers (first use the current
                   10084: one). C<$upass> should be the users password.
1.191     harris41 10085: 
                   10086: =item *
1.394     bowersj2 10087: X<homeserver()>
                   10088: B<homeserver($uname,$udom)>: find the server which has
                   10089: the user's directory and files (there must be only one), this caches
                   10090: the answer, and also caches if there is a borken connection.
1.191     harris41 10091: 
                   10092: =item *
1.394     bowersj2 10093: X<idget()>
                   10094: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   10095: (IDs are a unique resource in a domain, there must be only 1 ID per
                   10096: username, and only 1 username per ID in a specific domain) (returns
                   10097: hash: id=>name,id=>name)
1.191     harris41 10098: 
                   10099: =item *
1.394     bowersj2 10100: X<idrget()>
                   10101: B<idrget($udom,@unames)>: find the IDs behind a list of
                   10102: usernames (returns hash: name=>id,name=>id)
1.191     harris41 10103: 
                   10104: =item *
1.394     bowersj2 10105: X<idput()>
                   10106: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 10107: 
                   10108: =item *
1.394     bowersj2 10109: X<rolesinit()>
                   10110: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 10111: 
                   10112: =item *
1.551     albertel 10113: X<getsection()>
                   10114: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 10115: course $cname, return section name/number or '' for "not in course"
                   10116: and '-1' for "no section"
                   10117: 
                   10118: =item *
1.394     bowersj2 10119: X<userenvironment()>
                   10120: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 10121: passed in @what from the requested user's environment, returns a hash
                   10122: 
1.858     raeburn  10123: =item * 
                   10124: X<userlog_query()>
1.859     albertel 10125: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   10126: activity.log file. %filters defines filters applied when parsing the
                   10127: log file. These can be start or end timestamps, or the type of action
                   10128: - log to look for Login or Logout events, check for Checkin or
                   10129: Checkout, role for role selection. The response is in the form
                   10130: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   10131: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  10132: 
1.243     albertel 10133: =back
                   10134: 
                   10135: =head2 User Roles
                   10136: 
                   10137: =over 4
                   10138: 
                   10139: =item *
                   10140: 
1.810     raeburn  10141: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 10142:  F: full access
                   10143:  U,I,K: authentication modes (cxx only)
                   10144:  '': forbidden
                   10145:  1: user needs to choose course
                   10146:  2: browse allowed
1.766     albertel 10147:  A: passphrase authentication needed
1.243     albertel 10148: 
                   10149: =item *
                   10150: 
                   10151: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   10152: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   10153: and course level
                   10154: 
                   10155: =item *
                   10156: 
1.988     raeburn  10157: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   10158: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  10159: $type is Course (default) or Community.
1.988     raeburn  10160: If $forcedefault evaluates to true, text returned will be default 
                   10161: text for $type. Otherwise, if this is a course, the text returned 
                   10162: will be a custom name for the role (if defined in the course's 
                   10163: environment).  If no custom name is defined the default is returned.
                   10164:    
1.832     raeburn  10165: =item *
                   10166: 
1.935     raeburn  10167: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  10168: All arguments are optional. Returns a hash of a roles, either for
                   10169: co-author/assistant author roles for a user's Construction Space
1.906     albertel 10170: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  10171: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   10172: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   10173: For each key, value is set to colon-separated start and end times for
                   10174: the role.  If no username and domain are specified, will default to
1.934     raeburn  10175: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  10176: of role statuses (active, future or previous), roles 
                   10177: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   10178: to restrict the list of roles reported. If no array ref is 
                   10179: provided for types, will default to return only active roles.
1.834     albertel 10180: 
1.243     albertel 10181: =back
                   10182: 
                   10183: =head2 User Modification
                   10184: 
                   10185: =over 4
                   10186: 
                   10187: =item *
                   10188: 
1.957     raeburn  10189: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 10190: user for the level given by URL.  Optional start and end dates (leave empty
                   10191: string or zero for "no date")
1.191     harris41 10192: 
                   10193: =item *
                   10194: 
1.243     albertel 10195: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   10196: change a users, password, possible return values are: ok,
                   10197: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   10198: refused
1.191     harris41 10199: 
                   10200: =item *
                   10201: 
1.243     albertel 10202: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 10203: 
                   10204: =item *
                   10205: 
1.963     raeburn  10206: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   10207:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 10208: modify user
1.191     harris41 10209: 
                   10210: =item *
                   10211: 
1.286     matthew  10212: modifystudent
                   10213: 
1.957     raeburn  10214: modify a student's enrollment and identification information.
1.286     matthew  10215: The course id is resolved based on the current users environment.  
                   10216: This means the envoking user must be a course coordinator or otherwise
                   10217: associated with a course.
                   10218: 
1.297     matthew  10219: This call is essentially a wrapper for lonnet::modifyuser and
                   10220: lonnet::modify_student_enrollment
1.286     matthew  10221: 
                   10222: Inputs: 
                   10223: 
                   10224: =over 4
                   10225: 
1.957     raeburn  10226: =item B<$udom> Student's loncapa domain
1.286     matthew  10227: 
1.957     raeburn  10228: =item B<$uname> Student's loncapa login name
1.286     matthew  10229: 
1.964     bisitz   10230: =item B<$uid> Student/Employee ID
1.286     matthew  10231: 
1.957     raeburn  10232: =item B<$umode> Student's authentication mode
1.286     matthew  10233: 
1.957     raeburn  10234: =item B<$upass> Student's password
1.286     matthew  10235: 
1.957     raeburn  10236: =item B<$first> Student's first name
1.286     matthew  10237: 
1.957     raeburn  10238: =item B<$middle> Student's middle name
1.286     matthew  10239: 
1.957     raeburn  10240: =item B<$last> Student's last name
1.286     matthew  10241: 
1.957     raeburn  10242: =item B<$gene> Student's generation
1.286     matthew  10243: 
1.957     raeburn  10244: =item B<$usec> Student's section in course
1.286     matthew  10245: 
                   10246: =item B<$end> Unix time of the roles expiration
                   10247: 
                   10248: =item B<$start> Unix time of the roles start date
                   10249: 
                   10250: =item B<$forceid> If defined, allow $uid to be changed
                   10251: 
                   10252: =item B<$desiredhome> server to use as home server for student
                   10253: 
1.957     raeburn  10254: =item B<$email> Student's permanent e-mail address
                   10255: 
                   10256: =item B<$type> Type of enrollment (auto or manual)
                   10257: 
1.963     raeburn  10258: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   10259: 
                   10260: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  10261: 
1.963     raeburn  10262: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  10263: 
1.963     raeburn  10264: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  10265: 
1.963     raeburn  10266: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  10267: 
1.286     matthew  10268: =back
1.297     matthew  10269: 
                   10270: =item *
                   10271: 
                   10272: modify_student_enrollment
                   10273: 
                   10274: Change a students enrollment status in a class.  The environment variable
                   10275: 'role.request.course' must be defined for this function to proceed.
                   10276: 
                   10277: Inputs:
                   10278: 
                   10279: =over 4
                   10280: 
                   10281: =item $udom, students domain
                   10282: 
                   10283: =item $uname, students name
                   10284: 
                   10285: =item $uid, students user id
                   10286: 
                   10287: =item $first, students first name
                   10288: 
                   10289: =item $middle
                   10290: 
                   10291: =item $last
                   10292: 
                   10293: =item $gene
                   10294: 
                   10295: =item $usec
                   10296: 
                   10297: =item $end
                   10298: 
                   10299: =item $start
                   10300: 
1.957     raeburn  10301: =item $type
                   10302: 
                   10303: =item $locktype
                   10304: 
                   10305: =item $cid
                   10306: 
                   10307: =item $selfenroll
                   10308: 
                   10309: =item $context
                   10310: 
1.297     matthew  10311: =back
                   10312: 
1.191     harris41 10313: 
                   10314: =item *
                   10315: 
1.243     albertel 10316: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   10317: custom role; give a custom role to a user for the level given by URL.  Specify
                   10318: name and domain of role author, and role name
1.191     harris41 10319: 
                   10320: =item *
                   10321: 
1.243     albertel 10322: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 10323: 
                   10324: =item *
                   10325: 
1.243     albertel 10326: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   10327: 
                   10328: =back
                   10329: 
                   10330: =head2 Course Infomation
                   10331: 
                   10332: =over 4
1.191     harris41 10333: 
                   10334: =item *
                   10335: 
1.631     albertel 10336: coursedescription($courseid) : returns a hash of information about the
                   10337: specified course id, including all environment settings for the
                   10338: course, the description of the course will be in the hash under the
                   10339: key 'description'
1.191     harris41 10340: 
                   10341: =item *
                   10342: 
1.624     albertel 10343: resdata($name,$domain,$type,@which) : request for current parameter
                   10344: setting for a specific $type, where $type is either 'course' or 'user',
                   10345: @what should be a list of parameters to ask about. This routine caches
                   10346: answers for 5 minutes.
1.243     albertel 10347: 
1.877     foxr     10348: =item *
                   10349: 
                   10350: get_courseresdata($courseid, $domain) : dump the entire course resource
                   10351: data base, returning a hash that is keyed by the resource name and has
                   10352: values that are the resource value.  I believe that the timestamps and
                   10353: versions are also returned.
                   10354: 
                   10355: 
1.243     albertel 10356: =back
                   10357: 
                   10358: =head2 Course Modification
                   10359: 
                   10360: =over 4
1.191     harris41 10361: 
                   10362: =item *
                   10363: 
1.243     albertel 10364: writecoursepref($courseid,%prefs) : write preferences (environment
                   10365: database) for a course
1.191     harris41 10366: 
                   10367: =item *
                   10368: 
1.1011    raeburn  10369: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   10370: 
                   10371: =item *
                   10372: 
1.1038    raeburn  10373: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 10374: 
                   10375: =back
                   10376: 
                   10377: =head2 Resource Subroutines
                   10378: 
                   10379: =over 4
1.191     harris41 10380: 
                   10381: =item *
                   10382: 
1.243     albertel 10383: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 10384: 
                   10385: =item *
                   10386: 
1.243     albertel 10387: repcopy($filename) : subscribes to the requested file, and attempts to
                   10388: replicate from the owning library server, Might return
1.607     raeburn  10389: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   10390: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 10391: resource. Expects the local filesystem pathname
                   10392: (/home/httpd/html/res/....)
                   10393: 
                   10394: =back
                   10395: 
                   10396: =head2 Resource Information
                   10397: 
                   10398: =over 4
1.191     harris41 10399: 
                   10400: =item *
                   10401: 
1.243     albertel 10402: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   10403: a vairety of different possible values, $varname should be a request
                   10404: string, and the other parameters can be used to specify who and what
                   10405: one is asking about.
                   10406: 
                   10407: Possible values for $varname are environment.lastname (or other item
                   10408: from the envirnment hash), user.name (or someother aspect about the
                   10409: user), resource.0.maxtries (or some other part and parameter of a
                   10410: resource)
1.204     albertel 10411: 
                   10412: =item *
                   10413: 
1.243     albertel 10414: directcondval($number) : get current value of a condition; reads from a state
                   10415: string
1.204     albertel 10416: 
                   10417: =item *
                   10418: 
1.243     albertel 10419: condval($condidx) : value of condition index based on state
1.204     albertel 10420: 
                   10421: =item *
                   10422: 
1.243     albertel 10423: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   10424: resource's metadata, $what should be either a specific key, or either
                   10425: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   10426: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   10427: 
                   10428: this function automatically caches all requests
1.191     harris41 10429: 
                   10430: =item *
                   10431: 
1.243     albertel 10432: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   10433: network of library servers; returns file handle of where SQL and regex results
                   10434: will be stored for query
1.191     harris41 10435: 
                   10436: =item *
                   10437: 
1.243     albertel 10438: symbread($filename) : return symbolic list entry (filename argument optional);
                   10439: returns the data handle
1.191     harris41 10440: 
                   10441: =item *
                   10442: 
1.243     albertel 10443: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 10444: a possible symb for the URL in $thisfn, and if is an encryypted
                   10445: resource that the user accessed using /enc/ returns a 1 on success, 0
                   10446: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 10447: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 10448: 
1.191     harris41 10449: 
                   10450: =item *
                   10451: 
1.243     albertel 10452: symbclean($symb) : removes versions numbers from a symb, returns the
                   10453: cleaned symb
1.191     harris41 10454: 
                   10455: =item *
                   10456: 
1.243     albertel 10457: is_on_map($uri) : checks if the $uri is somewhere on the current
                   10458: course map, user must be in a course for it to work.
1.191     harris41 10459: 
                   10460: =item *
                   10461: 
1.243     albertel 10462: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 10463: 
                   10464: =item *
                   10465: 
1.243     albertel 10466: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   10467: a random seed, all arguments are optional, if they aren't sent it uses the
                   10468: environment to derive them. Note: if symb isn't sent and it can't get one
                   10469: from &symbread it will use the current time as its return value
1.191     harris41 10470: 
                   10471: =item *
                   10472: 
1.243     albertel 10473: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   10474: unfakeable, receipt
1.191     harris41 10475: 
                   10476: =item *
                   10477: 
1.620     albertel 10478: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 10479: 
                   10480: =item *
                   10481: 
1.243     albertel 10482: countacc($url) : count the number of accesses to a given URL
1.191     harris41 10483: 
                   10484: =item *
                   10485: 
1.243     albertel 10486: checkout($symb,$tuname,$tudom,$tcrsid) :  creates a record of a user having looked at an item, most likely printed out or otherwise using a resource
1.191     harris41 10487: 
                   10488: =item *
                   10489: 
1.243     albertel 10490: checkin($token) : updates that a resource has beeen returned (a hard copy version for instance) and returns the data that $token was Checkout with ($symb, $tuname, $tudom, and $tcrsid)
1.191     harris41 10491: 
                   10492: =item *
                   10493: 
1.243     albertel 10494: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 10495: 
                   10496: =item *
                   10497: 
1.243     albertel 10498: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   10499: forcing spreadsheet to reevaluate the resource scores next time.
                   10500: 
                   10501: =back
                   10502: 
                   10503: =head2 Storing/Retreiving Data
                   10504: 
                   10505: =over 4
1.191     harris41 10506: 
                   10507: =item *
                   10508: 
1.243     albertel 10509: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   10510: for this url; hashref needs to be given and should be a \%hashname; the
                   10511: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 10512: be derived from the env
1.191     harris41 10513: 
                   10514: =item *
                   10515: 
1.243     albertel 10516: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   10517: uses critical subroutine
1.191     harris41 10518: 
                   10519: =item *
                   10520: 
1.243     albertel 10521: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   10522: all args are optional
1.191     harris41 10523: 
                   10524: =item *
                   10525: 
1.717     albertel 10526: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   10527: dumps the complete (or key matching regexp) namespace into a hash
                   10528: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   10529: normally &store()ed into
                   10530: 
                   10531: $range should be either an integer '100' (give me the first 100
                   10532:                                            matching records)
                   10533:               or be  two integers sperated by a - with no spaces
                   10534:                  '30-50' (give me the 30th through the 50th matching
                   10535:                           records)
                   10536: 
                   10537: 
                   10538: =item *
                   10539: 
                   10540: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   10541: replaces a &store() version of data with a replacement set of data
                   10542: for a particular resource in a namespace passed in the $storehash hash 
                   10543: reference
                   10544: 
                   10545: =item *
                   10546: 
1.243     albertel 10547: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   10548: works very similar to store/cstore, but all data is stored in a
                   10549: temporary location and can be reset using tmpreset, $storehash should
                   10550: be a hash reference, returns nothing on success
1.191     harris41 10551: 
                   10552: =item *
                   10553: 
1.243     albertel 10554: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   10555: similar to restore, but all data is stored in a temporary location and
                   10556: can be reset using tmpreset. Returns a hash of values on success,
                   10557: error string otherwise.
1.191     harris41 10558: 
                   10559: =item *
                   10560: 
1.243     albertel 10561: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   10562: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 10563: 
                   10564: =item *
                   10565: 
1.243     albertel 10566: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10567: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 10568: 
                   10569: =item *
                   10570: 
1.243     albertel 10571: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   10572: namesp ($udom and $uname are optional)
1.191     harris41 10573: 
                   10574: =item *
                   10575: 
1.702     albertel 10576: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 10577: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 10578: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  10579: 
1.702     albertel 10580: $range should be either an integer '100' (give me the first 100
                   10581:                                            matching records)
                   10582:               or be  two integers sperated by a - with no spaces
                   10583:                  '30-50' (give me the 30th through the 50th matching
                   10584:                           records)
1.449     matthew  10585: =item *
                   10586: 
                   10587: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   10588: $store can be a scalar, an array reference, or if the amount to be 
                   10589: incremented is > 1, a hash reference.
                   10590: 
                   10591: ($udom and $uname are optional)
1.191     harris41 10592: 
                   10593: =item *
                   10594: 
1.243     albertel 10595: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   10596: ($udom and $uname are optional)
1.191     harris41 10597: 
                   10598: =item *
                   10599: 
1.243     albertel 10600: cput($namespace,$storehash,$udom,$uname) : critical put
                   10601: ($udom and $uname are optional)
1.191     harris41 10602: 
                   10603: =item *
                   10604: 
1.748     albertel 10605: newput($namespace,$storehash,$udom,$uname) :
                   10606: 
                   10607: Attempts to store the items in the $storehash, but only if they don't
                   10608: currently exist, if this succeeds you can be certain that you have 
                   10609: successfully created a new key value pair in the $namespace db.
                   10610: 
                   10611: 
                   10612: Args:
                   10613:  $namespace: name of database to store values to
                   10614:  $storehash: hashref to store to the db
                   10615:  $udom: (optional) domain of user containing the db
                   10616:  $uname: (optional) name of user caontaining the db
                   10617: 
                   10618: Returns:
                   10619:  'ok' -> succeeded in storing all keys of $storehash
                   10620:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   10621:                         least <key> already existed in the db (other
                   10622:                         requested keys may also already exist)
1.967     bisitz   10623:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 10624:  'con_lost' -> unable to contact request server
                   10625:  'refused' -> action was not allowed by remote machine
                   10626: 
                   10627: 
                   10628: =item *
                   10629: 
1.243     albertel 10630: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   10631: reference filled in from namesp (encrypts the return communication)
                   10632: ($udom and $uname are optional)
1.191     harris41 10633: 
                   10634: =item *
                   10635: 
1.243     albertel 10636: log($udom,$name,$home,$message) : write to permanent log for user; use
                   10637: critical subroutine
                   10638: 
1.806     raeburn  10639: =item *
                   10640: 
1.860     raeburn  10641: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   10642: array reference filled in from namespace found in domain level on either
                   10643: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  10644: 
                   10645: =item *
                   10646: 
1.860     raeburn  10647: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   10648: domain level either on specified domain server ($uhome) or primary domain 
                   10649: server ($udom and $uhome are optional)
1.806     raeburn  10650: 
1.943     raeburn  10651: =item * 
                   10652: 
                   10653: get_domain_defaults($target_domain) : returns hash with defaults for
                   10654: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   10655: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   10656: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   10657: Values are retrieved from cache (if current), or from domain's configuration.db
                   10658: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   10659: or lonTabs/domain.tab. 
                   10660: 
                   10661: %domdefaults = &get_auth_defaults($target_domain);
                   10662: 
1.243     albertel 10663: =back
                   10664: 
                   10665: =head2 Network Status Functions
                   10666: 
                   10667: =over 4
1.191     harris41 10668: 
                   10669: =item *
                   10670: 
                   10671: dirlist($uri) : return directory list based on URI
                   10672: 
                   10673: =item *
                   10674: 
1.243     albertel 10675: spareserver() : find server with least workload from spare.tab
                   10676: 
1.986     foxr     10677: 
                   10678: =item *
                   10679: 
                   10680: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   10681: if there is no corresponding loncapa host.
                   10682: 
1.243     albertel 10683: =back
                   10684: 
1.986     foxr     10685: 
1.243     albertel 10686: =head2 Apache Request
                   10687: 
                   10688: =over 4
1.191     harris41 10689: 
                   10690: =item *
                   10691: 
1.243     albertel 10692: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   10693: localhost, posts hash
                   10694: 
                   10695: =back
                   10696: 
                   10697: =head2 Data to String to Data
                   10698: 
                   10699: =over 4
1.191     harris41 10700: 
                   10701: =item *
                   10702: 
1.243     albertel 10703: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   10704: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 10705: 
                   10706: =item *
                   10707: 
1.243     albertel 10708: hashref2str($hashref) : convert a hashref into a string complete with
                   10709: escaping and '=' and '&' separators, supports elements that are
                   10710: arrayrefs and hashrefs
1.191     harris41 10711: 
                   10712: =item *
                   10713: 
1.243     albertel 10714: arrayref2str($arrayref) : convert an arrayref into a string complete
                   10715: with escaping and '&' separators, supports elements that are arrayrefs
                   10716: and hashrefs
1.191     harris41 10717: 
                   10718: =item *
                   10719: 
1.243     albertel 10720: str2hash($string) : convert string to hash using unescaping and
                   10721: splitting on '=' and '&', supports elements that are arrayrefs and
                   10722: hashrefs
1.191     harris41 10723: 
                   10724: =item *
                   10725: 
1.243     albertel 10726: str2array($string) : convert string to hash using unescaping and
                   10727: splitting on '&', supports elements that are arrayrefs and hashrefs
                   10728: 
                   10729: =back
                   10730: 
                   10731: =head2 Logging Routines
                   10732: 
                   10733: =over 4
                   10734: 
                   10735: These routines allow one to make log messages in the lonnet.log and
                   10736: lonnet.perm logfiles.
1.191     harris41 10737: 
                   10738: =item *
                   10739: 
1.243     albertel 10740: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 10741: 
                   10742: =item *
                   10743: 
1.243     albertel 10744: logthis() : append message to the normal lonnet.log file, it gets
                   10745: preiodically rolled over and deleted.
1.191     harris41 10746: 
                   10747: =item *
                   10748: 
1.243     albertel 10749: logperm() : append a permanent message to lonnet.perm.log, this log
                   10750: file never gets deleted by any automated portion of the system, only
                   10751: messages of critical importance should go in here.
                   10752: 
                   10753: =back
                   10754: 
                   10755: =head2 General File Helper Routines
                   10756: 
                   10757: =over 4
1.191     harris41 10758: 
                   10759: =item *
                   10760: 
1.481     raeburn  10761: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   10762: (a) files in /uploaded
                   10763:   (i) If a local copy of the file exists - 
                   10764:       compares modification date of local copy with last-modified date for 
                   10765:       definitive version stored on home server for course. If local copy is 
                   10766:       stale, requests a new version from the home server and stores it. 
                   10767:       If the original has been removed from the home server, then local copy 
                   10768:       is unlinked.
                   10769:   (ii) If local copy does not exist -
                   10770:       requests the file from the home server and stores it. 
                   10771:   
                   10772:   If $caller is 'uploadrep':  
                   10773:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   10774:     for request for files originally uploaded via DOCS. 
                   10775:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   10776:   
                   10777:   Otherwise:
                   10778:      This indicates a call from the content generation phase of the request.
                   10779:      -  returns the entire contents of the file or -1.
                   10780:      
                   10781: (b) files in /res
                   10782:    - returns the entire contents of a file or -1; 
                   10783:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 10784: 
1.712     albertel 10785: 
                   10786: =item *
                   10787: 
                   10788: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   10789:                   reference
                   10790: 
                   10791: returns either a stat() list of data about the file or an empty list
                   10792: if the file doesn't exist or couldn't find out about it (connection
                   10793: problems or user unknown)
                   10794: 
1.191     harris41 10795: =item *
                   10796: 
1.243     albertel 10797: filelocation($dir,$file) : returns file system location of a file
                   10798: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   10799: directory that relative $file lookups are to looked in ($dir of /a/dir
                   10800: and a file of ../bob will become /a/bob)
1.191     harris41 10801: 
                   10802: =item *
                   10803: 
                   10804: hreflocation($dir,$file) : returns file system location or a URL; same as
                   10805: filelocation except for hrefs
                   10806: 
                   10807: =item *
                   10808: 
                   10809: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   10810: 
1.243     albertel 10811: =back
                   10812: 
1.608     albertel 10813: =head2 Usererfile file routines (/uploaded*)
                   10814: 
                   10815: =over 4
                   10816: 
                   10817: =item *
                   10818: 
                   10819: userfileupload(): main rotine for putting a file in a user or course's
                   10820:                   filespace, arguments are,
                   10821: 
1.620     albertel 10822:  formname - required - this is the name of the element in $env where the
1.608     albertel 10823:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10824:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10825:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10826:  coursedoc - if true, store the file in the course of the active role
                   10827:              of the current user
                   10828:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10829:          if undefined, it will be placed in "unknown"
                   10830: 
                   10831:  (This routine calls clean_filename() to remove any dangerous
                   10832:  characters from the filename, and then calls finuserfileupload() to
                   10833:  complete the transaction)
                   10834: 
                   10835:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10836:  and /adm/notfound.html if unsuccessful
                   10837: 
                   10838: =item *
                   10839: 
                   10840: clean_filename(): routine for cleaing a filename up for storage in
                   10841:                  userfile space, argument is:
                   10842: 
                   10843:  filename - proposed filename
                   10844: 
                   10845: returns: the new clean filename
                   10846: 
                   10847: =item *
                   10848: 
                   10849: finishuserfileupload(): routine that creaes and sends the file to
                   10850: userspace, probably shouldn't be called directly
                   10851: 
                   10852:   docuname: username or courseid of destination for the file
                   10853:   docudom: domain of user/course of destination for the file
                   10854:   formname: same as for userfileupload()
                   10855:   fname: filename (inculding subdirectories) for the file
                   10856: 
                   10857:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10858:  and /adm/notfound.html if unsuccessful
                   10859: 
                   10860: =item *
                   10861: 
                   10862: renameuserfile(): renames an existing userfile to a new name
                   10863: 
                   10864:   Args:
                   10865:    docuname: username or courseid of destination for the file
                   10866:    docudom: domain of user/course of destination for the file
                   10867:    old: current file name (including any subdirs under userfiles)
                   10868:    new: desired file name (including any subdirs under userfiles)
                   10869: 
                   10870: =item *
                   10871: 
                   10872: mkdiruserfile(): creates a directory is a userfiles dir
                   10873: 
                   10874:   Args:
                   10875:    docuname: username or courseid of destination for the file
                   10876:    docudom: domain of user/course of destination for the file
                   10877:    dir: dir to create (including any subdirs under userfiles)
                   10878: 
                   10879: =item *
                   10880: 
                   10881: removeuserfile(): removes a file that exists in userfiles
                   10882: 
                   10883:   Args:
                   10884:    docuname: username or courseid of destination for the file
                   10885:    docudom: domain of user/course of destination for the file
                   10886:    fname: filname to delete (including any subdirs under userfiles)
                   10887: 
                   10888: =item *
                   10889: 
                   10890: removeuploadedurl(): convience function for removeuserfile()
                   10891: 
                   10892:   Args:
                   10893:    url:  a full /uploaded/... url to delete
                   10894: 
1.747     albertel 10895: =item * 
                   10896: 
                   10897: get_portfile_permissions():
                   10898:   Args:
                   10899:     domain: domain of user or course contain the portfolio files
                   10900:     user: name of user or num of course contain the portfolio files
                   10901:   Returns:
                   10902:     hashref of a dump of the proper file_permissions.db
                   10903:    
                   10904: 
                   10905: =item * 
                   10906: 
                   10907: get_access_controls():
                   10908: 
                   10909: Args:
                   10910:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10911:   group: (optional) the group you want the files associated with
                   10912:   file: (optional) the file you want access info on
                   10913: 
                   10914: Returns:
1.749     raeburn  10915:     a hash (keys are file names) of hashes containing
                   10916:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10917:         values are XML containing access control settings (see below) 
1.747     albertel 10918: 
                   10919: Internal notes:
                   10920: 
1.749     raeburn  10921:  access controls are stored in file_permissions.db as key=value pairs.
                   10922:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10923:         where scope -> public,guest,course,group,domains or users.
                   10924:               end -> UNIX time for end of access (0 -> no end date)
                   10925:               start -> UNIX time for start of access
                   10926: 
                   10927:     value -> XML description of access control
                   10928:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10929:             <start></start>
                   10930:             <end></end>
                   10931: 
                   10932:             <password></password>  for scope type = guest
                   10933: 
                   10934:             <domain></domain>     for scope type = course or group
                   10935:             <number></number>
                   10936:             <roles id="">
                   10937:              <role></role>
                   10938:              <access></access>
                   10939:              <section></section>
                   10940:              <group></group>
                   10941:             </roles>
                   10942: 
                   10943:             <dom></dom>         for scope type = domains
                   10944: 
                   10945:             <users>             for scope type = users
                   10946:              <user>
                   10947:               <uname></uname>
                   10948:               <udom></udom>
                   10949:              </user>
                   10950:             </users>
                   10951:            </scope> 
                   10952:               
                   10953:  Access data is also aggregated for each file in an additional key=value pair:
                   10954:  key -> path to file/file_name\0accesscontrol 
                   10955:  value -> reference to hash
                   10956:           hash contains key = value pairs
                   10957:           where key = uniqueID:scope_end_start
                   10958:                 value = UNIX time record was last updated
                   10959: 
                   10960:           Used to improve speed of look-ups of access controls for each file.  
                   10961:  
                   10962:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10963: 
                   10964: modify_access_controls():
                   10965: 
                   10966: Modifies access controls for a portfolio file
                   10967: Args
                   10968: 1. file name
                   10969: 2. reference to hash of required changes,
                   10970: 3. domain
                   10971: 4. username
                   10972:   where domain,username are the domain of the portfolio owner 
                   10973:   (either a user or a course) 
                   10974: 
                   10975: Returns:
                   10976: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10977: 2. result of deletions ('ok' or 'error', with error message).
                   10978: 3. reference to hash of any new or updated access controls.
                   10979: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10980:    key = integer (inbound ID)
                   10981:    value = uniqueID  
1.747     albertel 10982: 
1.608     albertel 10983: =back
                   10984: 
1.243     albertel 10985: =head2 HTTP Helper Routines
                   10986: 
                   10987: =over 4
                   10988: 
1.191     harris41 10989: =item *
                   10990: 
                   10991: escape() : unpack non-word characters into CGI-compatible hex codes
                   10992: 
                   10993: =item *
                   10994: 
                   10995: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10996: 
1.243     albertel 10997: =back
                   10998: 
                   10999: =head1 PRIVATE SUBROUTINES
                   11000: 
                   11001: =head2 Underlying communication routines (Shouldn't call)
                   11002: 
                   11003: =over 4
                   11004: 
                   11005: =item *
                   11006: 
                   11007: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   11008: 
                   11009: =item *
                   11010: 
                   11011: reply() : uses subreply to send a message to remote machine, logs all failures
                   11012: 
                   11013: =item *
                   11014: 
                   11015: critical() : passes a critical message to another server; if cannot
                   11016: get through then place message in connection buffer directory and
                   11017: returns con_delayed, if incapable of saving message, returns
                   11018: con_failed
                   11019: 
                   11020: =item *
                   11021: 
                   11022: reconlonc() : tries to reconnect lonc client processes.
                   11023: 
                   11024: =back
                   11025: 
                   11026: =head2 Resource Access Logging
                   11027: 
                   11028: =over 4
                   11029: 
                   11030: =item *
                   11031: 
                   11032: flushcourselogs() : flush (save) buffer logs and access logs
                   11033: 
                   11034: =item *
                   11035: 
                   11036: courselog($what) : save message for course in hash
                   11037: 
                   11038: =item *
                   11039: 
                   11040: courseacclog($what) : save message for course using &courselog().  Perform
                   11041: special processing for specific resource types (problems, exams, quizzes, etc).
                   11042: 
1.191     harris41 11043: =item *
                   11044: 
                   11045: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   11046: as a PerlChildExitHandler
1.243     albertel 11047: 
                   11048: =back
                   11049: 
                   11050: =head2 Other
                   11051: 
                   11052: =over 4
                   11053: 
                   11054: =item *
                   11055: 
                   11056: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 11057: 
                   11058: =back
                   11059: 
                   11060: =cut
1.877     foxr     11061: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>