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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.783   ! albertel    4: # $Id: lonnet.pm,v 1.782 2006/09/19 19:03:24 albertel 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.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599     albertel   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
1.740     www        55: use lib '/home/httpd/lib/perl';
                     56: use LONCAPA;
                     57: use LONCAPA::Configuration;
1.676     albertel   58: 
1.195     www        59: my $readit;
1.550     foxr       60: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   61: 
1.619     albertel   62: require Exporter;
                     63: 
                     64: our @ISA = qw (Exporter);
                     65: our @EXPORT = qw(%env);
                     66: 
1.449     matthew    67: =pod
                     68: 
                     69: =head1 Package Variables
                     70: 
                     71: These are largely undocumented, so if you decipher one please note it here.
                     72: 
                     73: =over 4
                     74: 
                     75: =item $processmarker
                     76: 
                     77: Contains the time this process was started and this servers host id.
                     78: 
                     79: =item $dumpcount
                     80: 
                     81: Counts the number of times a message log flush has been attempted (regardless
                     82: of success) by this process.  Used as part of the filename when messages are
                     83: delayed.
                     84: 
                     85: =back
                     86: 
                     87: =cut
                     88: 
                     89: 
1.1       albertel   90: # --------------------------------------------------------------------- Logging
1.729     www        91: {
                     92:     my $logid;
                     93:     sub instructor_log {
                     94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     95: 	$logid++;
                     96: 	my $id=time().'00000'.$$.'00000'.$logid;
                     97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        98: 				    { $id => {
                     99: 					'exe_uname' => $env{'user.name'},
                    100: 					'exe_udom'  => $env{'user.domain'},
                    101: 					'exe_time'  => time(),
                    102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    103: 					'delflag'   => $delflag,
                    104: 					'logentry'  => $storehash,
                    105: 					'uname'     => $uname,
                    106: 					'udom'      => $udom,
                    107: 				    }
                    108: 				  },
1.729     www       109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    111: 				    );
                    112:     }
                    113: }
1.1       albertel  114: 
1.163     harris41  115: sub logtouch {
                    116:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  117:     unless (-e "$execdir/logs/lonnet.log") {	
                    118: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  119: 	close $fh;
                    120:     }
                    121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    123: }
                    124: 
1.1       albertel  125: sub logthis {
                    126:     my $message=shift;
                    127:     my $execdir=$perlvar{'lonDaemons'};
                    128:     my $now=time;
                    129:     my $local=localtime($now);
1.448     albertel  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    131: 	print $fh "$local ($$): $message\n";
                    132: 	close($fh);
                    133:     }
1.1       albertel  134:     return 1;
                    135: }
                    136: 
                    137: sub logperm {
                    138:     my $message=shift;
                    139:     my $execdir=$perlvar{'lonDaemons'};
                    140:     my $now=time;
                    141:     my $local=localtime($now);
1.448     albertel  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    143: 	print $fh "$now:$message:$local\n";
                    144: 	close($fh);
                    145:     }
1.1       albertel  146:     return 1;
                    147: }
                    148: 
                    149: # -------------------------------------------------- Non-critical communication
                    150: sub subreply {
                    151:     my ($cmd,$server)=@_;
1.704     albertel  152:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      153:     #
                    154:     #  With loncnew process trimming, there's a timing hole between lonc server
                    155:     #  process exit and the master server picking up the listen on the AF_UNIX
                    156:     #  socket.  In that time interval, a lock file will exist:
                    157: 
                    158:     my $lockfile=$peerfile.".lock";
                    159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    160: 	sleep(1);
                    161:     }
                    162:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      163:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      164:     #
1.550     foxr      165:     #   We'll give the connection a few tries before abandoning it.  If
                    166:     #   connection is not possible, we'll con_lost back to the client.
                    167:     #   
                    168:     my $client;
                    169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    171: 				      Type    => SOCK_STREAM,
                    172: 				      Timeout => 10);
                    173: 	if($client) {
                    174: 	    last;		# Connected!
                    175: 	}
                    176: 	sleep(1);		# Try again later if failed connection.
                    177:     }
                    178:     my $answer;
                    179:     if ($client) {
1.704     albertel  180: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      181: 	$answer=<$client>;
                    182: 	if (!$answer) { $answer="con_lost"; }
                    183: 	chomp($answer);
                    184:     } else {
                    185: 	$answer = 'con_lost';	# Failed connection.
                    186:     }
1.1       albertel  187:     return $answer;
                    188: }
                    189: 
                    190: sub reply {
                    191:     my ($cmd,$server)=@_;
1.205     www       192:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  193:     my $answer=subreply($cmd,$server);
1.65      www       194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  195:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       196:                 " $cmd to $server returned $answer</font>");
                    197:     }
1.1       albertel  198:     return $answer;
                    199: }
                    200: 
                    201: # ----------------------------------------------------------- Send USR1 to lonc
                    202: 
                    203: sub reconlonc {
                    204:     my $peerfile=shift;
                    205:     &logthis("Trying to reconnect for $peerfile");
                    206:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  207:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  208: 	my $loncpid=<$fh>;
                    209:         chomp($loncpid);
                    210:         if (kill 0 => $loncpid) {
                    211: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    212:             kill USR1 => $loncpid;
                    213:             sleep 1;
                    214:             if (-e "$peerfile") { return; }
                    215:             &logthis("$peerfile still not there, give it another try");
                    216:             sleep 5;
                    217:             if (-e "$peerfile") { return; }
1.12      www       218:             &logthis(
1.672     albertel  219:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  220:         } else {
1.12      www       221: 	    &logthis(
1.672     albertel  222:                "<font color=\"blue\">WARNING:".
1.12      www       223:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  224:         }
                    225:     } else {
1.672     albertel  226:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  227:     }
                    228: }
                    229: 
                    230: # ------------------------------------------------------ Critical communication
1.12      www       231: 
1.1       albertel  232: sub critical {
                    233:     my ($cmd,$server)=@_;
1.89      www       234:     unless ($hostname{$server}) {
1.672     albertel  235:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       236:                " Critical message to unknown server ($server)</font>");
                    237:         return 'no_such_host';
                    238:     }
1.1       albertel  239:     my $answer=reply($cmd,$server);
                    240:     if ($answer eq 'con_lost') {
                    241: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  242: 	my $answer=reply($cmd,$server);
1.1       albertel  243:         if ($answer eq 'con_lost') {
                    244:             my $now=time;
                    245:             my $middlename=$cmd;
1.5       www       246:             $middlename=substr($middlename,0,16);
1.1       albertel  247:             $middlename=~s/\W//g;
                    248:             my $dfilename=
1.305     www       249:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    250:             $dumpcount++;
1.1       albertel  251:             {
1.448     albertel  252: 		my $dfh;
                    253: 		if (open($dfh,">$dfilename")) {
                    254: 		    print $dfh "$cmd\n"; 
                    255: 		    close($dfh);
                    256: 		}
1.1       albertel  257:             }
                    258:             sleep 2;
                    259:             my $wcmd='';
                    260:             {
1.448     albertel  261: 		my $dfh;
                    262: 		if (open($dfh,"<$dfilename")) {
                    263: 		    $wcmd=<$dfh>; 
                    264: 		    close($dfh);
                    265: 		}
1.1       albertel  266:             }
                    267:             chomp($wcmd);
1.7       www       268:             if ($wcmd eq $cmd) {
1.672     albertel  269: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       270:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  271:                 &logperm("D:$server:$cmd");
                    272: 	        return 'con_delayed';
                    273:             } else {
1.672     albertel  274:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       275:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  276:                 &logperm("F:$server:$cmd");
                    277:                 return 'con_failed';
                    278:             }
                    279:         }
                    280:     }
                    281:     return $answer;
1.405     albertel  282: }
                    283: 
1.755     albertel  284: # ------------------------------------------- check if return value is an error
                    285: 
                    286: sub error {
                    287:     my ($result) = @_;
1.756     albertel  288:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  289: 	if ($2 == 2) { return undef; }
                    290: 	return $1;
                    291:     }
                    292:     return undef;
                    293: }
                    294: 
1.783   ! albertel  295: sub convert_and_load_session_env {
        !           296:     my ($lonidsdir,$handle)=@_;
        !           297:     my @profile;
        !           298:     {
        !           299: 	open(my $idf,"$lonidsdir/$handle.id");
        !           300: 	flock($idf,LOCK_SH);
        !           301: 	@profile=<$idf>;
        !           302: 	close($idf);
        !           303:     }
        !           304:     my %temp_env;
        !           305:     foreach my $line (@profile) {
        !           306: 	chomp($line);
        !           307: 	my ($envname,$envvalue)=split(/=/,$line,2);
        !           308: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
        !           309:     }
        !           310:     unlink("$lonidsdir/$handle.id");
        !           311:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
        !           312: 	    0640)) {
        !           313: 	%disk_env = %temp_env;
        !           314: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
        !           315: 	untie(%disk_env);
        !           316:     }
        !           317: }
        !           318: 
1.374     www       319: # ------------------------------------------- Transfer profile into environment
1.780     albertel  320: my $env_loaded;
                    321: sub transfer_profile_to_env {
                    322:     if ($env_loaded) { return; } 
1.374     www       323: 
                    324:     my ($lonidsdir,$handle)=@_;
1.720     albertel  325:     if (!defined($lonidsdir)) {
                    326: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    327:     }
                    328:     if (!defined($handle)) {
                    329:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    330:     }
                    331: 
1.783   ! albertel  332:     my %remove;
        !           333:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_READER(),
        !           334: 	    0640)) {
        !           335: 	@env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
        !           336: 	untie(%disk_env);
        !           337:     } else {
        !           338: 	&convert_and_load_session_env($lonidsdir,$handle);
1.374     www       339:     }
1.783   ! albertel  340: 
        !           341:     while ( my $envname = each(%env) ) {
1.433     matthew   342:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    343:             if ($time < time-300) {
1.783   ! albertel  344:                 $remove{$key}++;
1.433     matthew   345:             }
                    346:         }
                    347:     }
1.783   ! albertel  348: 
1.619     albertel  349:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  350:     $env_loaded=1;
1.783   ! albertel  351:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   352:         &delenv($expired_key);
1.374     www       353:     }
1.1       albertel  354: }
                    355: 
1.5       www       356: # ---------------------------------------------------------- Append Environment
                    357: 
                    358: sub appenv {
1.6       www       359:     my %newenv=@_;
1.692     albertel  360:     foreach my $key (keys(%newenv)) {
                    361: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  362:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  363:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       364:                 .'</font>');
1.692     albertel  365: 	    delete($newenv{$key});
1.35      www       366:         } else {
1.692     albertel  367:             $env{$key}=$newenv{$key};
1.35      www       368:         }
1.191     harris41  369:     }
1.783   ! albertel  370:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
        !           371: 	    0640)) {
        !           372: 	while (my ($key,$value) = each(%newenv)) {
        !           373: 	    $disk_env{$key} = $value;
1.448     albertel  374: 	}
1.783   ! albertel  375: 	untie(%disk_env);
1.56      www       376:     }
                    377:     return 'ok';
                    378: }
                    379: # ----------------------------------------------------- Delete from Environment
                    380: 
                    381: sub delenv {
                    382:     my $delthis=shift;
                    383:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  384:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       385:                 "Attempt to delete from environment ".$delthis);
                    386:         return 'error';
                    387:     }
1.783   ! albertel  388:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
        !           389: 	    0640)) {
        !           390: 	foreach my $key (keys(%disk_env)) {
        !           391: 	    if ($key=~/^$delthis/) { 
1.619     albertel  392:                 delete($env{$key});
1.783   ! albertel  393:                 delete($disk_env{$key});
1.473     matthew   394:             }
1.448     albertel  395: 	}
1.783   ! albertel  396: 	untie(%disk_env);
1.5       www       397:     }
                    398:     return 'ok';
1.369     albertel  399: }
                    400: 
                    401: # ------------------------------------------ Find out current server userload
                    402: # there is a copy in lond
                    403: sub userload {
                    404:     my $numusers=0;
                    405:     {
                    406: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    407: 	my $filename;
                    408: 	my $curtime=time;
                    409: 	while ($filename=readdir(LONIDS)) {
                    410: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  411: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  412: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  413: 	}
                    414: 	closedir(LONIDS);
                    415:     }
                    416:     my $userloadpercent=0;
                    417:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    418:     if ($maxuserload) {
1.371     albertel  419: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  420:     }
1.372     albertel  421:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  422:     return $userloadpercent;
1.283     www       423: }
                    424: 
                    425: # ------------------------------------------ Fight off request when overloaded
                    426: 
                    427: sub overloaderror {
                    428:     my ($r,$checkserver)=@_;
                    429:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    430:     my $loadavg;
                    431:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  432:        open(my $loadfile,'/proc/loadavg');
1.283     www       433:        $loadavg=<$loadfile>;
                    434:        $loadavg =~ s/\s.*//g;
1.285     matthew   435:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  436:        close($loadfile);
1.283     www       437:     } else {
                    438:        $loadavg=&reply('load',$checkserver);
                    439:     }
1.285     matthew   440:     my $overload=$loadavg-100;
1.283     www       441:     if ($overload>0) {
1.285     matthew   442: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       443:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       444:         return 413;
1.283     www       445:     }    
                    446:     return '';
1.5       www       447: }
1.1       albertel  448: 
                    449: # ------------------------------ Find server with least workload from spare.tab
1.11      www       450: 
1.1       albertel  451: sub spareserver {
1.670     albertel  452:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.1       albertel  453:     my $tryserver;
                    454:     my $spareserver='';
1.370     albertel  455:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    456:     my $lowestserver=$loadpercent > $userloadpercent?
                    457: 	             $loadpercent :  $userloadpercent;
1.670     albertel  458:     foreach $tryserver (keys(%spareid)) {
                    459: 	my $loadans=&reply('load',$tryserver);
                    460: 	my $userloadans=&reply('userload',$tryserver);
1.411     albertel  461: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    462: 	    next; #didn't get a number from the server
                    463: 	}
                    464: 	my $answer;
                    465: 	if ($loadans =~ /\d/) {
                    466: 	    if ($userloadans =~ /\d/) {
                    467: 		#both are numbers, pick the bigger one
                    468: 		$answer=$loadans > $userloadans?
                    469: 		    $loadans :  $userloadans;
                    470: 	    } else {
                    471: 		$answer = $loadans;
                    472: 	    }
                    473: 	} else {
                    474: 	    $answer = $userloadans;
                    475: 	}
                    476: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
1.670     albertel  477: 	    if ($want_server_name) {
                    478: 		$spareserver=$tryserver;
                    479: 	    } else {
                    480: 		$spareserver="http://$hostname{$tryserver}";
                    481: 	    }
1.411     albertel  482: 	    $lowestserver=$answer;
                    483: 	}
1.370     albertel  484:     }
1.1       albertel  485:     return $spareserver;
1.202     matthew   486: }
                    487: 
                    488: # --------------------------------------------- Try to change a user's password
                    489: 
                    490: sub changepass {
                    491:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    492:     $currentpass = &escape($currentpass);
                    493:     $newpass     = &escape($newpass);
                    494:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    495: 		       $server);
                    496:     if (! $answer) {
                    497: 	&logthis("No reply on password change request to $server ".
                    498: 		 "by $uname in domain $udom.");
                    499:     } elsif ($answer =~ "^ok") {
                    500:         &logthis("$uname in $udom successfully changed their password ".
                    501: 		 "on $server.");
                    502:     } elsif ($answer =~ "^pwchange_failure") {
                    503: 	&logthis("$uname in $udom was unable to change their password ".
                    504: 		 "on $server.  The action was blocked by either lcpasswd ".
                    505: 		 "or pwchange");
                    506:     } elsif ($answer =~ "^non_authorized") {
                    507:         &logthis("$uname in $udom did not get their password correct when ".
                    508: 		 "attempting to change it on $server.");
                    509:     } elsif ($answer =~ "^auth_mode_error") {
                    510:         &logthis("$uname in $udom attempted to change their password despite ".
                    511: 		 "not being locally or internally authenticated on $server.");
                    512:     } elsif ($answer =~ "^unknown_user") {
                    513:         &logthis("$uname in $udom attempted to change their password ".
                    514: 		 "on $server but were unable to because $server is not ".
                    515: 		 "their home server.");
                    516:     } elsif ($answer =~ "^refused") {
                    517: 	&logthis("$server refused to change $uname in $udom password because ".
                    518: 		 "it was sent an unencrypted request to change the password.");
                    519:     }
                    520:     return $answer;
1.1       albertel  521: }
                    522: 
1.169     harris41  523: # ----------------------- Try to determine user's current authentication scheme
                    524: 
                    525: sub queryauthenticate {
                    526:     my ($uname,$udom)=@_;
1.456     albertel  527:     my $uhome=&homeserver($uname,$udom);
                    528:     if (!$uhome) {
                    529: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    530: 	return 'no_host';
                    531:     }
                    532:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    533:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    534: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  535:     }
1.456     albertel  536:     return $answer;
1.169     harris41  537: }
                    538: 
1.1       albertel  539: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       540: 
1.1       albertel  541: sub authenticate {
                    542:     my ($uname,$upass,$udom)=@_;
1.12      www       543:     $upass=escape($upass);
1.199     www       544:     $uname=~s/\W//g;
1.471     albertel  545:     my $uhome=&homeserver($uname,$udom);
                    546:     if (!$uhome) {
                    547: 	&logthis("User $uname at $udom is unknown in authenticate");
                    548: 	return 'no_host';
1.1       albertel  549:     }
1.471     albertel  550:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    551:     if ($answer eq 'authorized') {
                    552: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    553: 	return $uhome; 
                    554:     }
                    555:     if ($answer eq 'non_authorized') {
                    556: 	&logthis("User $uname at $udom rejected by $uhome");
                    557: 	return 'no_host'; 
1.9       www       558:     }
1.471     albertel  559:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  560:     return 'no_host';
                    561: }
                    562: 
                    563: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       564: 
1.599     albertel  565: my %homecache;
1.1       albertel  566: sub homeserver {
1.230     stredwic  567:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  568:     my $index="$uname:$udom";
1.426     albertel  569: 
1.599     albertel  570:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  571:     my $tryserver;
                    572:     foreach $tryserver (keys %libserv) {
1.230     stredwic  573:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  574: 		 exists($badServerCache{$tryserver}));
1.1       albertel  575: 	if ($hostdom{$tryserver} eq $udom) {
                    576:            my $answer=reply("home:$udom:$uname",$tryserver);
                    577:            if ($answer eq 'found') { 
1.599     albertel  578: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  579:            } elsif ($answer eq 'no_host') {
                    580: 	       $badServerCache{$tryserver}=1;
1.221     matthew   581:            }
1.1       albertel  582:        }
                    583:     }    
                    584:     return 'no_host';
1.70      www       585: }
                    586: 
                    587: # ------------------------------------- Find the usernames behind a list of IDs
                    588: 
                    589: sub idget {
                    590:     my ($udom,@ids)=@_;
                    591:     my %returnhash=();
                    592:     
                    593:     my $tryserver;
                    594:     foreach $tryserver (keys %libserv) {
                    595:        if ($hostdom{$tryserver} eq $udom) {
                    596: 	  my $idlist=join('&',@ids);
                    597:           $idlist=~tr/A-Z/a-z/; 
                    598: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    599:           my @answer=();
1.76      www       600:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       601: 	      @answer=split(/\&/,$reply);
                    602:           }                    ;
                    603:           my $i;
                    604:           for ($i=0;$i<=$#ids;$i++) {
                    605:               if ($answer[$i]) {
                    606: 		  $returnhash{$ids[$i]}=$answer[$i];
                    607:               } 
                    608:           }
                    609:        }
                    610:     }    
                    611:     return %returnhash;
                    612: }
                    613: 
                    614: # ------------------------------------- Find the IDs behind a list of usernames
                    615: 
                    616: sub idrget {
                    617:     my ($udom,@unames)=@_;
                    618:     my %returnhash=();
1.191     harris41  619:     foreach (@unames) {
1.70      www       620:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  621:     }
1.70      www       622:     return %returnhash;
                    623: }
                    624: 
                    625: # ------------------------------- Store away a list of names and associated IDs
                    626: 
                    627: sub idput {
                    628:     my ($udom,%ids)=@_;
                    629:     my %servers=();
1.191     harris41  630:     foreach (keys %ids) {
1.487     albertel  631: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       632:         my $uhom=&homeserver($_,$udom);
                    633:         if ($uhom ne 'no_host') {
                    634:             my $id=&escape($ids{$_});
                    635:             $id=~tr/A-Z/a-z/;
                    636:             my $unam=&escape($_);
                    637: 	    if ($servers{$uhom}) {
                    638: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    639:             } else {
                    640:                 $servers{$uhom}=$id.'='.$unam;
                    641:             }
                    642:         }
1.191     harris41  643:     }
                    644:     foreach (keys %servers) {
1.70      www       645:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  646:     }
1.344     www       647: }
                    648: 
                    649: # --------------------------------------------------- Assign a key to a student
                    650: 
                    651: sub assign_access_key {
1.364     www       652: #
                    653: # a valid key looks like uname:udom#comments
                    654: # comments are being appended
                    655: #
1.498     www       656:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    657:     $kdom=
1.620     albertel  658:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       659:     $knum=
1.620     albertel  660:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       661:     $cdom=
1.620     albertel  662:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       663:     $cnum=
1.620     albertel  664:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    665:     $udom=$env{'user.name'} unless (defined($udom));
                    666:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       667:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       668:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  669:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       670:                                                   # assigned to this person
                    671:                                                   # - this should not happen,
1.345     www       672:                                                   # unless something went wrong
                    673:                                                   # the first time around
                    674: # ready to assign
1.364     www       675:         $logentry=$1.'; '.$logentry;
1.496     www       676:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       677:                                                  $kdom,$knum) eq 'ok') {
1.345     www       678: # key now belongs to user
1.346     www       679: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       680:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    681:                 &appenv('environment.'.$envkey => $ckey);
                    682:                 return 'ok';
                    683:             } else {
                    684:                 return 
                    685:   'error: Count not permanently assign key, will need to be re-entered later.';
                    686: 	    }
                    687:         } else {
                    688:             return 'error: Could not assign key, try again later.';
                    689:         }
1.364     www       690:     } elsif (!$existing{$ckey}) {
1.345     www       691: # the key does not exist
                    692: 	return 'error: The key does not exist';
                    693:     } else {
                    694: # the key is somebody else's
                    695: 	return 'error: The key is already in use';
                    696:     }
1.344     www       697: }
                    698: 
1.364     www       699: # ------------------------------------------ put an additional comment on a key
                    700: 
                    701: sub comment_access_key {
                    702: #
                    703: # a valid key looks like uname:udom#comments
                    704: # comments are being appended
                    705: #
                    706:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    707:     $cdom=
1.620     albertel  708:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       709:     $cnum=
1.620     albertel  710:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       711:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    712:     if ($existing{$ckey}) {
                    713:         $existing{$ckey}.='; '.$logentry;
                    714: # ready to assign
1.367     www       715:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       716:                                                  $cdom,$cnum) eq 'ok') {
                    717: 	    return 'ok';
                    718:         } else {
                    719: 	    return 'error: Count not store comment.';
                    720:         }
                    721:     } else {
                    722: # the key does not exist
                    723: 	return 'error: The key does not exist';
                    724:     }
                    725: }
                    726: 
1.344     www       727: # ------------------------------------------------------ Generate a set of keys
                    728: 
                    729: sub generate_access_keys {
1.364     www       730:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       731:     $cdom=
1.620     albertel  732:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       733:     $cnum=
1.620     albertel  734:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       735:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       736:     unless (($cdom) && ($cnum)) { return 0; }
                    737:     if ($number>10000) { return 0; }
                    738:     sleep(2); # make sure don't get same seed twice
                    739:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    740:     my $total=0;
                    741:     for (my $i=1;$i<=$number;$i++) {
                    742:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    743:                   sprintf("%lx",int(100000*rand)).'-'.
                    744:                   sprintf("%lx",int(100000*rand));
                    745:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    746:        $newkey=~s/0/h/g; # and also 0 and O
                    747:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    748:        if ($existing{$newkey}) {
                    749:            $i--;
                    750:        } else {
1.364     www       751: 	  if (&put('accesskeys',
                    752:               { $newkey => '# generated '.localtime().
1.620     albertel  753:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       754:                            '; '.$logentry },
                    755: 		   $cdom,$cnum) eq 'ok') {
1.344     www       756:               $total++;
                    757: 	  }
                    758:        }
                    759:     }
1.620     albertel  760:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       761:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    762:     return $total;
                    763: }
                    764: 
                    765: # ------------------------------------------------------- Validate an accesskey
                    766: 
                    767: sub validate_access_key {
                    768:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    769:     $cdom=
1.620     albertel  770:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       771:     $cnum=
1.620     albertel  772:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    773:     $udom=$env{'user.domain'} unless (defined($udom));
                    774:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       775:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  776:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       777: }
                    778: 
                    779: # ------------------------------------- Find the section of student in a course
1.652     albertel  780: sub devalidate_getsection_cache {
                    781:     my ($udom,$unam,$courseid)=@_;
                    782:     $courseid=~s/\_/\//g;
                    783:     $courseid=~s/^(\w)/\/$1/;
                    784:     my $hashid="$udom:$unam:$courseid";
                    785:     &devalidate_cache_new('getsection',$hashid);
                    786: }
1.298     matthew   787: 
                    788: sub getsection {
                    789:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  790:     my $cachetime=1800;
1.298     matthew   791:     $courseid=~s/\_/\//g;
                    792:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  793: 
                    794:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  795:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  796:     if (defined($cached)) { return $result; }
                    797: 
1.298     matthew   798:     my %Pending; 
                    799:     my %Expired;
                    800:     #
                    801:     # Each role can either have not started yet (pending), be active, 
                    802:     #    or have expired.
                    803:     #
                    804:     # If there is an active role, we are done.
                    805:     #
                    806:     # If there is more than one role which has not started yet, 
                    807:     #     choose the one which will start sooner
                    808:     # If there is one role which has not started yet, return it.
                    809:     #
                    810:     # If there is more than one expired role, choose the one which ended last.
                    811:     # If there is a role which has expired, return it.
                    812:     #
                    813:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    814:                         &homeserver($unam,$udom)))) {
                    815:         my ($key,$value)=split(/\=/,$_);
                    816:         $key=&unescape($key);
1.479     albertel  817:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   818:         my $section=$1;
                    819:         if ($key eq $courseid.'_st') { $section=''; }
                    820:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    821:         my $now=time;
1.548     albertel  822:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   823:             $Expired{$end}=$section;
                    824:             next;
                    825:         }
1.548     albertel  826:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   827:             $Pending{$start}=$section;
                    828:             next;
                    829:         }
1.599     albertel  830:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   831:     }
                    832:     #
                    833:     # Presumedly there will be few matching roles from the above
                    834:     # loop and the sorting time will be negligible.
                    835:     if (scalar(keys(%Pending))) {
                    836:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  837:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   838:     } 
                    839:     if (scalar(keys(%Expired))) {
                    840:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    841:         my $time = pop(@sorted);
1.599     albertel  842:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   843:     }
1.599     albertel  844:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   845: }
1.70      www       846: 
1.599     albertel  847: sub save_cache {
                    848:     &purge_remembered();
1.722     albertel  849:     #&Apache::loncommon::validate_page();
1.620     albertel  850:     undef(%env);
1.780     albertel  851:     undef($env_loaded);
1.599     albertel  852: }
1.452     albertel  853: 
1.599     albertel  854: my $to_remember=-1;
                    855: my %remembered;
                    856: my %accessed;
                    857: my $kicks=0;
                    858: my $hits=0;
                    859: sub devalidate_cache_new {
                    860:     my ($name,$id,$debug) = @_;
                    861:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    862:     $id=&escape($name.':'.$id);
                    863:     $memcache->delete($id);
                    864:     delete($remembered{$id});
                    865:     delete($accessed{$id});
                    866: }
                    867: 
                    868: sub is_cached_new {
                    869:     my ($name,$id,$debug) = @_;
                    870:     $id=&escape($name.':'.$id);
                    871:     if (exists($remembered{$id})) {
                    872: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    873: 	$accessed{$id}=[&gettimeofday()];
                    874: 	$hits++;
                    875: 	return ($remembered{$id},1);
                    876:     }
                    877:     my $value = $memcache->get($id);
                    878:     if (!(defined($value))) {
                    879: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  880: 	return (undef,undef);
1.416     albertel  881:     }
1.599     albertel  882:     if ($value eq '__undef__') {
                    883: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    884: 	$value=undef;
                    885:     }
                    886:     &make_room($id,$value,$debug);
                    887:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    888:     return ($value,1);
                    889: }
                    890: 
                    891: sub do_cache_new {
                    892:     my ($name,$id,$value,$time,$debug) = @_;
                    893:     $id=&escape($name.':'.$id);
                    894:     my $setvalue=$value;
                    895:     if (!defined($setvalue)) {
                    896: 	$setvalue='__undef__';
                    897:     }
1.623     albertel  898:     if (!defined($time) ) {
                    899: 	$time=600;
                    900:     }
1.599     albertel  901:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  902:     $memcache->set($id,$setvalue,$time);
                    903:     # need to make a copy of $value
                    904:     #&make_room($id,$value,$debug);
1.599     albertel  905:     return $value;
                    906: }
                    907: 
                    908: sub make_room {
                    909:     my ($id,$value,$debug)=@_;
                    910:     $remembered{$id}=$value;
                    911:     if ($to_remember<0) { return; }
                    912:     $accessed{$id}=[&gettimeofday()];
                    913:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    914:     my $to_kick;
                    915:     my $max_time=0;
                    916:     foreach my $other (keys(%accessed)) {
                    917: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    918: 	    $to_kick=$other;
                    919: 	    $max_time=&tv_interval($accessed{$other});
                    920: 	}
                    921:     }
                    922:     delete($remembered{$to_kick});
                    923:     delete($accessed{$to_kick});
                    924:     $kicks++;
                    925:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  926:     return;
                    927: }
                    928: 
1.599     albertel  929: sub purge_remembered {
1.604     albertel  930:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    931:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  932:     undef(%remembered);
                    933:     undef(%accessed);
1.428     albertel  934: }
1.70      www       935: # ------------------------------------- Read an entry from a user's environment
                    936: 
                    937: sub userenvironment {
                    938:     my ($udom,$unam,@what)=@_;
                    939:     my %returnhash=();
                    940:     my @answer=split(/\&/,
                    941:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    942:                       &homeserver($unam,$udom)));
                    943:     my $i;
                    944:     for ($i=0;$i<=$#what;$i++) {
                    945: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    946:     }
                    947:     return %returnhash;
1.1       albertel  948: }
                    949: 
1.617     albertel  950: # ---------------------------------------------------------- Get a studentphoto
                    951: sub studentphoto {
                    952:     my ($udom,$unam,$ext) = @_;
                    953:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn   954:     if (defined($env{'request.course.id'})) {
1.708     raeburn   955:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn   956:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                    957:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                    958:             } else {
                    959:                 my ($result,$perm_reqd)=
1.707     albertel  960: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn   961:                 if ($result eq 'ok') {
                    962:                     if (!($perm_reqd eq 'yes')) {
                    963:                         return(&retrievestudentphoto($udom,$unam,$ext));
                    964:                     }
                    965:                 }
                    966:             }
                    967:         }
                    968:     } else {
                    969:         my ($result,$perm_reqd) = 
1.707     albertel  970: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn   971:         if ($result eq 'ok') {
                    972:             if (!($perm_reqd eq 'yes')) {
                    973:                 return(&retrievestudentphoto($udom,$unam,$ext));
                    974:             }
                    975:         }
                    976:     }
                    977:     return '/adm/lonKaputt/lonlogo_broken.gif';
                    978: }
                    979: 
                    980: sub retrievestudentphoto {
                    981:     my ($udom,$unam,$ext,$type) = @_;
                    982:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                    983:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                    984:     if ($ret eq 'ok') {
                    985:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                    986:         if ($type eq 'thumbnail') {
                    987:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                    988:         }
                    989:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                    990:         return $tokenurl;
                    991:     } else {
                    992:         if ($type eq 'thumbnail') {
                    993:             return '/adm/lonKaputt/genericstudent_tn.gif';
                    994:         } else { 
                    995:             return '/adm/lonKaputt/lonlogo_broken.gif';
                    996:         }
1.617     albertel  997:     }
                    998: }
                    999: 
1.263     www      1000: # -------------------------------------------------------------------- New chat
                   1001: 
                   1002: sub chatsend {
1.724     raeburn  1003:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1004:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1005:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1006:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1007:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1008: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1009: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1010: }
                   1011: 
                   1012: # ------------------------------------------ Find current version of a resource
                   1013: 
                   1014: sub getversion {
                   1015:     my $fname=&clutter(shift);
                   1016:     unless ($fname=~/^\/res\//) { return -1; }
                   1017:     return &currentversion(&filelocation('',$fname));
                   1018: }
                   1019: 
                   1020: sub currentversion {
                   1021:     my $fname=shift;
1.599     albertel 1022:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1023:     if (defined($cached)) { return $result; }
1.292     www      1024:     my $author=$fname;
                   1025:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1026:     my ($udom,$uname)=split(/\//,$author);
                   1027:     my $home=homeserver($uname,$udom);
                   1028:     if ($home eq 'no_host') { 
                   1029:         return -1; 
                   1030:     }
                   1031:     my $answer=reply("currentversion:$fname",$home);
                   1032:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1033: 	return -1;
                   1034:     }
1.599     albertel 1035:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1036: }
                   1037: 
1.1       albertel 1038: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1039: 
1.1       albertel 1040: sub subscribe {
                   1041:     my $fname=shift;
1.761     raeburn  1042:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1043:     $fname=~s/[\n\r]//g;
1.1       albertel 1044:     my $author=$fname;
                   1045:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1046:     my ($udom,$uname)=split(/\//,$author);
                   1047:     my $home=homeserver($uname,$udom);
1.335     albertel 1048:     if ($home eq 'no_host') {
                   1049:         return 'not_found';
1.1       albertel 1050:     }
                   1051:     my $answer=reply("sub:$fname",$home);
1.64      www      1052:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1053: 	$answer.=' by '.$home;
                   1054:     }
1.1       albertel 1055:     return $answer;
                   1056: }
                   1057:     
1.8       www      1058: # -------------------------------------------------------------- Replicate file
                   1059: 
                   1060: sub repcopy {
                   1061:     my $filename=shift;
1.23      www      1062:     $filename=~s/\/+/\//g;
1.607     raeburn  1063:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1064:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1065:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1066: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1067: 	return &repcopy_userfile($filename);
                   1068:     }
1.532     albertel 1069:     $filename=~s/[\n\r]//g;
1.8       www      1070:     my $transname="$filename.in.transfer";
1.607     raeburn  1071:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1072:     my $remoteurl=subscribe($filename);
1.64      www      1073:     if ($remoteurl =~ /^con_lost by/) {
                   1074: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1075:            return 'unavailable';
1.8       www      1076:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1077: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1078: 	   return 'not_found';
1.64      www      1079:     } elsif ($remoteurl =~ /^rejected by/) {
                   1080: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1081:            return 'forbidden';
1.20      www      1082:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1083:            return 'ok';
1.8       www      1084:     } else {
1.290     www      1085:         my $author=$filename;
                   1086:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1087:         my ($udom,$uname)=split(/\//,$author);
                   1088:         my $home=homeserver($uname,$udom);
                   1089:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1090:            my @parts=split(/\//,$filename);
                   1091:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1092:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1093:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1094: 	       return 'bad_request';
1.8       www      1095:            }
                   1096:            my $count;
                   1097:            for ($count=5;$count<$#parts;$count++) {
                   1098:                $path.="/$parts[$count]";
                   1099:                if ((-e $path)!=1) {
                   1100: 		   mkdir($path,0777);
                   1101:                }
                   1102:            }
                   1103:            my $ua=new LWP::UserAgent;
                   1104:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1105:            my $response=$ua->request($request,$transname);
                   1106:            if ($response->is_error()) {
                   1107: 	       unlink($transname);
                   1108:                my $message=$response->status_line;
1.672     albertel 1109:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1110:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1111:                return 'unavailable';
1.8       www      1112:            } else {
1.16      www      1113: 	       if ($remoteurl!~/\.meta$/) {
                   1114:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1115:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1116:                   if ($mresponse->is_error()) {
                   1117: 		      unlink($filename.'.meta');
                   1118:                       &logthis(
1.672     albertel 1119:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1120:                   }
                   1121: 	       }
1.8       www      1122:                rename($transname,$filename);
1.607     raeburn  1123:                return 'ok';
1.8       www      1124:            }
1.290     www      1125:        }
1.8       www      1126:     }
1.330     www      1127: }
                   1128: 
                   1129: # ------------------------------------------------ Get server side include body
                   1130: sub ssi_body {
1.381     albertel 1131:     my ($filelink,%form)=@_;
1.606     matthew  1132:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1133:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1134:     }
1.330     www      1135:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1136:                                      &ssi($filelink,%form));
1.778     albertel 1137:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1138:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1139:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1140:     return $output;
1.8       www      1141: }
                   1142: 
1.15      www      1143: # --------------------------------------------------------- Server Side Include
                   1144: 
1.782     albertel 1145: sub absolute_url {
                   1146:     my ($host_name) = @_;
                   1147:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1148:     if ($host_name eq '') {
                   1149: 	$host_name = $ENV{'SERVER_NAME'};
                   1150:     }
                   1151:     return $protocol.$host_name;
                   1152: }
                   1153: 
1.783   ! albertel 1154: sub absolute_url {
        !          1155:     my ($host_name) = @_;
        !          1156:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
        !          1157:     if ($host_name eq '') {
        !          1158: 	$host_name = $ENV{'SERVER_NAME'};
        !          1159:     }
        !          1160:     return $protocol.$host_name;
        !          1161: }
        !          1162: 
1.15      www      1163: sub ssi {
                   1164: 
1.23      www      1165:     my ($fn,%form)=@_;
1.15      www      1166: 
                   1167:     my $ua=new LWP::UserAgent;
1.23      www      1168:     
                   1169:     my $request;
1.711     albertel 1170: 
                   1171:     $form{'no_update_last_known'}=1;
                   1172: 
1.23      www      1173:     if (%form) {
1.782     albertel 1174:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1175:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1176:     } else {
1.782     albertel 1177:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1178:     }
                   1179: 
1.15      www      1180:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1181:     my $response=$ua->request($request);
                   1182: 
1.324     www      1183:     return $response->content;
                   1184: }
                   1185: 
                   1186: sub externalssi {
                   1187:     my ($url)=@_;
                   1188:     my $ua=new LWP::UserAgent;
                   1189:     my $request=new HTTP::Request('GET',$url);
                   1190:     my $response=$ua->request($request);
1.15      www      1191:     return $response->content;
                   1192: }
1.254     www      1193: 
1.492     albertel 1194: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1195: 
                   1196: sub allowuploaded {
                   1197:     my ($srcurl,$url)=@_;
                   1198:     $url=&clutter(&declutter($url));
                   1199:     my $dir=$url;
                   1200:     $dir=~s/\/[^\/]+$//;
                   1201:     my %httpref=();
                   1202:     my $httpurl=&hreflocation('',$url);
                   1203:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1204:     &Apache::lonnet::appenv(%httpref);
1.254     www      1205: }
1.477     raeburn  1206: 
1.478     albertel 1207: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1208: # input: action, courseID, current domain, intended
1.637     raeburn  1209: #        path to file, source of file, instruction to parse file for objects,
                   1210: #        ref to hash for embedded objects,
                   1211: #        ref to hash for codebase of java objects.
                   1212: #
1.485     raeburn  1213: # output: url to file (if action was uploaddoc), 
                   1214: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1215: #
1.478     albertel 1216: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1217: # course.
1.477     raeburn  1218: #
1.478     albertel 1219: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1220: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1221: #          course's home server.
1.477     raeburn  1222: #
1.478     albertel 1223: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1224: #          be copied from $source (current location) to 
                   1225: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1226: #         and will then be copied to
                   1227: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1228: #         course's home server.
1.485     raeburn  1229: #
1.481     raeburn  1230: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1231: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1232: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1233: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1234: #         in course's home server.
1.637     raeburn  1235: #
1.477     raeburn  1236: 
                   1237: sub process_coursefile {
1.638     albertel 1238:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1239:     my $fetchresult;
1.638     albertel 1240:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1241:     if ($action eq 'propagate') {
1.638     albertel 1242:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1243: 			     $home);
1.481     raeburn  1244:     } else {
1.477     raeburn  1245:         my $fpath = '';
                   1246:         my $fname = $file;
1.478     albertel 1247:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1248:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1249:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1250:         if ($action eq 'copy') {
                   1251:             if ($source eq '') {
                   1252:                 $fetchresult = 'no source file';
                   1253:                 return $fetchresult;
                   1254:             } else {
                   1255:                 my $destination = $filepath.'/'.$fname;
                   1256:                 rename($source,$destination);
                   1257:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1258:                                  $home);
1.481     raeburn  1259:             }
                   1260:         } elsif ($action eq 'uploaddoc') {
                   1261:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1262:             print $fh $env{'form.'.$source};
1.481     raeburn  1263:             close($fh);
1.637     raeburn  1264:             if ($parser eq 'parse') {
                   1265:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1266:                 unless ($parse_result eq 'ok') {
                   1267:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1268:                 }
                   1269:             }
1.477     raeburn  1270:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1271:                                  $home);
1.481     raeburn  1272:             if ($fetchresult eq 'ok') {
                   1273:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1274:             } else {
                   1275:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1276:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1277:                 return '/adm/notfound.html';
                   1278:             }
1.477     raeburn  1279:         }
                   1280:     }
1.485     raeburn  1281:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1282:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1283:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1284:     }
                   1285:     return $fetchresult;
                   1286: }
                   1287: 
1.637     raeburn  1288: sub build_filepath {
                   1289:     my ($fpath) = @_;
                   1290:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1291:     unless ($fpath eq '') {
                   1292:         my @parts=split('/',$fpath);
                   1293:         foreach my $part (@parts) {
                   1294:             $filepath.= '/'.$part;
                   1295:             if ((-e $filepath)!=1) {
                   1296:                 mkdir($filepath,0777);
                   1297:             }
                   1298:         }
                   1299:     }
                   1300:     return $filepath;
                   1301: }
                   1302: 
                   1303: sub store_edited_file {
1.638     albertel 1304:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1305:     my $file = $primary_url;
                   1306:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1307:     my $fpath = '';
                   1308:     my $fname = $file;
                   1309:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1310:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1311:     my $filepath = &build_filepath($fpath);
                   1312:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1313:     print $fh $content;
                   1314:     close($fh);
1.638     albertel 1315:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1316:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1317: 			  $home);
1.637     raeburn  1318:     if ($$fetchresult eq 'ok') {
                   1319:         return '/uploaded/'.$fpath.'/'.$fname;
                   1320:     } else {
1.638     albertel 1321:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1322: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1323:         return '/adm/notfound.html';
                   1324:     }
                   1325: }
                   1326: 
1.531     albertel 1327: sub clean_filename {
                   1328:     my ($fname)=@_;
1.315     www      1329: # Replace Windows backslashes by forward slashes
1.257     www      1330:     $fname=~s/\\/\//g;
1.315     www      1331: # Get rid of everything but the actual filename
1.257     www      1332:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1333: # Replace spaces by underscores
                   1334:     $fname=~s/\s+/\_/g;
                   1335: # Replace all other weird characters by nothing
1.317     www      1336:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1337: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1338: # numbers
                   1339:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1340:     return $fname;
                   1341: }
                   1342: 
1.608     albertel 1343: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1344: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1345: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1346: #        $coursedoc - if true up to the current course
                   1347: #                     if false
                   1348: #        $subdir - directory in userfile to store the file into
                   1349: #        $parser, $allfiles, $codebase - unknown
                   1350: #
                   1351: # output: url of file in userspace, or error: <message> 
                   1352: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1353: 
                   1354: 
1.531     albertel 1355: sub userfileupload {
1.719     banghart 1356:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1357:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1358:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1359:     $fname=&clean_filename($fname);
1.315     www      1360: # See if there is anything left
1.257     www      1361:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1362:     chop($env{'form.'.$formname});
1.523     raeburn  1363:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1364:         my $now = time;
                   1365:         my $filepath = 'tmp/helprequests/'.$now;
                   1366:         my @parts=split(/\//,$filepath);
                   1367:         my $fullpath = $perlvar{'lonDaemons'};
                   1368:         for (my $i=0;$i<@parts;$i++) {
                   1369:             $fullpath .= '/'.$parts[$i];
                   1370:             if ((-e $fullpath)!=1) {
                   1371:                 mkdir($fullpath,0777);
                   1372:             }
                   1373:         }
                   1374:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1375:         print $fh $env{'form.'.$formname};
1.523     raeburn  1376:         close($fh);
1.741     raeburn  1377:         return $fullpath.'/'.$fname;
                   1378:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1379:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1380:                        '_'.$env{'user.domain'}.'/pending';
                   1381:         my @parts=split(/\//,$filepath);
                   1382:         my $fullpath = $perlvar{'lonDaemons'};
                   1383:         for (my $i=0;$i<@parts;$i++) {
                   1384:             $fullpath .= '/'.$parts[$i];
                   1385:             if ((-e $fullpath)!=1) {
                   1386:                 mkdir($fullpath,0777);
                   1387:             }
                   1388:         }
                   1389:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1390:         print $fh $env{'form.'.$formname};
                   1391:         close($fh);
                   1392:         return $fullpath.'/'.$fname;
1.523     raeburn  1393:     }
1.719     banghart 1394:     
1.258     www      1395: # Create the directory if not present
1.493     albertel 1396:     $fname="$subdir/$fname";
1.259     www      1397:     if ($coursedoc) {
1.638     albertel 1398: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1399: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1400:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1401:             return &finishuserfileupload($docuname,$docudom,
                   1402: 					 $formname,$fname,$parser,$allfiles,
                   1403: 					 $codebase);
1.481     raeburn  1404:         } else {
1.620     albertel 1405:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1406:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1407: 				       $fname,$formname,$parser,
                   1408: 				       $allfiles,$codebase);
1.481     raeburn  1409:         }
1.719     banghart 1410:     } elsif (defined($destuname)) {
                   1411:         my $docuname=$destuname;
                   1412:         my $docudom=$destudom;
                   1413: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1414: 				     $fname,$parser,$allfiles,$codebase);
                   1415:         
1.259     www      1416:     } else {
1.638     albertel 1417:         my $docuname=$env{'user.name'};
                   1418:         my $docudom=$env{'user.domain'};
1.714     raeburn  1419:         if (exists($env{'form.group'})) {
                   1420:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1421:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1422:         }
1.638     albertel 1423: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1424: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1425:     }
1.271     www      1426: }
                   1427: 
                   1428: sub finishuserfileupload {
1.638     albertel 1429:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1430:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1431:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1432:     my ($fnamepath,$file);
                   1433:     $file=$fname;
                   1434:     if ($fname=~m|/|) {
                   1435:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1436: 	$path.=$fnamepath.'/';
                   1437:     }
1.259     www      1438:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1439:     my $count;
                   1440:     for ($count=4;$count<=$#parts;$count++) {
                   1441:         $filepath.="/$parts[$count]";
                   1442:         if ((-e $filepath)!=1) {
                   1443: 	    mkdir($filepath,0777);
                   1444:         }
                   1445:     }
                   1446: # Save the file
                   1447:     {
1.701     albertel 1448: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1449: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1450: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1451: 	    return '/adm/notfound.html';
                   1452: 	}
                   1453: 	if (!print FH ($env{'form.'.$formname})) {
                   1454: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1455: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1456: 	    return '/adm/notfound.html';
                   1457: 	}
1.570     albertel 1458: 	close(FH);
1.258     www      1459:     }
1.637     raeburn  1460:     if ($parser eq 'parse') {
1.638     albertel 1461:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1462: 						   $codebase);
1.637     raeburn  1463:         unless ($parse_result eq 'ok') {
1.638     albertel 1464:             &logthis('Failed to parse '.$filepath.$file.
                   1465: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1466:         }
                   1467:     }
1.259     www      1468: # Notify homeserver to grep it
                   1469: #
1.638     albertel 1470:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1471:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1472:     if ($fetchresult eq 'ok') {
1.259     www      1473: #
1.258     www      1474: # Return the URL to it
1.494     albertel 1475:         return '/uploaded/'.$path.$file;
1.263     www      1476:     } else {
1.494     albertel 1477:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1478: 		 ': '.$fetchresult);
1.263     www      1479:         return '/adm/notfound.html';
                   1480:     }    
1.493     albertel 1481: }
                   1482: 
1.637     raeburn  1483: sub extract_embedded_items {
1.648     raeburn  1484:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1485:     my @state = ();
                   1486:     my %javafiles = (
                   1487:                       codebase => '',
                   1488:                       code => '',
                   1489:                       archive => ''
                   1490:                     );
                   1491:     my %mediafiles = (
                   1492:                       src => '',
                   1493:                       movie => '',
                   1494:                      );
1.648     raeburn  1495:     my $p;
                   1496:     if ($content) {
                   1497:         $p = HTML::LCParser->new($content);
                   1498:     } else {
                   1499:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1500:     }
1.641     albertel 1501:     while (my $t=$p->get_token()) {
1.640     albertel 1502: 	if ($t->[0] eq 'S') {
                   1503: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1504: 	    push (@state, $tagname);
1.648     raeburn  1505:             if (lc($tagname) eq 'allow') {
                   1506:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1507:             }
1.640     albertel 1508: 	    if (lc($tagname) eq 'img') {
                   1509: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1510: 	    }
1.645     raeburn  1511:             if (lc($tagname) eq 'script') {
                   1512:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1513:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1514:                 } else {
                   1515:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1516:                 }
                   1517:             }
                   1518:             if (lc($tagname) eq 'link') {
                   1519:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1520:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1521:                 }
                   1522:             }
1.640     albertel 1523: 	    if (lc($tagname) eq 'object' ||
                   1524: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1525: 		foreach my $item (keys(%javafiles)) {
                   1526: 		    $javafiles{$item} = '';
                   1527: 		}
                   1528: 	    }
                   1529: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1530: 		my $name = lc($attr->{'name'});
                   1531: 		foreach my $item (keys(%javafiles)) {
                   1532: 		    if ($name eq $item) {
                   1533: 			$javafiles{$item} = $attr->{'value'};
                   1534: 			last;
                   1535: 		    }
                   1536: 		}
                   1537: 		foreach my $item (keys(%mediafiles)) {
                   1538: 		    if ($name eq $item) {
                   1539: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1540: 			last;
                   1541: 		    }
                   1542: 		}
                   1543: 	    }
                   1544: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1545: 		foreach my $item (keys(%javafiles)) {
                   1546: 		    if ($attr->{$item}) {
                   1547: 			$javafiles{$item} = $attr->{$item};
                   1548: 			last;
                   1549: 		    }
                   1550: 		}
                   1551: 		foreach my $item (keys(%mediafiles)) {
                   1552: 		    if ($attr->{$item}) {
                   1553: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1554: 			last;
                   1555: 		    }
                   1556: 		}
                   1557: 	    }
                   1558: 	} elsif ($t->[0] eq 'E') {
                   1559: 	    my ($tagname) = ($t->[1]);
                   1560: 	    if ($javafiles{'codebase'} ne '') {
                   1561: 		$javafiles{'codebase'} .= '/';
                   1562: 	    }  
                   1563: 	    if (lc($tagname) eq 'applet' ||
                   1564: 		lc($tagname) eq 'object' ||
                   1565: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1566: 		) {
                   1567: 		foreach my $item (keys(%javafiles)) {
                   1568: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1569: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1570: 			&add_filetype($allfiles,$file,$item);
                   1571: 		    }
                   1572: 		}
                   1573: 	    } 
                   1574: 	    pop @state;
                   1575: 	}
                   1576:     }
1.637     raeburn  1577:     return 'ok';
                   1578: }
                   1579: 
1.639     albertel 1580: sub add_filetype {
                   1581:     my ($allfiles,$file,$type)=@_;
                   1582:     if (exists($allfiles->{$file})) {
                   1583: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1584: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1585: 	}
                   1586:     } else {
                   1587: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1588:     }
                   1589: }
                   1590: 
1.493     albertel 1591: sub removeuploadedurl {
                   1592:     my ($url)=@_;
                   1593:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1594:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1595: }
                   1596: 
                   1597: sub removeuserfile {
                   1598:     my ($docuname,$docudom,$fname)=@_;
                   1599:     my $home=&homeserver($docuname,$docudom);
                   1600:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1601: }
1.15      www      1602: 
1.530     albertel 1603: sub mkdiruserfile {
                   1604:     my ($docuname,$docudom,$dir)=@_;
                   1605:     my $home=&homeserver($docuname,$docudom);
                   1606:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1607: }
                   1608: 
1.531     albertel 1609: sub renameuserfile {
                   1610:     my ($docuname,$docudom,$old,$new)=@_;
                   1611:     my $home=&homeserver($docuname,$docudom);
                   1612:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1613: 		  &escape("$new"),$home);
                   1614: }
                   1615: 
1.14      www      1616: # ------------------------------------------------------------------------- Log
                   1617: 
                   1618: sub log {
                   1619:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1620:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1621: }
                   1622: 
                   1623: # ------------------------------------------------------------------ Course Log
1.352     www      1624: #
                   1625: # This routine flushes several buffers of non-mission-critical nature
                   1626: #
1.157     www      1627: 
                   1628: sub flushcourselogs {
1.352     www      1629:     &logthis('Flushing log buffers');
                   1630: #
                   1631: # course logs
                   1632: # This is a log of all transactions in a course, which can be used
                   1633: # for data mining purposes
                   1634: #
                   1635: # It also collects the courseid database, which lists last transaction
                   1636: # times and course titles for all courseids
                   1637: #
                   1638:     my %courseidbuffer=();
1.191     harris41 1639:     foreach (keys %courselogs) {
1.157     www      1640:         my $crsid=$_;
1.352     www      1641:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1642: 		          &escape($courselogs{$crsid}),
                   1643: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1644: 	    delete $courselogs{$crsid};
                   1645:         } else {
                   1646:             &logthis('Failed to flush log buffer for '.$crsid);
                   1647:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1648:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1649:                         " exceeded maximum size, deleting.</font>");
                   1650:                delete $courselogs{$crsid};
                   1651:             }
1.352     www      1652:         }
                   1653:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1654:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1655: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1656:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1657:         } else {
                   1658:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1659: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1660:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1661:         }
1.191     harris41 1662:     }
1.352     www      1663: #
                   1664: # Write course id database (reverse lookup) to homeserver of courses 
                   1665: # Is used in pickcourse
                   1666: #
                   1667:     foreach (keys %courseidbuffer) {
1.353     www      1668:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1669:     }
                   1670: #
                   1671: # File accesses
                   1672: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1673: #
1.449     matthew  1674:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1675:         if ($entry =~ /___count$/) {
                   1676:             my ($dom,$name);
                   1677:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1678:             if (! defined($dom) || $dom eq '' || 
                   1679:                 ! defined($name) || $name eq '') {
1.620     albertel 1680:                 my $cid = $env{'request.course.id'};
                   1681:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1682:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1683:             }
1.450     matthew  1684:             my $value = $accesshash{$entry};
                   1685:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1686:             my %temphash=($url => $value);
1.449     matthew  1687:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1688:             if ($result eq 'ok') {
                   1689:                 delete $accesshash{$entry};
                   1690:             } elsif ($result eq 'unknown_cmd') {
                   1691:                 # Target server has old code running on it.
1.450     matthew  1692:                 my %temphash=($entry => $value);
1.449     matthew  1693:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1694:                     delete $accesshash{$entry};
                   1695:                 }
                   1696:             }
                   1697:         } else {
1.458     matthew  1698:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1699:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1700:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1701:                 delete $accesshash{$entry};
                   1702:             }
1.185     www      1703:         }
1.191     harris41 1704:     }
1.352     www      1705: #
                   1706: # Roles
                   1707: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1708: #
1.349     www      1709:     foreach (keys %userrolehash) {
                   1710:         my $entry=$_;
1.351     www      1711:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1712: 	    split(/\:/,$entry);
                   1713:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1714:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1715:                 $rudom,$runame) eq 'ok') {
                   1716: 	    delete $userrolehash{$entry};
                   1717:         }
                   1718:     }
1.662     raeburn  1719: #
                   1720: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1721: #
                   1722:     my %domrolebuffer = ();
                   1723:     foreach my $entry (keys %domainrolehash) {
                   1724:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1725:         if ($domrolebuffer{$rudom}) {
                   1726:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1727:                       '='.&escape($domainrolehash{$entry});
                   1728:         } else {
                   1729:             $domrolebuffer{$rudom}.=&escape($entry).
                   1730:                       '='.&escape($domainrolehash{$entry});
                   1731:         }
                   1732:         delete $domainrolehash{$entry};
                   1733:     }
                   1734:     foreach my $dom (keys(%domrolebuffer)) {
                   1735:         foreach my $tryserver (keys %libserv) {
                   1736:             if ($hostdom{$tryserver} eq $dom) {
                   1737:                 unless (&reply('domroleput:'.$dom.':'.
                   1738:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1739:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1740:                 }
                   1741:             }
                   1742:         }
                   1743:     }
1.186     www      1744:     $dumpcount++;
1.157     www      1745: }
                   1746: 
                   1747: sub courselog {
                   1748:     my $what=shift;
1.158     www      1749:     $what=time.':'.$what;
1.620     albertel 1750:     unless ($env{'request.course.id'}) { return ''; }
                   1751:     $coursedombuf{$env{'request.course.id'}}=
                   1752:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1753:     $coursenumbuf{$env{'request.course.id'}}=
                   1754:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1755:     $coursehombuf{$env{'request.course.id'}}=
                   1756:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1757:     $coursedescrbuf{$env{'request.course.id'}}=
                   1758:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1759:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1760:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1761:     $courseownerbuf{$env{'request.course.id'}}=
                   1762:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1763:     $coursetypebuf{$env{'request.course.id'}}=
                   1764:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1765:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1766: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1767:     } else {
1.620     albertel 1768: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1769:     }
1.620     albertel 1770:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1771: 	&flushcourselogs();
                   1772:     }
1.158     www      1773: }
                   1774: 
                   1775: sub courseacclog {
                   1776:     my $fnsymb=shift;
1.620     albertel 1777:     unless ($env{'request.course.id'}) { return ''; }
                   1778:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1779:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1780:         $what.=':POST';
1.583     matthew  1781:         # FIXME: Probably ought to escape things....
1.620     albertel 1782: 	foreach (keys %env) {
1.158     www      1783:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1784: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1785:             }
1.191     harris41 1786:         }
1.583     matthew  1787:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1788:         # FIXME: We should not be depending on a form parameter that someone
                   1789:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1790:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1791:             $what.= ':POST';
                   1792:             # FIXME: Probably ought to escape things....
                   1793:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1794:                                  'crsdiscuss') {
1.620     albertel 1795:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1796:             }
                   1797:         }
1.158     www      1798:     }
                   1799:     &courselog($what);
1.149     www      1800: }
                   1801: 
1.185     www      1802: sub countacc {
                   1803:     my $url=&declutter(shift);
1.458     matthew  1804:     return if (! defined($url) || $url eq '');
1.620     albertel 1805:     unless ($env{'request.course.id'}) { return ''; }
                   1806:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1807:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1808:     $accesshash{$key}++;
1.185     www      1809: }
1.349     www      1810: 
1.361     www      1811: sub linklog {
                   1812:     my ($from,$to)=@_;
                   1813:     $from=&declutter($from);
                   1814:     $to=&declutter($to);
                   1815:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1816:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1817: }
                   1818:   
1.349     www      1819: sub userrolelog {
                   1820:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1821:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1822:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1823:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1824:         ($trole=~/^ta/)) {
1.350     www      1825:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1826:        $userrolehash
                   1827:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1828:                     =$tend.':'.$tstart;
1.662     raeburn  1829:     }
                   1830:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1831:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1832:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1833:         ($trole=~/^sc/)) {
                   1834:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1835:        $domainrolehash
                   1836:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1837:                     = $tend.':'.$tstart;
                   1838:     }
1.351     www      1839: }
                   1840: 
                   1841: sub get_course_adv_roles {
                   1842:     my $cid=shift;
1.620     albertel 1843:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1844:     my %coursehash=&coursedescription($cid);
1.470     www      1845:     my %nothide=();
                   1846:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1847: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1848:     }
1.351     www      1849:     my %returnhash=();
                   1850:     my %dumphash=
                   1851:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1852:     my $now=time;
                   1853:     foreach (keys %dumphash) {
                   1854: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1855:         if (($tstart) && ($tstart<0)) { next; }
                   1856:         if (($tend) && ($tend<$now)) { next; }
                   1857:         if (($tstart) && ($now<$tstart)) { next; }
                   1858:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1859: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1860: 	if ((&privileged($username,$domain)) && 
                   1861: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1862: 	if ($role eq 'cr') { next; }
1.351     www      1863:         my $key=&plaintext($role);
                   1864:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1865:         if ($returnhash{$key}) {
                   1866: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1867:         } else {
                   1868:             $returnhash{$key}=$username.':'.$domain;
                   1869:         }
1.400     www      1870:      }
                   1871:     return %returnhash;
                   1872: }
                   1873: 
                   1874: sub get_my_roles {
                   1875:     my ($uname,$udom)=@_;
1.620     albertel 1876:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1877:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1878:     my %dumphash=
                   1879:             &dump('nohist_userroles',$udom,$uname);
                   1880:     my %returnhash=();
                   1881:     my $now=time;
                   1882:     foreach (keys %dumphash) {
                   1883: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1884:         if (($tstart) && ($tstart<0)) { next; }
                   1885:         if (($tend) && ($tend<$now)) { next; }
                   1886:         if (($tstart) && ($now<$tstart)) { next; }
                   1887:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1888: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1889:      }
                   1890:     return %returnhash;
1.399     www      1891: }
                   1892: 
                   1893: # ----------------------------------------------------- Frontpage Announcements
                   1894: #
                   1895: #
                   1896: 
                   1897: sub postannounce {
                   1898:     my ($server,$text)=@_;
                   1899:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1900:     unless ($text=~/\w/) { $text=''; }
                   1901:     return &reply('setannounce:'.&escape($text),$server);
                   1902: }
                   1903: 
                   1904: sub getannounce {
1.448     albertel 1905: 
                   1906:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1907: 	my $announcement='';
                   1908: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1909: 	close($fh);
1.399     www      1910: 	if ($announcement=~/\w/) { 
                   1911: 	    return 
                   1912:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1913:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1914: 	} else {
                   1915: 	    return '';
                   1916: 	}
                   1917:     } else {
                   1918: 	return '';
                   1919:     }
1.351     www      1920: }
1.353     www      1921: 
                   1922: # ---------------------------------------------------------- Course ID routines
                   1923: # Deal with domain's nohist_courseid.db files
                   1924: #
                   1925: 
                   1926: sub courseidput {
                   1927:     my ($domain,$what,$coursehome)=@_;
                   1928:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1929: }
                   1930: 
                   1931: sub courseiddump {
1.741     raeburn  1932:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
1.353     www      1933:     my %returnhash=();
1.355     www      1934:     unless ($domfilter) { $domfilter=''; }
1.353     www      1935:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1936:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1937: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1938: 	        foreach (
                   1939:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1940: 			       $sincefilter.':'.&escape($descfilter).':'.
1.741     raeburn  1941:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
1.354     www      1942:                                $tryserver))) {
1.506     raeburn  1943: 		    my ($key,$value)=split(/\=/,$_);
                   1944:                     if (($key) && ($value)) {
1.516     raeburn  1945: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1946:                     }
1.353     www      1947:                 }
                   1948:             }
                   1949:         }
                   1950:     }
                   1951:     return %returnhash;
                   1952: }
                   1953: 
1.658     raeburn  1954: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1955: 
                   1956: sub dcmailput {
1.685     raeburn  1957:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  1958:     my $status = &Apache::lonnet::critical(
1.740     www      1959:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   1960:        &escape($message),$server);
1.662     raeburn  1961:     return $status;
                   1962: }
                   1963: 
1.658     raeburn  1964: sub dcmaildump {
                   1965:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  1966:     my %returnhash=();
                   1967:     if (exists($domain_primary{$dom})) {
                   1968:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   1969:                                                          &escape($enddate).':';
                   1970: 	my @esc_senders=map { &escape($_)} @$senders;
                   1971: 	$cmd.=&escape(join('&',@esc_senders));
                   1972: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   1973:             my ($key,$value) = split(/\=/,$_);
                   1974:             if (($key) && ($value)) {
                   1975:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  1976:             }
                   1977:         }
                   1978:     }
                   1979:     return %returnhash;
                   1980: }
1.662     raeburn  1981: # ---------------------------------------------------------- Domain roles
                   1982: 
                   1983: sub get_domain_roles {
                   1984:     my ($dom,$roles,$startdate,$enddate)=@_;
                   1985:     if (undef($startdate) || $startdate eq '') {
                   1986:         $startdate = '.';
                   1987:     }
                   1988:     if (undef($enddate) || $enddate eq '') {
                   1989:         $enddate = '.';
                   1990:     }
                   1991:     my $rolelist = join(':',@{$roles});
                   1992:     my %personnel = ();
                   1993:     foreach my $tryserver (keys(%libserv)) {
                   1994:         if ($hostdom{$tryserver} eq $dom) {
                   1995:             %{$personnel{$tryserver}}=();
                   1996:             foreach (
                   1997:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   1998:                    &escape($startdate).':'.&escape($enddate).':'.
                   1999:                    &escape($rolelist), $tryserver))) {
                   2000:                 my($key,$value) = split(/\=/,$_);
                   2001:                 if (($key) && ($value)) {
                   2002:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2003:                 }
                   2004:             }
                   2005:         }
                   2006:     }
                   2007:     return %personnel;
                   2008: }
1.658     raeburn  2009: 
1.149     www      2010: # ----------------------------------------------------------- Check out an item
                   2011: 
1.504     albertel 2012: sub get_first_access {
                   2013:     my ($type,$argsymb)=@_;
                   2014:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2015:     if ($argsymb) { $symb=$argsymb; }
                   2016:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2017:     if ($type eq 'map') {
                   2018: 	$res=&symbread($map);
                   2019:     } else {
                   2020: 	$res=$symb;
                   2021:     }
                   2022:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2023:     return $times{"$courseid\0$res"};
1.504     albertel 2024: }
                   2025: 
                   2026: sub set_first_access {
                   2027:     my ($type)=@_;
                   2028:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   2029:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2030:     if ($type eq 'map') {
                   2031: 	$res=&symbread($map);
                   2032:     } else {
                   2033: 	$res=$symb;
                   2034:     }
                   2035:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2036:     if (!$firstaccess) {
1.588     albertel 2037: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2038:     }
                   2039:     return 'already_set';
1.504     albertel 2040: }
                   2041: 
1.149     www      2042: sub checkout {
                   2043:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2044:     my $now=time;
                   2045:     my $lonhost=$perlvar{'lonHostID'};
                   2046:     my $infostr=&escape(
1.234     www      2047:                  'CHECKOUTTOKEN&'.
1.149     www      2048:                  $tuname.'&'.
                   2049:                  $tudom.'&'.
                   2050:                  $tcrsid.'&'.
                   2051:                  $symb.'&'.
                   2052: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2053:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2054:     if ($token=~/^error\:/) { 
1.672     albertel 2055:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2056:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2057:                  "</font>");
                   2058:         return ''; 
                   2059:     }
                   2060: 
1.149     www      2061:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2062:     $token=~tr/a-z/A-Z/;
                   2063: 
1.153     www      2064:     my %infohash=('resource.0.outtoken' => $token,
                   2065:                   'resource.0.checkouttime' => $now,
                   2066:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2067: 
                   2068:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2069:        return '';
1.151     www      2070:     } else {
1.672     albertel 2071:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2072:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2073:                  "</font>");
1.149     www      2074:     }    
                   2075: 
                   2076:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2077:                          &escape('Checkout '.$infostr.' - '.
                   2078:                                                  $token)) ne 'ok') {
                   2079: 	return '';
1.151     www      2080:     } else {
1.672     albertel 2081:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2082:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2083:                  "</font>");
1.149     www      2084:     }
1.151     www      2085:     return $token;
1.149     www      2086: }
                   2087: 
                   2088: # ------------------------------------------------------------ Check in an item
                   2089: 
                   2090: sub checkin {
                   2091:     my $token=shift;
1.150     www      2092:     my $now=time;
                   2093:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2094:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2095:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2096:     $dtoken=~s/\W/\_/g;
1.234     www      2097:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2098:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2099: 
1.154     www      2100:     unless (($tuname) && ($tudom)) {
                   2101:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2102:         return '';
                   2103:     }
                   2104:     
                   2105:     unless (&allowed('mgr',$tcrsid)) {
                   2106:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2107:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2108:         return '';
                   2109:     }
                   2110: 
1.153     www      2111:     my %infohash=('resource.0.intoken' => $token,
                   2112:                   'resource.0.checkintime' => $now,
                   2113:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2114: 
                   2115:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2116:        return '';
                   2117:     }    
                   2118: 
                   2119:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2120:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2121: 	return '';
                   2122:     }
                   2123: 
                   2124:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2125: }
                   2126: 
                   2127: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2128: 
                   2129: sub expirespread {
                   2130:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2131:     my $cid=$env{'request.course.id'}; 
1.110     www      2132:     if ($cid) {
                   2133:        my $now=time;
                   2134:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2135:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2136:                             $env{'course.'.$cid.'.num'}.
1.110     www      2137: 	        	    ':nohist_expirationdates:'.
                   2138:                             &escape($key).'='.$now,
1.620     albertel 2139:                             $env{'course.'.$cid.'.home'})
1.110     www      2140:     }
                   2141:     return 'ok';
1.14      www      2142: }
                   2143: 
1.109     www      2144: # ----------------------------------------------------- Devalidate Spreadsheets
                   2145: 
                   2146: sub devalidate {
1.325     www      2147:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2148:     my $cid=$env{'request.course.id'}; 
1.109     www      2149:     if ($cid) {
1.391     matthew  2150:         # delete the stored spreadsheets for
                   2151:         # - the student level sheet of this user in course's homespace
                   2152:         # - the assessment level sheet for this resource 
                   2153:         #   for this user in user's homespace
1.553     albertel 2154: 	# - current conditional state info
1.325     www      2155: 	my $key=$uname.':'.$udom.':';
1.109     www      2156:         my $status=
1.299     matthew  2157: 	    &del('nohist_calculatedsheets',
1.391     matthew  2158: 		 [$key.'studentcalc:'],
1.620     albertel 2159: 		 $env{'course.'.$cid.'.domain'},
                   2160: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2161: 		.' '.
                   2162: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2163: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2164:         unless ($status eq 'ok ok') {
                   2165:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2166:                     $uname.' at '.$udom.' for '.
1.109     www      2167: 		    $symb.': '.$status);
1.133     albertel 2168:         }
1.553     albertel 2169: 	&delenv('user.state.'.$cid);
1.109     www      2170:     }
                   2171: }
                   2172: 
1.265     albertel 2173: sub get_scalar {
                   2174:     my ($string,$end) = @_;
                   2175:     my $value;
                   2176:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2177: 	$value = $1;
                   2178:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2179: 	$value = $1;
                   2180:     }
                   2181:     return &unescape($value);
                   2182: }
                   2183: 
                   2184: sub array2str {
                   2185:   my (@array) = @_;
                   2186:   my $result=&arrayref2str(\@array);
                   2187:   $result=~s/^__ARRAY_REF__//;
                   2188:   $result=~s/__END_ARRAY_REF__$//;
                   2189:   return $result;
                   2190: }
                   2191: 
1.204     albertel 2192: sub arrayref2str {
                   2193:   my ($arrayref) = @_;
1.265     albertel 2194:   my $result='__ARRAY_REF__';
1.204     albertel 2195:   foreach my $elem (@$arrayref) {
1.265     albertel 2196:     if(ref($elem) eq 'ARRAY') {
                   2197:       $result.=&arrayref2str($elem).'&';
                   2198:     } elsif(ref($elem) eq 'HASH') {
                   2199:       $result.=&hashref2str($elem).'&';
                   2200:     } elsif(ref($elem)) {
                   2201:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2202:     } else {
                   2203:       $result.=&escape($elem).'&';
                   2204:     }
                   2205:   }
                   2206:   $result=~s/\&$//;
1.265     albertel 2207:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2208:   return $result;
                   2209: }
                   2210: 
1.168     albertel 2211: sub hash2str {
1.204     albertel 2212:   my (%hash) = @_;
                   2213:   my $result=&hashref2str(\%hash);
1.265     albertel 2214:   $result=~s/^__HASH_REF__//;
                   2215:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2216:   return $result;
                   2217: }
                   2218: 
                   2219: sub hashref2str {
                   2220:   my ($hashref)=@_;
1.265     albertel 2221:   my $result='__HASH_REF__';
1.495     albertel 2222:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2223:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2224:       $result.=&arrayref2str($_).'=';
1.204     albertel 2225:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2226:       $result.=&hashref2str($_).'=';
1.204     albertel 2227:     } elsif (ref($_)) {
1.265     albertel 2228:       $result.='=';
                   2229:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2230:     } else {
1.265     albertel 2231: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2232:     }
                   2233: 
1.265     albertel 2234:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2235:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2236:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2237:       $result.=&hashref2str($hashref->{$_}).'&';
                   2238:     } elsif(ref($hashref->{$_})) {
                   2239:        $result.='&';
                   2240:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2241:     } else {
1.265     albertel 2242:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2243:     }
                   2244:   }
1.168     albertel 2245:   $result=~s/\&$//;
1.265     albertel 2246:   $result .= '__END_HASH_REF__';
1.168     albertel 2247:   return $result;
                   2248: }
                   2249: 
                   2250: sub str2hash {
1.265     albertel 2251:     my ($string)=@_;
                   2252:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2253:     return %$hash;
                   2254: }
                   2255: 
                   2256: sub str2hashref {
1.168     albertel 2257:   my ($string) = @_;
1.265     albertel 2258: 
                   2259:   my %hash;
                   2260: 
                   2261:   if($string !~ /^__HASH_REF__/) {
                   2262:       if (! ($string eq '' || !defined($string))) {
                   2263: 	  $hash{'error'}='Not hash reference';
                   2264:       }
                   2265:       return (\%hash, $string);
                   2266:   }
                   2267: 
                   2268:   $string =~ s/^__HASH_REF__//;
                   2269: 
                   2270:   while($string !~ /^__END_HASH_REF__/) {
                   2271:       #key
                   2272:       my $key='';
                   2273:       if($string =~ /^__HASH_REF__/) {
                   2274:           ($key, $string)=&str2hashref($string);
                   2275:           if(defined($key->{'error'})) {
                   2276:               $hash{'error'}='Bad data';
                   2277:               return (\%hash, $string);
                   2278:           }
                   2279:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2280:           ($key, $string)=&str2arrayref($string);
                   2281:           if($key->[0] eq 'Array reference error') {
                   2282:               $hash{'error'}='Bad data';
                   2283:               return (\%hash, $string);
                   2284:           }
                   2285:       } else {
                   2286:           $string =~ s/^(.*?)=//;
1.267     albertel 2287: 	  $key=&unescape($1);
1.265     albertel 2288:       }
                   2289:       $string =~ s/^=//;
                   2290: 
                   2291:       #value
                   2292:       my $value='';
                   2293:       if($string =~ /^__HASH_REF__/) {
                   2294:           ($value, $string)=&str2hashref($string);
                   2295:           if(defined($value->{'error'})) {
                   2296:               $hash{'error'}='Bad data';
                   2297:               return (\%hash, $string);
                   2298:           }
                   2299:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2300:           ($value, $string)=&str2arrayref($string);
                   2301:           if($value->[0] eq 'Array reference error') {
                   2302:               $hash{'error'}='Bad data';
                   2303:               return (\%hash, $string);
                   2304:           }
                   2305:       } else {
                   2306: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2307:       }
                   2308:       $string =~ s/^&//;
                   2309: 
                   2310:       $hash{$key}=$value;
1.204     albertel 2311:   }
1.265     albertel 2312: 
                   2313:   $string =~ s/^__END_HASH_REF__//;
                   2314: 
                   2315:   return (\%hash, $string);
1.204     albertel 2316: }
                   2317: 
                   2318: sub str2array {
1.265     albertel 2319:     my ($string)=@_;
                   2320:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2321:     return @$array;
                   2322: }
                   2323: 
                   2324: sub str2arrayref {
1.204     albertel 2325:   my ($string) = @_;
1.265     albertel 2326:   my @array;
                   2327: 
                   2328:   if($string !~ /^__ARRAY_REF__/) {
                   2329:       if (! ($string eq '' || !defined($string))) {
                   2330: 	  $array[0]='Array reference error';
                   2331:       }
                   2332:       return (\@array, $string);
                   2333:   }
                   2334: 
                   2335:   $string =~ s/^__ARRAY_REF__//;
                   2336: 
                   2337:   while($string !~ /^__END_ARRAY_REF__/) {
                   2338:       my $value='';
                   2339:       if($string =~ /^__HASH_REF__/) {
                   2340:           ($value, $string)=&str2hashref($string);
                   2341:           if(defined($value->{'error'})) {
                   2342:               $array[0] ='Array reference error';
                   2343:               return (\@array, $string);
                   2344:           }
                   2345:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2346:           ($value, $string)=&str2arrayref($string);
                   2347:           if($value->[0] eq 'Array reference error') {
                   2348:               $array[0] ='Array reference error';
                   2349:               return (\@array, $string);
                   2350:           }
                   2351:       } else {
                   2352: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2353:       }
                   2354:       $string =~ s/^&//;
                   2355: 
                   2356:       push(@array, $value);
1.191     harris41 2357:   }
1.265     albertel 2358: 
                   2359:   $string =~ s/^__END_ARRAY_REF__//;
                   2360: 
                   2361:   return (\@array, $string);
1.168     albertel 2362: }
                   2363: 
1.167     albertel 2364: # -------------------------------------------------------------------Temp Store
                   2365: 
1.168     albertel 2366: sub tmpreset {
                   2367:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2368:   if (!$symb) {
                   2369:     $symb=&symbread();
1.620     albertel 2370:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2371:   }
                   2372:   $symb=escape($symb);
                   2373: 
1.620     albertel 2374:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2375:   $namespace=~s/\//\_/g;
                   2376:   $namespace=~s/\W//g;
                   2377: 
1.620     albertel 2378:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2379:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2380:   if ($domain eq 'public' && $stuname eq 'public') {
                   2381:       $stuname=$ENV{'REMOTE_ADDR'};
                   2382:   }
1.168     albertel 2383:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2384:   my %hash;
                   2385:   if (tie(%hash,'GDBM_File',
                   2386: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2387: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2388:     foreach my $key (keys %hash) {
1.180     albertel 2389:       if ($key=~ /:$symb/) {
1.168     albertel 2390: 	delete($hash{$key});
                   2391:       }
                   2392:     }
                   2393:   }
                   2394: }
                   2395: 
1.167     albertel 2396: sub tmpstore {
1.168     albertel 2397:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2398: 
                   2399:   if (!$symb) {
                   2400:     $symb=&symbread();
1.620     albertel 2401:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2402:   }
                   2403:   $symb=escape($symb);
                   2404: 
                   2405:   if (!$namespace) {
                   2406:     # I don't think we would ever want to store this for a course.
                   2407:     # it seems this will only be used if we don't have a course.
1.620     albertel 2408:     #$namespace=$env{'request.course.id'};
1.168     albertel 2409:     #if (!$namespace) {
1.620     albertel 2410:       $namespace=$env{'request.state'};
1.168     albertel 2411:     #}
                   2412:   }
                   2413:   $namespace=~s/\//\_/g;
                   2414:   $namespace=~s/\W//g;
1.620     albertel 2415:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2416:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2417:   if ($domain eq 'public' && $stuname eq 'public') {
                   2418:       $stuname=$ENV{'REMOTE_ADDR'};
                   2419:   }
1.168     albertel 2420:   my $now=time;
                   2421:   my %hash;
                   2422:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2423:   if (tie(%hash,'GDBM_File',
                   2424: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2425: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2426:     $hash{"version:$symb"}++;
                   2427:     my $version=$hash{"version:$symb"};
                   2428:     my $allkeys=''; 
                   2429:     foreach my $key (keys(%$storehash)) {
                   2430:       $allkeys.=$key.':';
1.591     albertel 2431:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2432:     }
                   2433:     $hash{"$version:$symb:timestamp"}=$now;
                   2434:     $allkeys.='timestamp';
                   2435:     $hash{"$version:keys:$symb"}=$allkeys;
                   2436:     if (untie(%hash)) {
                   2437:       return 'ok';
                   2438:     } else {
                   2439:       return "error:$!";
                   2440:     }
                   2441:   } else {
                   2442:     return "error:$!";
                   2443:   }
                   2444: }
1.167     albertel 2445: 
1.168     albertel 2446: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2447: 
1.168     albertel 2448: sub tmprestore {
                   2449:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2450: 
1.168     albertel 2451:   if (!$symb) {
                   2452:     $symb=&symbread();
1.620     albertel 2453:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2454:   }
                   2455:   $symb=escape($symb);
                   2456: 
1.620     albertel 2457:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2458: 
1.620     albertel 2459:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2460:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2461:   if ($domain eq 'public' && $stuname eq 'public') {
                   2462:       $stuname=$ENV{'REMOTE_ADDR'};
                   2463:   }
1.168     albertel 2464:   my %returnhash;
                   2465:   $namespace=~s/\//\_/g;
                   2466:   $namespace=~s/\W//g;
                   2467:   my %hash;
                   2468:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2469:   if (tie(%hash,'GDBM_File',
                   2470: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2471: 	  &GDBM_READER(),0640)) {
1.168     albertel 2472:     my $version=$hash{"version:$symb"};
                   2473:     $returnhash{'version'}=$version;
                   2474:     my $scope;
                   2475:     for ($scope=1;$scope<=$version;$scope++) {
                   2476:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2477:       my @keys=split(/:/,$vkeys);
                   2478:       my $key;
                   2479:       $returnhash{"$scope:keys"}=$vkeys;
                   2480:       foreach $key (@keys) {
1.591     albertel 2481: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2482: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2483:       }
                   2484:     }
1.168     albertel 2485:     if (!(untie(%hash))) {
                   2486:       return "error:$!";
                   2487:     }
                   2488:   } else {
                   2489:     return "error:$!";
                   2490:   }
                   2491:   return %returnhash;
1.167     albertel 2492: }
                   2493: 
1.9       www      2494: # ----------------------------------------------------------------------- Store
                   2495: 
                   2496: sub store {
1.124     www      2497:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2498:     my $home='';
                   2499: 
1.168     albertel 2500:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2501: 
1.213     www      2502:     $symb=&symbclean($symb);
1.122     albertel 2503:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2504: 
1.620     albertel 2505:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2506:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2507: 
                   2508:     &devalidate($symb,$stuname,$domain);
1.109     www      2509: 
                   2510:     $symb=escape($symb);
1.187     www      2511:     if (!$namespace) { 
1.620     albertel 2512:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2513:           return ''; 
                   2514:        } 
                   2515:     }
1.620     albertel 2516:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2517: 
                   2518:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2519:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2520: 
1.12      www      2521:     my $namevalue='';
1.191     harris41 2522:     foreach (keys %$storehash) {
1.591     albertel 2523:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2524:     }
1.12      www      2525:     $namevalue=~s/\&$//;
1.187     www      2526:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2527:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2528: }
                   2529: 
1.47      www      2530: # -------------------------------------------------------------- Critical Store
                   2531: 
                   2532: sub cstore {
1.124     www      2533:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2534:     my $home='';
                   2535: 
1.168     albertel 2536:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2537: 
1.213     www      2538:     $symb=&symbclean($symb);
1.122     albertel 2539:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2540: 
1.620     albertel 2541:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2542:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2543: 
                   2544:     &devalidate($symb,$stuname,$domain);
1.109     www      2545: 
                   2546:     $symb=escape($symb);
1.187     www      2547:     if (!$namespace) { 
1.620     albertel 2548:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2549:           return ''; 
                   2550:        } 
                   2551:     }
1.620     albertel 2552:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2553: 
                   2554:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2555:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2556: 
1.47      www      2557:     my $namevalue='';
1.191     harris41 2558:     foreach (keys %$storehash) {
1.591     albertel 2559:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2560:     }
1.47      www      2561:     $namevalue=~s/\&$//;
1.187     www      2562:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2563:     return critical
                   2564:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2565: }
                   2566: 
1.9       www      2567: # --------------------------------------------------------------------- Restore
                   2568: 
                   2569: sub restore {
1.124     www      2570:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2571:     my $home='';
                   2572: 
1.168     albertel 2573:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2574: 
1.122     albertel 2575:     if (!$symb) {
                   2576:       unless ($symb=escape(&symbread())) { return ''; }
                   2577:     } else {
1.213     www      2578:       $symb=&escape(&symbclean($symb));
1.122     albertel 2579:     }
1.188     www      2580:     if (!$namespace) { 
1.620     albertel 2581:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2582:           return ''; 
                   2583:        } 
                   2584:     }
1.620     albertel 2585:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2586:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2587:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2588:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2589: 
1.12      www      2590:     my %returnhash=();
1.191     harris41 2591:     foreach (split(/\&/,$answer)) {
1.12      www      2592: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2593:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2594:     }
1.75      www      2595:     my $version;
                   2596:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2597:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2598:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2599:        }
1.75      www      2600:     }
1.13      www      2601:     return %returnhash;
1.34      www      2602: }
                   2603: 
                   2604: # ---------------------------------------------------------- Course Description
                   2605: 
                   2606: sub coursedescription {
1.731     albertel 2607:     my ($courseid,$args)=@_;
1.34      www      2608:     $courseid=~s/^\///;
1.49      www      2609:     $courseid=~s/\_/\//g;
1.34      www      2610:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2611:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2612:     my $normalid=$cdomain.'_'.$cnum;
                   2613:     # need to always cache even if we get errors otherwise we keep 
                   2614:     # trying and trying and trying to get the course description.
                   2615:     my %envhash=();
                   2616:     my %returnhash=();
1.731     albertel 2617:     
                   2618:     my $expiretime=600;
                   2619:     if ($env{'request.course.id'} eq $normalid) {
                   2620: 	$expiretime=120;
                   2621:     }
                   2622: 
                   2623:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2624:     if (!$args->{'freshen_cache'}
                   2625: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2626: 	foreach my $key (keys(%env)) {
                   2627: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2628: 	    my ($setting) = $1;
                   2629: 	    $returnhash{$setting} = $env{$key};
                   2630: 	}
                   2631: 	return %returnhash;
                   2632:     }
                   2633: 
                   2634:     # get the data agin
                   2635:     if (!$args->{'one_time'}) {
                   2636: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2637:     }
1.34      www      2638:     if ($chome ne 'no_host') {
1.302     albertel 2639:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2640:        if (!exists($returnhash{'con_lost'})) {
                   2641:            $returnhash{'home'}= $chome;
                   2642: 	   $returnhash{'domain'} = $cdomain;
                   2643: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2644:            if (!defined($returnhash{'type'})) {
                   2645:                $returnhash{'type'} = 'Course';
                   2646:            }
1.130     albertel 2647:            while (my ($name,$value) = each %returnhash) {
1.53      www      2648:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2649:            }
1.270     www      2650:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2651:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2652: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2653:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2654:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2655:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2656:        }
                   2657:     }
1.731     albertel 2658:     if (!$args->{'one_time'}) {
                   2659: 	&appenv(%envhash);
                   2660:     }
1.302     albertel 2661:     return %returnhash;
1.461     www      2662: }
                   2663: 
                   2664: # -------------------------------------------------See if a user is privileged
                   2665: 
                   2666: sub privileged {
                   2667:     my ($username,$domain)=@_;
                   2668:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2669: 			&homeserver($username,$domain));
                   2670:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2671:     my $now=time;
                   2672:     if ($rolesdump ne '') {
                   2673:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2674: 	    if ($_!~/^rolesdef_/) {
1.461     www      2675: 		my ($area,$role)=split(/=/,$_);
                   2676: 		$area=~s/\_\w\w$//;
                   2677: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2678: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2679: 		    my $active=1;
                   2680: 		    if ($tend) {
                   2681: 			if ($tend<$now) { $active=0; }
                   2682: 		    }
                   2683: 		    if ($tstart) {
                   2684: 			if ($tstart>$now) { $active=0; }
                   2685: 		    }
                   2686: 		    if ($active) { return 1; }
                   2687: 		}
                   2688: 	    }
                   2689: 	}
                   2690:     }
                   2691:     return 0;
1.9       www      2692: }
1.1       albertel 2693: 
1.103     harris41 2694: # -------------------------------------------------------- Get user privileges
1.11      www      2695: 
                   2696: sub rolesinit {
                   2697:     my ($domain,$username,$authhost)=@_;
                   2698:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2699:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2700:     my %allroles=();
1.678     raeburn  2701:     my %allgroups=();   
1.11      www      2702:     my $now=time;
1.743     albertel 2703:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2704:     my $group_privs;
1.11      www      2705: 
                   2706:     if ($rolesdump ne '') {
1.191     harris41 2707:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2708: 	  if ($_!~/^rolesdef_/) {
1.11      www      2709:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2710: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2711:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2712: 	    if ($role=~/^cr/) { 
1.655     albertel 2713: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2714: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2715: 		    ($tend,$tstart)=split('_',$trest);
                   2716: 		} else {
                   2717: 		    $trole=$role;
                   2718: 		}
1.678     raeburn  2719:             } elsif ($role =~ m|^gr/|) {
                   2720:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2721:                 ($trole,$group_privs) = split(/\//,$trole);
                   2722:                 $group_privs = &unescape($group_privs);
1.587     albertel 2723: 	    } else {
                   2724: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2725: 	    }
1.743     albertel 2726: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2727: 					 $username);
                   2728: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2729:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2730:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2731:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2732: 		my $spec=$trole.'.'.$area;
                   2733: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2734: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2735:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2736:                 } elsif ($trole eq 'gr') {
                   2737:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2738: 		} else {
1.567     raeburn  2739:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2740: 		}
1.12      www      2741:             }
1.662     raeburn  2742:           }
1.191     harris41 2743:         }
1.743     albertel 2744:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2745:         $userroles{'user.adv'}    = $adv;
                   2746: 	$userroles{'user.author'} = $author;
1.620     albertel 2747:         $env{'user.adv'}=$adv;
1.11      www      2748:     }
1.743     albertel 2749:     return \%userroles;  
1.11      www      2750: }
                   2751: 
1.567     raeburn  2752: sub set_arearole {
                   2753:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2754: # log the associated role with the area
                   2755:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2756:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2757: }
                   2758: 
                   2759: sub custom_roleprivs {
                   2760:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2761:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2762:     my $homsvr=homeserver($rauthor,$rdomain);
                   2763:     if ($hostname{$homsvr} ne '') {
                   2764:         my ($rdummy,$roledef)=
                   2765:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2766:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2767:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2768:             if (defined($syspriv)) {
                   2769:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2770:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2771:             }
                   2772:             if ($tdomain ne '') {
                   2773:                 if (defined($dompriv)) {
                   2774:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2775:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2776:                 }
                   2777:                 if (($trest ne '') && (defined($coursepriv))) {
                   2778:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2779:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2780:                 }
                   2781:             }
                   2782:         }
                   2783:     }
                   2784: }
                   2785: 
1.678     raeburn  2786: sub group_roleprivs {
                   2787:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2788:     my $access = 1;
                   2789:     my $now = time;
                   2790:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2791:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2792:     if ($access) {
                   2793:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2794:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2795:     }
                   2796: }
1.567     raeburn  2797: 
                   2798: sub standard_roleprivs {
                   2799:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2800:     if (defined($pr{$trole.':s'})) {
                   2801:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2802:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2803:     }
                   2804:     if ($tdomain ne '') {
                   2805:         if (defined($pr{$trole.':d'})) {
                   2806:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2807:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2808:         }
                   2809:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2810:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2811:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2812:         }
                   2813:     }
                   2814: }
                   2815: 
                   2816: sub set_userprivs {
1.678     raeburn  2817:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2818:     my $author=0;
                   2819:     my $adv=0;
1.678     raeburn  2820:     my %grouproles = ();
                   2821:     if (keys(%{$allgroups}) > 0) {
                   2822:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2823:             my ($trole,$area,$sec,$extendedarea);
1.771     raeburn  2824:             if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
1.678     raeburn  2825:                 $trole = $1;
                   2826:                 $area = $2;
1.681     raeburn  2827:                 $sec = $3;
                   2828:                 $extendedarea = $area.$sec;
                   2829:                 if (exists($$allgroups{$area})) {
                   2830:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2831:                         my $spec = $trole.'.'.$extendedarea;
                   2832:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2833:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2834:                     }
                   2835:                 }
                   2836:             }
                   2837:         }
                   2838:     }
                   2839:     foreach (keys(%grouproles)) {
                   2840:         $$allroles{$_} = $grouproles{$_};
                   2841:     }
1.567     raeburn  2842:     foreach (keys %{$allroles}) {
                   2843:         my %thesepriv=();
                   2844:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2845:         foreach (split(/:/,$$allroles{$_})) {
                   2846:             if ($_ ne '') {
                   2847:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2848:                 if ($restrictions eq '') {
                   2849:                     $thesepriv{$privilege}='F';
                   2850:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2851:                     $thesepriv{$privilege}.=$restrictions;
                   2852:                 }
                   2853:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2854:             }
                   2855:         }
                   2856:         my $thesestr='';
                   2857:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.743     albertel 2858:         $userroles->{'user.priv.'.$_} = $thesestr;
1.567     raeburn  2859:     }
                   2860:     return ($author,$adv);
                   2861: }
                   2862: 
1.12      www      2863: # --------------------------------------------------------------- get interface
                   2864: 
                   2865: sub get {
1.131     albertel 2866:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2867:    my $items='';
1.191     harris41 2868:    foreach (@$storearr) {
1.12      www      2869:        $items.=escape($_).'&';
1.191     harris41 2870:    }
1.12      www      2871:    $items=~s/\&$//;
1.620     albertel 2872:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2873:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2874:    my $uhome=&homeserver($uname,$udomain);
                   2875: 
1.133     albertel 2876:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2877:    my @pairs=split(/\&/,$rep);
1.273     albertel 2878:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2879:      return @pairs;
                   2880:    }
1.15      www      2881:    my %returnhash=();
1.42      www      2882:    my $i=0;
1.191     harris41 2883:    foreach (@$storearr) {
1.557     albertel 2884:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2885:       $i++;
1.191     harris41 2886:    }
1.15      www      2887:    return %returnhash;
1.27      www      2888: }
                   2889: 
                   2890: # --------------------------------------------------------------- del interface
                   2891: 
                   2892: sub del {
1.133     albertel 2893:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2894:    my $items='';
1.191     harris41 2895:    foreach (@$storearr) {
1.27      www      2896:        $items.=escape($_).'&';
1.191     harris41 2897:    }
1.27      www      2898:    $items=~s/\&$//;
1.620     albertel 2899:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2900:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2901:    my $uhome=&homeserver($uname,$udomain);
                   2902: 
                   2903:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2904: }
                   2905: 
                   2906: # -------------------------------------------------------------- dump interface
                   2907: 
                   2908: sub dump {
1.755     albertel 2909:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2910:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2911:     if (!$uname) { $uname=$env{'user.name'}; }
                   2912:     my $uhome=&homeserver($uname,$udomain);
                   2913:     if ($regexp) {
                   2914: 	$regexp=&escape($regexp);
                   2915:     } else {
                   2916: 	$regexp='.';
                   2917:     }
                   2918:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   2919:     my @pairs=split(/\&/,$rep);
                   2920:     my %returnhash=();
                   2921:     foreach my $item (@pairs) {
                   2922: 	my ($key,$value)=split(/=/,$item,2);
                   2923: 	$key = &unescape($key);
                   2924: 	next if ($key =~ /^error: 2 /);
                   2925: 	$returnhash{$key}=&thaw_unescape($value);
                   2926:     }
                   2927:     return %returnhash;
1.407     www      2928: }
                   2929: 
1.717     albertel 2930: # --------------------------------------------------------- dumpstore interface
                   2931: 
                   2932: sub dumpstore {
                   2933:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2934:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2935: }
                   2936: 
1.407     www      2937: # -------------------------------------------------------------- keys interface
                   2938: 
                   2939: sub getkeys {
                   2940:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2941:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2942:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2943:    my $uhome=&homeserver($uname,$udomain);
                   2944:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2945:    my @keyarray=();
                   2946:    foreach (split(/\&/,$rep)) {
                   2947:       push (@keyarray,&unescape($_));
                   2948:    }
                   2949:    return @keyarray;
1.318     matthew  2950: }
                   2951: 
1.319     matthew  2952: # --------------------------------------------------------------- currentdump
                   2953: sub currentdump {
1.328     matthew  2954:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2955:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2956:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2957:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2958:    my $uhome = &homeserver($sname,$sdom);
                   2959:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2960:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2961:    #
1.318     matthew  2962:    my %returnhash=();
1.319     matthew  2963:    #
                   2964:    if ($rep eq "unknown_cmd") { 
                   2965:        # an old lond will not know currentdump
                   2966:        # Do a dump and make it look like a currentdump
1.326     matthew  2967:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2968:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2969:        my %hash = @tmp;
                   2970:        @tmp=();
1.424     matthew  2971:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  2972:    } else {
                   2973:        my @pairs=split(/\&/,$rep);
                   2974:        foreach (@pairs) {
                   2975:            my ($key,$value)=split(/=/,$_);
                   2976:            my ($symb,$param) = split(/:/,$key);
                   2977:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 2978:                                                         &thaw_unescape($value);
1.319     matthew  2979:        }
1.191     harris41 2980:    }
1.12      www      2981:    return %returnhash;
1.424     matthew  2982: }
                   2983: 
                   2984: sub convert_dump_to_currentdump{
                   2985:     my %hash = %{shift()};
                   2986:     my %returnhash;
                   2987:     # Code ripped from lond, essentially.  The only difference
                   2988:     # here is the unescaping done by lonnet::dump().  Conceivably
                   2989:     # we might run in to problems with parameter names =~ /^v\./
                   2990:     while (my ($key,$value) = each(%hash)) {
                   2991:         my ($v,$symb,$param) = split(/:/,$key);
                   2992:         next if ($v eq 'version' || $symb eq 'keys');
                   2993:         next if (exists($returnhash{$symb}) &&
                   2994:                  exists($returnhash{$symb}->{$param}) &&
                   2995:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   2996:         $returnhash{$symb}->{$param}=$value;
                   2997:         $returnhash{$symb}->{'v.'.$param}=$v;
                   2998:     }
                   2999:     #
                   3000:     # Remove all of the keys in the hashes which keep track of
                   3001:     # the version of the parameter.
                   3002:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3003:         # use a foreach because we are going to delete from the hash.
                   3004:         foreach my $key (keys(%$param_hash)) {
                   3005:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3006:         }
                   3007:     }
                   3008:     return \%returnhash;
1.12      www      3009: }
                   3010: 
1.627     albertel 3011: # ------------------------------------------------------ critical inc interface
                   3012: 
                   3013: sub cinc {
                   3014:     return &inc(@_,'critical');
                   3015: }
                   3016: 
1.449     matthew  3017: # --------------------------------------------------------------- inc interface
                   3018: 
                   3019: sub inc {
1.627     albertel 3020:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3021:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3022:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3023:     my $uhome=&homeserver($uname,$udomain);
                   3024:     my $items='';
                   3025:     if (! ref($store)) {
                   3026:         # got a single value, so use that instead
                   3027:         $items = &escape($store).'=&';
                   3028:     } elsif (ref($store) eq 'SCALAR') {
                   3029:         $items = &escape($$store).'=&';        
                   3030:     } elsif (ref($store) eq 'ARRAY') {
                   3031:         $items = join('=&',map {&escape($_);} @{$store});
                   3032:     } elsif (ref($store) eq 'HASH') {
                   3033:         while (my($key,$value) = each(%{$store})) {
                   3034:             $items.= &escape($key).'='.&escape($value).'&';
                   3035:         }
                   3036:     }
                   3037:     $items=~s/\&$//;
1.627     albertel 3038:     if ($critical) {
                   3039: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3040:     } else {
                   3041: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3042:     }
1.449     matthew  3043: }
                   3044: 
1.12      www      3045: # --------------------------------------------------------------- put interface
                   3046: 
                   3047: sub put {
1.134     albertel 3048:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3049:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3050:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3051:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3052:    my $items='';
1.191     harris41 3053:    foreach (keys %$storehash) {
1.557     albertel 3054:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3055:    }
1.12      www      3056:    $items=~s/\&$//;
1.134     albertel 3057:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3058: }
                   3059: 
1.631     albertel 3060: # ------------------------------------------------------------ newput interface
                   3061: 
                   3062: sub newput {
                   3063:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3064:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3065:    if (!$uname) { $uname=$env{'user.name'}; }
                   3066:    my $uhome=&homeserver($uname,$udomain);
                   3067:    my $items='';
                   3068:    foreach my $key (keys(%$storehash)) {
                   3069:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3070:    }
                   3071:    $items=~s/\&$//;
                   3072:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3073: }
                   3074: 
                   3075: # ---------------------------------------------------------  putstore interface
                   3076: 
1.524     raeburn  3077: sub putstore {
1.715     albertel 3078:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3079:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3080:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3081:    my $uhome=&homeserver($uname,$udomain);
                   3082:    my $items='';
1.715     albertel 3083:    foreach my $key (keys(%$storehash)) {
                   3084:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3085:    }
1.715     albertel 3086:    $items=~s/\&$//;
1.716     albertel 3087:    my $esc_symb=&escape($symb);
                   3088:    my $esc_v=&escape($version);
1.715     albertel 3089:    my $reply =
1.716     albertel 3090:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3091: 	      $uhome);
                   3092:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3093:        # gfall back to way things use to be done
1.715     albertel 3094:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3095: 			    $uname);
1.524     raeburn  3096:    }
1.715     albertel 3097:    return $reply;
                   3098: }
                   3099: 
                   3100: sub old_putstore {
1.716     albertel 3101:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3102:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3103:     if (!$uname) { $uname=$env{'user.name'}; }
                   3104:     my $uhome=&homeserver($uname,$udomain);
                   3105:     my %newstorehash;
                   3106:     foreach (keys %$storehash) {
                   3107: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3108: 	$newstorehash{$key} = $storehash->{$_};
                   3109:     }
                   3110:     my $items='';
                   3111:     my %allitems = ();
                   3112:     foreach (keys %newstorehash) {
                   3113: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3114: 	    my $key = $1.':keys:'.$2;
                   3115: 	    $allitems{$key} .= $3.':';
                   3116: 	}
                   3117: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3118:     }
                   3119:     foreach (keys %allitems) {
                   3120: 	$allitems{$_} =~ s/\:$//;
                   3121: 	$items.= $_.'='.$allitems{$_}.'&';
                   3122:     }
                   3123:     $items=~s/\&$//;
                   3124:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3125: }
                   3126: 
1.47      www      3127: # ------------------------------------------------------ critical put interface
                   3128: 
                   3129: sub cput {
1.134     albertel 3130:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3131:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3132:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3133:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3134:    my $items='';
1.191     harris41 3135:    foreach (keys %$storehash) {
1.715     albertel 3136:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3137:    }
1.47      www      3138:    $items=~s/\&$//;
1.134     albertel 3139:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3140: }
                   3141: 
                   3142: # -------------------------------------------------------------- eget interface
                   3143: 
                   3144: sub eget {
1.133     albertel 3145:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3146:    my $items='';
1.191     harris41 3147:    foreach (@$storearr) {
1.12      www      3148:        $items.=escape($_).'&';
1.191     harris41 3149:    }
1.12      www      3150:    $items=~s/\&$//;
1.620     albertel 3151:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3152:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3153:    my $uhome=&homeserver($uname,$udomain);
                   3154:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3155:    my @pairs=split(/\&/,$rep);
                   3156:    my %returnhash=();
1.42      www      3157:    my $i=0;
1.191     harris41 3158:    foreach (@$storearr) {
1.557     albertel 3159:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3160:       $i++;
1.191     harris41 3161:    }
1.12      www      3162:    return %returnhash;
                   3163: }
                   3164: 
1.667     albertel 3165: # ------------------------------------------------------------ tmpput interface
                   3166: sub tmpput {
                   3167:     my ($storehash,$server)=@_;
                   3168:     my $items='';
                   3169:     foreach (keys(%$storehash)) {
                   3170: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3171:     }
                   3172:     $items=~s/\&$//;
                   3173:     return &reply("tmpput:$items",$server);
                   3174: }
                   3175: 
                   3176: # ------------------------------------------------------------ tmpget interface
                   3177: sub tmpget {
1.688     albertel 3178:     my ($token,$server)=@_;
                   3179:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3180:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3181:     my %returnhash;
                   3182:     foreach my $item (split(/\&/,$rep)) {
                   3183: 	my ($key,$value)=split(/=/,$item);
                   3184: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3185:     }
                   3186:     return %returnhash;
                   3187: }
                   3188: 
1.688     albertel 3189: # ------------------------------------------------------------ tmpget interface
                   3190: sub tmpdel {
                   3191:     my ($token,$server)=@_;
                   3192:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3193:     return &reply("tmpdel:$token",$server);
                   3194: }
                   3195: 
1.765     albertel 3196: # -------------------------------------------------- portfolio access checking
                   3197: 
                   3198: sub portfolio_access {
1.766     albertel 3199:     my ($requrl) = @_;
1.765     albertel 3200:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3201:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
                   3202:     if ($result eq 'ok') {
1.766     albertel 3203:        return 'F';
1.765     albertel 3204:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3205:        return 'A';
1.765     albertel 3206:     }
1.766     albertel 3207:     return '';
1.765     albertel 3208: }
                   3209: 
                   3210: sub get_portfolio_access {
1.767     albertel 3211:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3212: 
                   3213:     if (!ref($access_hash)) {
                   3214: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3215: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3216: 						   $file_name);
                   3217: 	$access_hash = $access_controls{$file_name};
                   3218:     }
                   3219: 
1.765     albertel 3220:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3221:     my $now = time;
                   3222:     if (ref($access_hash) eq 'HASH') {
                   3223:         foreach my $key (keys(%{$access_hash})) {
                   3224:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3225:             if ($start > $now) {
                   3226:                 next;
                   3227:             }
                   3228:             if ($end && $end<$now) {
                   3229:                 next;
                   3230:             }
                   3231:             if ($scope eq 'public') {
                   3232:                 $public = $key;
                   3233:                 last;
                   3234:             } elsif ($scope eq 'guest') {
                   3235:                 $guest = $key;
                   3236:             } elsif ($scope eq 'domains') {
                   3237:                 push(@domains,$key);
                   3238:             } elsif ($scope eq 'users') {
                   3239:                 push(@users,$key);
                   3240:             } elsif ($scope eq 'course') {
                   3241:                 push(@courses,$key);
                   3242:             } elsif ($scope eq 'group') {
                   3243:                 push(@groups,$key);
                   3244:             }
                   3245:         }
                   3246:         if ($public) {
                   3247:             return 'ok';
                   3248:         }
                   3249:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3250:             if ($guest) {
                   3251:                 return $guest;
                   3252:             }
                   3253:         } else {
                   3254:             if (@domains > 0) {
                   3255:                 foreach my $domkey (@domains) {
                   3256:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3257:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3258:                             return 'ok';
                   3259:                         }
                   3260:                     }
                   3261:                 }
                   3262:             }
                   3263:             if (@users > 0) {
                   3264:                 foreach my $userkey (@users) {
                   3265:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3266:                         return 'ok';
                   3267:                     }
                   3268:                 }
                   3269:             }
                   3270:             my %roleshash;
                   3271:             my @courses_and_groups = @courses;
                   3272:             push(@courses_and_groups,@groups); 
                   3273:             if (@courses_and_groups > 0) {
                   3274:                 my (%allgroups,%allroles); 
                   3275:                 my ($start,$end,$role,$sec,$group);
                   3276:                 foreach my $envkey (%env) {
                   3277:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3278:                         my $cid = $2.'_'.$3; 
                   3279:                         if ($1 eq 'gr') {
                   3280:                             $group = $4;
                   3281:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3282:                         } else {
                   3283:                             if ($4 eq '') {
                   3284:                                 $sec = 'none';
                   3285:                             } else {
                   3286:                                 $sec = $4;
                   3287:                             }
                   3288:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3289:                         }
                   3290:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3291:                         my $cid = $2.'_'.$3;
                   3292:                         if ($4 eq '') {
                   3293:                             $sec = 'none';
                   3294:                         } else {
                   3295:                             $sec = $4;
                   3296:                         }
                   3297:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3298:                     }
                   3299:                 }
                   3300:                 if (keys(%allroles) == 0) {
                   3301:                     return;
                   3302:                 }
                   3303:                 foreach my $key (@courses_and_groups) {
                   3304:                     my %content = %{$$access_hash{$key}};
                   3305:                     my $cnum = $content{'number'};
                   3306:                     my $cdom = $content{'domain'};
                   3307:                     my $cid = $cdom.'_'.$cnum;
                   3308:                     if (!exists($allroles{$cid})) {
                   3309:                         next;
                   3310:                     }    
                   3311:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3312:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3313:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3314:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3315:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3316:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3317:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3318:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3319:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3320:                                         if (grep/^all$/,@sections) {
                   3321:                                             return 'ok';
                   3322:                                         } else {
                   3323:                                             if (grep/^$sec$/,@sections) {
                   3324:                                                 return 'ok';
                   3325:                                             }
                   3326:                                         }
                   3327:                                     }
                   3328:                                 }
                   3329:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3330:                                     if (grep/^none$/,@groups) {
                   3331:                                         return 'ok';
                   3332:                                     }
                   3333:                                 } else {
                   3334:                                     if (grep/^all$/,@groups) {
                   3335:                                         return 'ok';
                   3336:                                     } 
                   3337:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3338:                                         if (grep/^$group$/,@groups) {
                   3339:                                             return 'ok';
                   3340:                                         }
                   3341:                                     }
                   3342:                                 } 
                   3343:                             }
                   3344:                         }
                   3345:                     }
                   3346:                 }
                   3347:             }
                   3348:             if ($guest) {
                   3349:                 return $guest;
                   3350:             }
                   3351:         }
                   3352:     }
                   3353:     return;
                   3354: }
                   3355: 
                   3356: sub course_group_datechecker {
                   3357:     my ($dates,$now,$status) = @_;
                   3358:     my ($start,$end) = split(/\./,$dates);
                   3359:     if (!$start && !$end) {
                   3360:         return 'ok';
                   3361:     }
                   3362:     if (grep/^active$/,@{$status}) {
                   3363:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3364:             return 'ok';
                   3365:         }
                   3366:     }
                   3367:     if (grep/^previous$/,@{$status}) {
                   3368:         if ($end > $now ) {
                   3369:             return 'ok';
                   3370:         }
                   3371:     }
                   3372:     if (grep/^future$/,@{$status}) {
                   3373:         if ($start > $now) {
                   3374:             return 'ok';
                   3375:         }
                   3376:     }
                   3377:     return; 
                   3378: }
                   3379: 
                   3380: sub parse_portfolio_url {
                   3381:     my ($url) = @_;
                   3382: 
                   3383:     my ($type,$udom,$unum,$group,$file_name);
                   3384:     
                   3385:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
                   3386: 	$type = 1;
                   3387:         $udom = $1;
                   3388:         $unum = $2;
                   3389:         $file_name = $3;
                   3390:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
                   3391: 	$type = 2;
                   3392:         $udom = $1;
                   3393:         $unum = $2;
                   3394:         $group = $3;
                   3395:         $file_name = $3.'/'.$4;
                   3396:     }
                   3397:     if (wantarray) {
                   3398: 	return ($type,$udom,$unum,$file_name,$group);
                   3399:     }
                   3400:     return $type;
                   3401: }
                   3402: 
                   3403: sub is_portfolio_url {
                   3404:     my ($url) = @_;
                   3405:     return scalar(&parse_portfolio_url($url));
                   3406: }
                   3407: 
1.341     www      3408: # ---------------------------------------------- Custom access rule evaluation
                   3409: 
                   3410: sub customaccess {
                   3411:     my ($priv,$uri)=@_;
1.620     albertel 3412:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3413:     $urealm=~s/^\W//;
                   3414:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3415:     my $access=0;
                   3416:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3417: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3418:         if ($role) {
                   3419: 	   if ($role ne $urole) { next; }
                   3420:         }
                   3421:         foreach (split(/\s*\,\s*/,$realm)) {
                   3422:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3423:             if ($tdom) {
                   3424: 		if ($tdom ne $udom) { next; }
                   3425:             }
                   3426:             if ($tcrs) {
                   3427: 		if ($tcrs ne $ucrs) { next; }
                   3428:             }
                   3429:             if ($tsec) {
                   3430: 		if ($tsec ne $usec) { next; }
                   3431:             }
                   3432:             $access=($effect eq 'allow');
                   3433:             last;
1.342     www      3434:         }
1.402     bowersj2 3435: 	if ($realm eq '' && $role eq '') {
                   3436:             $access=($effect eq 'allow');
                   3437: 	}
1.341     www      3438:     }
                   3439:     return $access;
                   3440: }
                   3441: 
1.103     harris41 3442: # ------------------------------------------------- Check for a user privilege
1.12      www      3443: 
                   3444: sub allowed {
1.579     albertel 3445:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3446:     my $ver_orguri=$uri;
1.439     www      3447:     $uri=&deversion($uri);
1.152     www      3448:     my $orguri=$uri;
1.52      www      3449:     $uri=&declutter($uri);
1.545     banghart 3450:     
1.620     albertel 3451:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3452: # Free bre access to adm and meta resources
1.775     albertel 3453:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3454: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3455: 	&& ($priv eq 'bre')) {
1.14      www      3456: 	return 'F';
1.159     www      3457:     }
                   3458: 
1.545     banghart 3459: # Free bre access to user's own portfolio contents
1.714     raeburn  3460:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3461:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3462: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3463:         return 'F';
                   3464:     }
                   3465: 
1.762     raeburn  3466: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3467:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3468:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3469:         if (exists($env{'request.course.id'})) {
                   3470:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3471:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3472:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3473:                 my $courseprivid=$env{'request.course.id'};
                   3474:                 $courseprivid=~s/\_/\//;
                   3475:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3476:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3477:                     return $1; 
1.762     raeburn  3478:                 } else {
                   3479:                     if ($env{'request.course.sec'}) {
                   3480:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3481:                     }
                   3482:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3483:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3484:                         return $2;
                   3485:                     }
1.714     raeburn  3486:                 }
                   3487:             }
                   3488:         }
                   3489:     }
                   3490: 
1.159     www      3491: # Free bre to public access
                   3492: 
                   3493:     if ($priv eq 'bre') {
1.238     www      3494:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3495: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3496:            return 'F'; 
                   3497:         }
1.238     www      3498:         if ($copyright eq 'priv') {
                   3499:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3500: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3501: 		return '';
                   3502:             }
                   3503:         }
                   3504:         if ($copyright eq 'domain') {
                   3505:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3506: 	    unless (($env{'user.domain'} eq $1) ||
                   3507:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3508: 		return '';
                   3509:             }
1.262     matthew  3510:         }
1.620     albertel 3511:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3512:             # Library role, so allow browsing of resources in this domain.
                   3513:             return 'F';
1.238     www      3514:         }
1.341     www      3515:         if ($copyright eq 'custom') {
                   3516: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3517:         }
1.14      www      3518:     }
1.264     matthew  3519:     # Domain coordinator is trying to create a course
1.620     albertel 3520:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3521:         # uri is the requested domain in this case.
                   3522:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3523:         # a role of dc for the domain in question.
1.620     albertel 3524:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3525:     }
1.29      www      3526: 
1.52      www      3527:     my $thisallowed='';
                   3528:     my $statecond=0;
                   3529:     my $courseprivid='';
                   3530: 
                   3531: # Course
                   3532: 
1.620     albertel 3533:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3534:        $thisallowed.=$1;
                   3535:     }
1.29      www      3536: 
1.52      www      3537: # Domain
                   3538: 
1.620     albertel 3539:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3540:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3541:        $thisallowed.=$1;
                   3542:     }
1.52      www      3543: 
                   3544: # Course: uri itself is a course
1.66      www      3545:     my $courseuri=$uri;
                   3546:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3547:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3548: 
1.620     albertel 3549:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3550:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3551:        $thisallowed.=$1;
                   3552:     }
1.29      www      3553: 
1.665     albertel 3554: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3555: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3556:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3557: 	$thisallowed='';
1.671     raeburn  3558:         my ($match)=&is_on_map($uri);
                   3559:         if ($match) {
                   3560:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3561:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3562:                 $thisallowed.=$1;
                   3563:             }
                   3564:         } else {
1.705     albertel 3565:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3566:             if ($refuri) {
                   3567:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3568:                     $thisallowed='F';
1.671     raeburn  3569:                 } else {
                   3570:                     $refuri=&declutter($refuri);
                   3571:                     my ($match) = &is_on_map($refuri);
                   3572:                     if ($match) {
                   3573:                         $thisallowed='F';
                   3574:                     }
1.669     raeburn  3575:                 }
1.671     raeburn  3576:             }
                   3577:         }
1.314     www      3578:     }
1.492     albertel 3579: 
1.766     albertel 3580:     if ($priv eq 'bre'
                   3581: 	&& $thisallowed ne 'F' 
                   3582: 	&& $thisallowed ne '2'
                   3583: 	&& &is_portfolio_url($uri)) {
                   3584: 	$thisallowed = &portfolio_access($uri);
                   3585:     }
                   3586:     
1.52      www      3587: # Full access at system, domain or course-wide level? Exit.
1.29      www      3588: 
                   3589:     if ($thisallowed=~/F/) {
                   3590: 	return 'F';
                   3591:     }
                   3592: 
1.52      www      3593: # If this is generating or modifying users, exit with special codes
1.29      www      3594: 
1.643     www      3595:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3596: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3597: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3598: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3599: 	    unless ($auname) { return $thisallowed; }
                   3600: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3601: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3602: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3603: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3604: 	}
1.52      www      3605: 	return $thisallowed;
                   3606:     }
                   3607: #
1.103     harris41 3608: # Gathered so far: system, domain and course wide privileges
1.52      www      3609: #
                   3610: # Course: See if uri or referer is an individual resource that is part of 
                   3611: # the course
                   3612: 
1.620     albertel 3613:     if ($env{'request.course.id'}) {
1.232     www      3614: 
1.620     albertel 3615:        $courseprivid=$env{'request.course.id'};
                   3616:        if ($env{'request.course.sec'}) {
                   3617:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3618:        }
                   3619:        $courseprivid=~s/\_/\//;
                   3620:        my $checkreferer=1;
1.232     www      3621:        my ($match,$cond)=&is_on_map($uri);
                   3622:        if ($match) {
                   3623:            $statecond=$cond;
1.620     albertel 3624:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3625:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3626:                $thisallowed.=$1;
                   3627:                $checkreferer=0;
                   3628:            }
1.29      www      3629:        }
1.83      www      3630:        
1.148     www      3631:        if ($checkreferer) {
1.620     albertel 3632: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3633:             unless ($refuri) {
1.620     albertel 3634:                 foreach (keys %env) {
1.148     www      3635: 		    if ($_=~/^httpref\..*\*/) {
                   3636: 			my $pattern=$_;
1.156     www      3637:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3638:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3639:                         $pattern=~s/\//\\\//g;
1.152     www      3640:                         if ($orguri=~/$pattern/) {
1.620     albertel 3641: 			    $refuri=$env{$_};
1.148     www      3642:                         }
                   3643:                     }
1.191     harris41 3644:                 }
1.148     www      3645:             }
1.232     www      3646: 
1.148     www      3647:          if ($refuri) { 
1.152     www      3648: 	  $refuri=&declutter($refuri);
1.232     www      3649:           my ($match,$cond)=&is_on_map($refuri);
                   3650:             if ($match) {
                   3651:               my $refstatecond=$cond;
1.620     albertel 3652:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3653:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3654:                   $thisallowed.=$1;
1.53      www      3655:                   $uri=$refuri;
                   3656:                   $statecond=$refstatecond;
1.52      www      3657:               }
                   3658:           }
1.148     www      3659:         }
1.29      www      3660:        }
1.52      www      3661:    }
1.29      www      3662: 
1.52      www      3663: #
1.103     harris41 3664: # Gathered now: all privileges that could apply, and condition number
1.52      www      3665: # 
                   3666: #
                   3667: # Full or no access?
                   3668: #
1.29      www      3669: 
1.52      www      3670:     if ($thisallowed=~/F/) {
                   3671: 	return 'F';
                   3672:     }
1.29      www      3673: 
1.52      www      3674:     unless ($thisallowed) {
                   3675:         return '';
                   3676:     }
1.29      www      3677: 
1.52      www      3678: # Restrictions exist, deal with them
                   3679: #
                   3680: #   C:according to course preferences
                   3681: #   R:according to resource settings
                   3682: #   L:unless locked
                   3683: #   X:according to user session state
                   3684: #
                   3685: 
                   3686: # Possibly locked functionality, check all courses
1.54      www      3687: # Locks might take effect only after 10 minutes cache expiration for other
                   3688: # courses, and 2 minutes for current course
1.52      www      3689: 
                   3690:     my $envkey;
                   3691:     if ($thisallowed=~/L/) {
1.620     albertel 3692:         foreach $envkey (keys %env) {
1.54      www      3693:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3694:                my $courseid=$2;
                   3695:                my $roleid=$1.'.'.$2;
1.92      www      3696:                $courseid=~s/^\///;
1.54      www      3697:                my $expiretime=600;
1.620     albertel 3698:                if ($env{'request.role'} eq $roleid) {
1.54      www      3699: 		  $expiretime=120;
                   3700:                }
                   3701: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3702:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3703:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3704: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3705:                }
1.620     albertel 3706:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3707:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3708: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3709:                        &log($env{'user.domain'},$env{'user.name'},
                   3710:                             $env{'user.home'},
1.57      www      3711:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3712:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3713:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3714: 		       return '';
                   3715:                    }
                   3716:                }
1.620     albertel 3717:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3718:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3719: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3720:                        &log($env{'user.domain'},$env{'user.name'},
                   3721:                             $env{'user.home'},
1.57      www      3722:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3723:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3724:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3725: 		       return '';
                   3726:                    }
                   3727:                }
                   3728: 	   }
1.29      www      3729:        }
1.52      www      3730:     }
                   3731:    
                   3732: #
                   3733: # Rest of the restrictions depend on selected course
                   3734: #
                   3735: 
1.620     albertel 3736:     unless ($env{'request.course.id'}) {
1.766     albertel 3737: 	if ($thisallowed eq 'A') {
                   3738: 	    return 'A';
                   3739: 	} else {
                   3740: 	    return '1';
                   3741: 	}
1.52      www      3742:     }
1.29      www      3743: 
1.52      www      3744: #
                   3745: # Now user is definitely in a course
                   3746: #
1.53      www      3747: 
                   3748: 
                   3749: # Course preferences
                   3750: 
                   3751:    if ($thisallowed=~/C/) {
1.620     albertel 3752:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3753:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3754:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3755: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3756: 	   if ($priv ne 'pch') { 
                   3757: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3758: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3759: 			$env{'request.course.id'});
                   3760: 	   }
1.237     www      3761:            return '';
                   3762:        }
                   3763: 
1.620     albertel 3764:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3765: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3766: 	   if ($priv ne 'pch') { 
                   3767: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3768: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3769: 			$env{'request.course.id'});
                   3770: 	   }
1.54      www      3771:            return '';
                   3772:        }
1.53      www      3773:    }
                   3774: 
                   3775: # Resource preferences
                   3776: 
                   3777:    if ($thisallowed=~/R/) {
1.620     albertel 3778:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3779:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3780: 	   if ($priv ne 'pch') { 
                   3781: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3782: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3783: 	   }
                   3784: 	   return '';
1.54      www      3785:        }
1.53      www      3786:    }
1.30      www      3787: 
1.246     www      3788: # Restricted by state or randomout?
1.30      www      3789: 
1.52      www      3790:    if ($thisallowed=~/X/) {
1.620     albertel 3791:       if ($env{'acc.randomout'}) {
1.579     albertel 3792: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3793:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3794:             return ''; 
                   3795:          }
1.247     www      3796:       }
                   3797:       if (&condval($statecond)) {
1.52      www      3798: 	 return '2';
                   3799:       } else {
                   3800:          return '';
                   3801:       }
                   3802:    }
1.30      www      3803: 
1.766     albertel 3804:     if ($thisallowed eq 'A') {
                   3805: 	return 'A';
                   3806:     }
1.52      www      3807:    return 'F';
1.232     www      3808: }
                   3809: 
1.710     albertel 3810: sub split_uri_for_cond {
                   3811:     my $uri=&deversion(&declutter(shift));
                   3812:     my @uriparts=split(/\//,$uri);
                   3813:     my $filename=pop(@uriparts);
                   3814:     my $pathname=join('/',@uriparts);
                   3815:     return ($pathname,$filename);
                   3816: }
1.232     www      3817: # --------------------------------------------------- Is a resource on the map?
                   3818: 
                   3819: sub is_on_map {
1.710     albertel 3820:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3821:     #Trying to find the conditional for the file
1.620     albertel 3822:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3823: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3824:     if ($match) {
1.289     bowersj2 3825: 	return (1,$1);
                   3826:     } else {
1.434     www      3827: 	return (0,0);
1.289     bowersj2 3828:     }
1.12      www      3829: }
                   3830: 
1.427     www      3831: # --------------------------------------------------------- Get symb from alias
                   3832: 
                   3833: sub get_symb_from_alias {
                   3834:     my $symb=shift;
                   3835:     my ($map,$resid,$url)=&decode_symb($symb);
                   3836: # Already is a symb
                   3837:     if ($url) { return $symb; }
                   3838: # Must be an alias
                   3839:     my $aliassymb='';
                   3840:     my %bighash;
1.620     albertel 3841:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3842:                             &GDBM_READER(),0640)) {
                   3843:         my $rid=$bighash{'mapalias_'.$symb};
                   3844: 	if ($rid) {
                   3845: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3846: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3847: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3848: 	}
                   3849:         untie %bighash;
                   3850:     }
                   3851:     return $aliassymb;
                   3852: }
                   3853: 
1.12      www      3854: # ----------------------------------------------------------------- Define Role
                   3855: 
                   3856: sub definerole {
                   3857:   if (allowed('mcr','/')) {
                   3858:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3859:     foreach (split(':',$sysrole)) {
1.21      www      3860: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3861:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3862:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3863: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3864:                return "refused:s:$crole&$cqual"; 
                   3865:             }
                   3866:         }
1.191     harris41 3867:     }
1.392     www      3868:     foreach (split(':',$domrole)) {
1.21      www      3869: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3870:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3871:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3872: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3873:                return "refused:d:$crole&$cqual"; 
                   3874:             }
                   3875:         }
1.191     harris41 3876:     }
1.392     www      3877:     foreach (split(':',$courole)) {
1.21      www      3878: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3879:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3880:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3881: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3882:                return "refused:c:$crole&$cqual"; 
                   3883:             }
                   3884:         }
1.191     harris41 3885:     }
1.620     albertel 3886:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3887:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3888: 	        "rolesdef_$rolename=".
                   3889:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3890:     return reply($command,$env{'user.home'});
1.12      www      3891:   } else {
                   3892:     return 'refused';
                   3893:   }
1.105     harris41 3894: }
                   3895: 
                   3896: # ---------------- Make a metadata query against the network of library servers
                   3897: 
                   3898: sub metadata_query {
1.244     matthew  3899:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3900:     my %rhash;
1.244     matthew  3901:     my @server_list = (defined($server_array) ? @$server_array
                   3902:                                               : keys(%libserv) );
                   3903:     for my $server (@server_list) {
1.118     harris41 3904: 	unless ($custom or $customshow) {
                   3905: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3906: 	    $rhash{$server}=$reply;
                   3907: 	}
                   3908: 	else {
                   3909: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3910: 			     &escape($custom).':'.&escape($customshow),
                   3911: 			     $server);
                   3912: 	    $rhash{$server}=$reply;
                   3913: 	}
1.112     harris41 3914:     }
1.118     harris41 3915:     return \%rhash;
1.240     www      3916: }
                   3917: 
                   3918: # ----------------------------------------- Send log queries and wait for reply
                   3919: 
                   3920: sub log_query {
                   3921:     my ($uname,$udom,$query,%filters)=@_;
                   3922:     my $uhome=&homeserver($uname,$udom);
                   3923:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3924:     my $uhost=$hostname{$uhome};
1.241     www      3925:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3926:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3927:                        $uhome);
1.479     albertel 3928:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3929:     return get_query_reply($queryid);
                   3930: }
                   3931: 
1.508     raeburn  3932: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3933: 
                   3934: sub fetch_enrollment_query {
1.511     raeburn  3935:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3936:     my $homeserver;
1.547     raeburn  3937:     my $maxtries = 1;
1.508     raeburn  3938:     if ($context eq 'automated') {
                   3939:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3940:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3941:     } else {
                   3942:         $homeserver = &homeserver($cnum,$dom);
                   3943:     }
1.506     raeburn  3944:     my $host=$hostname{$homeserver};
                   3945:     my $cmd = '';
                   3946:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3947:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3948:     }
                   3949:     $cmd =~ s/%%$//;
                   3950:     $cmd = &escape($cmd);
                   3951:     my $query = 'fetchenrollment';
1.620     albertel 3952:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3953:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3954:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3955:         return 'error: '.$queryid;
                   3956:     }
1.506     raeburn  3957:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3958:     my $tries = 1;
                   3959:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3960:         $reply = &get_query_reply($queryid);
                   3961:         $tries ++;
                   3962:     }
1.526     raeburn  3963:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3964:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3965:     } else {
1.515     raeburn  3966:         my @responses = split/:/,$reply;
                   3967:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3968:             foreach (@responses) {
                   3969:                 my ($key,$value) = split/=/,$_;
                   3970:                 $$replyref{$key} = $value;
                   3971:             }
                   3972:         } else {
1.506     raeburn  3973:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   3974:             foreach (@responses) {
                   3975:                 my ($key,$value) = split/=/,$_;
                   3976:                 $$replyref{$key} = $value;
                   3977:                 if ($value > 0) {
                   3978:                     foreach (@{$$affiliatesref{$key}}) {
                   3979:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   3980:                         my $destname = $pathname.'/'.$filename;
                   3981:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  3982:                         if ($xml_classlist =~ /^error/) {
                   3983:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   3984:                         } else {
1.506     raeburn  3985:                             if ( open(FILE,">$destname") ) {
                   3986:                                 print FILE &unescape($xml_classlist);
                   3987:                                 close(FILE);
1.526     raeburn  3988:                             } else {
                   3989:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  3990:                             }
                   3991:                         }
                   3992:                     }
                   3993:                 }
                   3994:             }
                   3995:         }
                   3996:         return 'ok';
                   3997:     }
                   3998:     return 'error';
                   3999: }
                   4000: 
1.242     www      4001: sub get_query_reply {
                   4002:     my $queryid=shift;
1.240     www      4003:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4004:     my $reply='';
                   4005:     for (1..100) {
                   4006: 	sleep 2;
                   4007:         if (-e $replyfile.'.end') {
1.448     albertel 4008: 	    if (open(my $fh,$replyfile)) {
1.240     www      4009:                $reply.=<$fh>;
1.448     albertel 4010:                close($fh);
1.240     www      4011: 	   } else { return 'error: reply_file_error'; }
1.242     www      4012:            return &unescape($reply);
                   4013: 	}
1.240     www      4014:     }
1.242     www      4015:     return 'timeout:'.$queryid;
1.240     www      4016: }
                   4017: 
                   4018: sub courselog_query {
1.241     www      4019: #
                   4020: # possible filters:
                   4021: # url: url or symb
                   4022: # username
                   4023: # domain
                   4024: # action: view, submit, grade
                   4025: # start: timestamp
                   4026: # end: timestamp
                   4027: #
1.240     www      4028:     my (%filters)=@_;
1.620     albertel 4029:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4030:     if ($filters{'url'}) {
                   4031: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4032:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4033:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4034:     }
1.620     albertel 4035:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4036:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4037:     return &log_query($cname,$cdom,'courselog',%filters);
                   4038: }
                   4039: 
                   4040: sub userlog_query {
                   4041:     my ($uname,$udom,%filters)=@_;
                   4042:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4043: }
                   4044: 
1.506     raeburn  4045: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4046: 
                   4047: sub auto_run {
1.508     raeburn  4048:     my ($cnum,$cdom) = @_;
                   4049:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4050:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4051:     return $response;
                   4052: }
1.776     albertel 4053: 
1.506     raeburn  4054: sub auto_get_sections {
1.508     raeburn  4055:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4056:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4057:     my @secs = ();
1.511     raeburn  4058:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4059:     unless ($response eq 'refused') {
                   4060:         @secs = split/:/,$response;
                   4061:     }
                   4062:     return @secs;
                   4063: }
1.776     albertel 4064: 
1.506     raeburn  4065: sub auto_new_course {
1.508     raeburn  4066:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4067:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4068:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4069:     return $response;
                   4070: }
1.776     albertel 4071: 
1.506     raeburn  4072: sub auto_validate_courseID {
1.508     raeburn  4073:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4074:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4075:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4076:     return $response;
                   4077: }
1.776     albertel 4078: 
1.506     raeburn  4079: sub auto_create_password {
1.508     raeburn  4080:     my ($cnum,$cdom,$authparam) = @_;
                   4081:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4082:     my $create_passwd = 0;
                   4083:     my $authchk = '';
1.511     raeburn  4084:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4085:     if ($response eq 'refused') {
                   4086:         $authchk = 'refused';
                   4087:     } else {
                   4088:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4089:     }
                   4090:     return ($authparam,$create_passwd,$authchk);
                   4091: }
                   4092: 
1.706     raeburn  4093: sub auto_photo_permission {
                   4094:     my ($cnum,$cdom,$students) = @_;
                   4095:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4096:     my ($outcome,$perm_reqd,$conditions) = 
                   4097: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4098:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4099: 	return (undef,undef);
                   4100:     }
1.706     raeburn  4101:     return ($outcome,$perm_reqd,$conditions);
                   4102: }
                   4103: 
                   4104: sub auto_checkphotos {
                   4105:     my ($uname,$udom,$pid) = @_;
                   4106:     my $homeserver = &homeserver($uname,$udom);
                   4107:     my ($result,$resulttype);
                   4108:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4109: 				   &escape($uname).':'.&escape($pid),
                   4110: 				   $homeserver));
1.709     albertel 4111:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4112: 	return (undef,undef);
                   4113:     }
1.706     raeburn  4114:     if ($outcome) {
                   4115:         ($result,$resulttype) = split(/:/,$outcome);
                   4116:     } 
                   4117:     return ($result,$resulttype);
                   4118: }
                   4119: 
                   4120: sub auto_photochoice {
                   4121:     my ($cnum,$cdom) = @_;
                   4122:     my $homeserver = &homeserver($cnum,$cdom);
                   4123:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4124: 						       &escape($cdom),
                   4125: 						       $homeserver)));
1.709     albertel 4126:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4127: 	return (undef,undef);
                   4128:     }
1.706     raeburn  4129:     return ($update,$comment);
                   4130: }
                   4131: 
                   4132: sub auto_photoupdate {
                   4133:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4134:     my $homeserver = &homeserver($cnum,$dom);
                   4135:     my $host=$hostname{$homeserver};
                   4136:     my $cmd = '';
                   4137:     my $maxtries = 1;
                   4138:     foreach (keys %{$affiliatesref}) {
                   4139:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   4140:     }
                   4141:     $cmd =~ s/%%$//;
                   4142:     $cmd = &escape($cmd);
                   4143:     my $query = 'institutionalphotos';
                   4144:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4145:     unless ($queryid=~/^\Q$host\E\_/) {
                   4146:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4147:         return 'error: '.$queryid;
                   4148:     }
                   4149:     my $reply = &get_query_reply($queryid);
                   4150:     my $tries = 1;
                   4151:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4152:         $reply = &get_query_reply($queryid);
                   4153:         $tries ++;
                   4154:     }
                   4155:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4156:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4157:     } else {
                   4158:         my @responses = split(/:/,$reply);
                   4159:         my $outcome = shift(@responses); 
                   4160:         foreach my $item (@responses) {
                   4161:             my ($key,$value) = split(/=/,$item);
                   4162:             $$photo{$key} = $value;
                   4163:         }
                   4164:         return $outcome;
                   4165:     }
                   4166:     return 'error';
                   4167: }
                   4168: 
1.521     raeburn  4169: sub auto_instcode_format {
                   4170:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   4171:     my $courses = '';
1.772     raeburn  4172:     my @homeservers;
1.521     raeburn  4173:     if ($caller eq 'global') {
1.584     raeburn  4174:         foreach my $tryserver (keys %libserv) {
                   4175:             if ($hostdom{$tryserver} eq $codedom) {
1.772     raeburn  4176:                 if (!grep/^\Q$tryserver\E$/,@homeservers) {
                   4177:                     push(@homeservers,$tryserver);
                   4178:                 }
1.584     raeburn  4179:             }
                   4180:         }
1.521     raeburn  4181:     } else {
1.772     raeburn  4182:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4183:     }
                   4184:     foreach (keys %{$instcodes}) {
                   4185:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   4186:     }
                   4187:     chop($courses);
1.772     raeburn  4188:     my $ok_response = 0;
                   4189:     my $response;
                   4190:     while (@homeservers > 0 && $ok_response == 0) {
                   4191:         my $server = shift(@homeservers); 
                   4192:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4193:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4194:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
                   4195:                                                             split/:/,$response;
                   4196:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4197:             push(@{$codetitles},&str2array($codetitles_str));
                   4198:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4199:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4200:             $ok_response = 1;
                   4201:         }
                   4202:     }
                   4203:     if ($ok_response) {
1.521     raeburn  4204:         return 'ok';
1.772     raeburn  4205:     } else {
                   4206:         return $response;
1.521     raeburn  4207:     }
                   4208: }
                   4209: 
1.777     albertel 4210: sub auto_validate_class_sec {
1.773     raeburn  4211:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4212:     my $homeserver = &homeserver($cnum,$cdom);
                   4213:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4214:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4215:     return $response;
                   4216: }
                   4217: 
1.679     raeburn  4218: # ------------------------------------------------------- Course Group routines
                   4219: 
                   4220: sub get_coursegroups {
1.683     raeburn  4221:     my ($cdom,$cnum,$group) = @_;
                   4222:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4223: }
                   4224: 
                   4225: sub modify_coursegroup {
                   4226:     my ($cdom,$cnum,$groupsettings) = @_;
                   4227:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4228: }
                   4229: 
                   4230: sub modify_group_roles {
                   4231:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4232:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4233:     my $role = 'gr/'.&escape($userprivs);
                   4234:     my ($uname,$udom) = split(/:/,$user);
                   4235:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4236:     if ($result eq 'ok') {
                   4237:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4238:     }
1.679     raeburn  4239:     return $result;
                   4240: }
                   4241: 
                   4242: sub modify_coursegroup_membership {
                   4243:     my ($cdom,$cnum,$membership) = @_;
                   4244:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4245:     return $result;
                   4246: }
                   4247: 
1.682     raeburn  4248: sub get_active_groups {
                   4249:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4250:     my $now = time;
                   4251:     my %groups = ();
                   4252:     foreach my $key (keys(%env)) {
                   4253:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4254:             my ($start,$end) = split(/\./,$env{$key});
                   4255:             if (($end!=0) && ($end<$now)) { next; }
                   4256:             if (($start!=0) && ($start>$now)) { next; }
                   4257:             if ($1 eq $cdom && $2 eq $cnum) {
                   4258:                 $groups{$3} = $env{$key} ;
                   4259:             }
                   4260:         }
                   4261:     }
                   4262:     return %groups;
                   4263: }
                   4264: 
1.683     raeburn  4265: sub get_group_membership {
                   4266:     my ($cdom,$cnum,$group) = @_;
                   4267:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4268: }
                   4269: 
                   4270: sub get_users_groups {
                   4271:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4272:     my @usersgroups;
1.683     raeburn  4273:     my $cachetime=1800;
                   4274:     $courseid=~s/\_/\//g;
                   4275:     $courseid=~s/^(\w)/\/$1/;
                   4276: 
                   4277:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4278:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4279:     if (defined($cached)) {
1.734     albertel 4280:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4281:     } else {  
                   4282:         $grouplist = '';
                   4283:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4284:         my ($tmp) = keys(%roleshash);
                   4285:         if ($tmp=~/^error:/) {
                   4286:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4287:         } else {
                   4288:             my $access_end = $env{'course.'.$courseid.
                   4289:                                   '.default_enrollment_end_date'};
                   4290:             my $now = time;
1.734     albertel 4291:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4292:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4293:                     my $group = $1;
                   4294:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4295:                         my $start = $2;
                   4296:                         my $end = $1;
                   4297:                         if ($start == -1) { next; } # deleted from group
                   4298:                         if (($start!=0) && ($start>$now)) { next; }
                   4299:                         if (($end!=0) && ($end<$now)) {
                   4300:                             if ($access_end && $access_end < $now) {
                   4301:                                 if ($access_end - $end < 86400) {
                   4302:                                     push(@usersgroups,$group);
                   4303:                                 }
                   4304:                             }
                   4305:                             next;
                   4306:                         }
                   4307:                         push(@usersgroups,$group);
                   4308:                     }
1.683     raeburn  4309:                 }
                   4310:             }
1.733     raeburn  4311:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4312:             $grouplist = join(':',@usersgroups);
                   4313:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4314:         }
                   4315:     }
1.733     raeburn  4316:     return @usersgroups;
1.683     raeburn  4317: }
                   4318: 
                   4319: sub devalidate_getgroups_cache {
                   4320:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4321:     my $courseid = $cdom.'_'.$cnum;
                   4322:     $courseid=~s/\_/\//g;
                   4323:     $courseid=~s/^(\w)/\/$1/;
                   4324:     my $hashid="$udom:$uname:$courseid";
                   4325:     &devalidate_cache_new('getgroups',$hashid);
                   4326: }
                   4327: 
1.12      www      4328: # ------------------------------------------------------------------ Plain Text
                   4329: 
                   4330: sub plaintext {
1.742     raeburn  4331:     my ($short,$type,$cid) = @_;
1.758     albertel 4332:     if ($short =~ /^cr/) {
                   4333: 	return (split('/',$short))[-1];
                   4334:     }
1.742     raeburn  4335:     if (!defined($cid)) {
                   4336:         $cid = $env{'request.course.id'};
                   4337:     }
                   4338:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4339:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4340:                                           '.plaintext'});
                   4341:     }
                   4342:     my %rolenames = (
                   4343:                       Course => 'std',
                   4344:                       Group => 'alt1',
                   4345:                     );
                   4346:     if (defined($type) && 
                   4347:          defined($rolenames{$type}) && 
                   4348:          defined($prp{$short}{$rolenames{$type}})) {
                   4349:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4350:     } else {
                   4351:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4352:     }
1.12      www      4353: }
                   4354: 
                   4355: # ----------------------------------------------------------------- Assign Role
                   4356: 
                   4357: sub assignrole {
1.357     www      4358:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4359:     my $mrole;
                   4360:     if ($role =~ /^cr\//) {
1.393     www      4361:         my $cwosec=$url;
                   4362:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4363: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4364:            &logthis('Refused custom assignrole: '.
                   4365:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4366: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4367:            return 'refused'; 
                   4368:         }
1.21      www      4369:         $mrole='cr';
1.678     raeburn  4370:     } elsif ($role =~ /^gr\//) {
                   4371:         my $cwogrp=$url;
                   4372:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4373:         unless (&allowed('mdg',$cwogrp)) {
                   4374:             &logthis('Refused group assignrole: '.
                   4375:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4376:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4377:             return 'refused';
                   4378:         }
                   4379:         $mrole='gr';
1.21      www      4380:     } else {
1.82      www      4381:         my $cwosec=$url;
1.83      www      4382:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4383:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4384:            &logthis('Refused assignrole: '.
                   4385:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4386: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4387:            return 'refused'; 
                   4388:         }
1.21      www      4389:         $mrole=$role;
                   4390:     }
1.620     albertel 4391:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4392:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4393:     if ($end) { $command.='_'.$end; }
1.21      www      4394:     if ($start) {
                   4395: 	if ($end) { 
1.81      www      4396:            $command.='_'.$start; 
1.21      www      4397:         } else {
1.81      www      4398:            $command.='_0_'.$start;
1.21      www      4399:         }
                   4400:     }
1.739     raeburn  4401:     my $origstart = $start;
                   4402:     my $origend = $end;
1.357     www      4403: # actually delete
                   4404:     if ($deleteflag) {
1.373     www      4405: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4406: # modify command to delete the role
1.620     albertel 4407:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4408:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4409: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4410: # set start and finish to negative values for userrolelog
                   4411:            $start=-1;
                   4412:            $end=-1;
                   4413:         }
                   4414:     }
                   4415: # send command
1.349     www      4416:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4417: # log new user role if status is ok
1.349     www      4418:     if ($answer eq 'ok') {
1.663     raeburn  4419: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4420: # for course roles, perform group memberships changes triggered by role change.
                   4421:         unless ($role =~ /^gr/) {
                   4422:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4423:                                              $origstart);
                   4424:         }
1.349     www      4425:     }
                   4426:     return $answer;
1.169     harris41 4427: }
                   4428: 
                   4429: # -------------------------------------------------- Modify user authentication
1.197     www      4430: # Overrides without validation
                   4431: 
1.169     harris41 4432: sub modifyuserauth {
                   4433:     my ($udom,$uname,$umode,$upass)=@_;
                   4434:     my $uhome=&homeserver($uname,$udom);
1.197     www      4435:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4436:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4437:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4438:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4439:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4440: 		     &escape($upass),$uhome);
1.620     albertel 4441:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4442:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4443:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4444:     &log($udom,,$uname,$uhome,
1.620     albertel 4445:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4446:                                      $env{'user.name'}.', '.$umode.
1.197     www      4447:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4448:     unless ($reply eq 'ok') {
1.197     www      4449:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4450: 	return 'error: '.$reply;
                   4451:     }   
1.170     harris41 4452:     return 'ok';
1.80      www      4453: }
                   4454: 
1.81      www      4455: # --------------------------------------------------------------- Modify a user
1.80      www      4456: 
1.81      www      4457: sub modifyuser {
1.206     matthew  4458:     my ($udom,    $uname, $uid,
                   4459:         $umode,   $upass, $first,
                   4460:         $middle,  $last,  $gene,
1.387     www      4461:         $forceid, $desiredhome, $email)=@_;
1.198     www      4462:     $udom=~s/\W//g;
                   4463:     $uname=~s/\W//g;
1.81      www      4464:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4465:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4466: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4467:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4468:                                      ' desiredhome not specified'). 
1.620     albertel 4469:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4470:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4471:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4472: # ----------------------------------------------------------------- Create User
1.406     albertel 4473:     if (($uhome eq 'no_host') && 
                   4474: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4475:         my $unhome='';
1.209     matthew  4476:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4477:             $unhome = $desiredhome;
1.620     albertel 4478: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4479: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4480:         } else { # load balancing routine for determining $unhome
1.80      www      4481:             my $tryserver;
1.81      www      4482:             my $loadm=10000000;
1.80      www      4483:             foreach $tryserver (keys %libserv) {
                   4484: 	       if ($hostdom{$tryserver} eq $udom) {
                   4485:                   my $answer=reply('load',$tryserver);
                   4486:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4487: 		      $loadm=$answer;
                   4488:                       $unhome=$tryserver;
                   4489:                   }
                   4490: 	       }
                   4491: 	    }
                   4492:         }
                   4493:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4494: 	    return 'error: unable to find a home server for '.$uname.
                   4495:                    ' in domain '.$udom;
1.80      www      4496:         }
                   4497:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4498:                          &escape($upass),$unhome);
                   4499: 	unless ($reply eq 'ok') {
                   4500:             return 'error: '.$reply;
                   4501:         }   
1.230     stredwic 4502:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4503:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4504: 	    return 'error: unable verify users home machine.';
1.80      www      4505:         }
1.209     matthew  4506:     }   # End of creation of new user
1.80      www      4507: # ---------------------------------------------------------------------- Add ID
                   4508:     if ($uid) {
                   4509:        $uid=~tr/A-Z/a-z/;
                   4510:        my %uidhash=&idrget($udom,$uname);
1.196     www      4511:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4512:          && (!$forceid)) {
1.80      www      4513: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4514: 	      return 'error: user id "'.$uid.'" does not match '.
                   4515:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4516:           }
                   4517:        } else {
                   4518: 	  &idput($udom,($uname => $uid));
                   4519:        }
                   4520:     }
                   4521: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4522:     my @tmp=&get('environment',
1.134     albertel 4523: 		   ['firstname','middlename','lastname','generation'],
                   4524: 		   $udom,$uname);
1.313     matthew  4525:     my %names;
                   4526:     if ($tmp[0] =~ m/^error:.*/) { 
                   4527:         %names=(); 
                   4528:     } else {
                   4529:         %names = @tmp;
                   4530:     }
1.388     www      4531: #
                   4532: # Make sure to not trash student environment if instructor does not bother
                   4533: # to supply name and email information
                   4534: #
                   4535:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4536:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4537:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4538:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4539:     if ($email) {
                   4540:        $email=~s/[^\w\@\.\-\,]//gs;
                   4541:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4542: 			   $names{'critnotification'} = $email;
                   4543: 			   $names{'permanentemail'} = $email; }
                   4544:     }
1.134     albertel 4545:     my $reply = &put('environment', \%names, $udom,$uname);
                   4546:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4547:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4548:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4549:              $umode.', '.$first.', '.$middle.', '.
                   4550: 	     $last.', '.$gene.' by '.
1.620     albertel 4551:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4552:     return 'ok';
1.80      www      4553: }
                   4554: 
1.81      www      4555: # -------------------------------------------------------------- Modify student
1.80      www      4556: 
1.81      www      4557: sub modifystudent {
                   4558:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4559:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4560:     if (!$cid) {
1.620     albertel 4561: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4562: 	    return 'not_in_class';
                   4563: 	}
1.80      www      4564:     }
                   4565: # --------------------------------------------------------------- Make the user
1.81      www      4566:     my $reply=&modifyuser
1.209     matthew  4567: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4568:          $desiredhome,$email);
1.80      www      4569:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4570:     # This will cause &modify_student_enrollment to get the uid from the
                   4571:     # students environment
                   4572:     $uid = undef if (!$forceid);
1.455     albertel 4573:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4574: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4575:     return $reply;
                   4576: }
                   4577: 
                   4578: sub modify_student_enrollment {
1.515     raeburn  4579:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4580:     my ($cdom,$cnum,$chome);
                   4581:     if (!$cid) {
1.620     albertel 4582: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4583: 	    return 'not_in_class';
                   4584: 	}
1.620     albertel 4585: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4586: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4587:     } else {
                   4588: 	($cdom,$cnum)=split(/_/,$cid);
                   4589:     }
1.620     albertel 4590:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4591:     if (!$chome) {
1.457     raeburn  4592: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4593:     }
1.455     albertel 4594:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4595:     # Make sure the user exists
1.81      www      4596:     my $uhome=&homeserver($uname,$udom);
                   4597:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4598: 	return 'error: no such user';
                   4599:     }
1.297     matthew  4600:     # Get student data if we were not given enough information
                   4601:     if (!defined($first)  || $first  eq '' || 
                   4602:         !defined($last)   || $last   eq '' || 
                   4603:         !defined($uid)    || $uid    eq '' || 
                   4604:         !defined($middle) || $middle eq '' || 
                   4605:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4606:         # They did not supply us with enough data to enroll the student, so
                   4607:         # we need to pick up more information.
1.297     matthew  4608:         my %tmp = &get('environment',
1.294     matthew  4609:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4610:                        ,$udom,$uname);
                   4611: 
1.455     albertel 4612:         #foreach (keys(%tmp)) {
                   4613:         #    &logthis("key $_ = ".$tmp{$_});
                   4614:         #}
1.294     matthew  4615:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4616:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4617:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4618:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4619:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4620:     }
1.556     albertel 4621:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4622:     my $reply=cput('classlist',
                   4623: 		   {"$uname:$udom" => 
1.515     raeburn  4624: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4625: 		   $cdom,$cnum);
1.81      www      4626:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4627: 	return 'error: '.$reply;
1.652     albertel 4628:     } else {
                   4629: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4630:     }
1.297     matthew  4631:     # Add student role to user
1.83      www      4632:     my $uurl='/'.$cid;
1.81      www      4633:     $uurl=~s/\_/\//g;
                   4634:     if ($usec) {
                   4635: 	$uurl.='/'.$usec;
                   4636:     }
                   4637:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4638: }
                   4639: 
1.556     albertel 4640: sub format_name {
                   4641:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4642:     my $name;
                   4643:     if ($first ne 'lastname') {
                   4644: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4645:     } else {
                   4646: 	if ($lastname=~/\S/) {
                   4647: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4648: 	    $name=~s/\s+,/,/;
                   4649: 	} else {
                   4650: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4651: 	}
                   4652:     }
                   4653:     $name=~s/^\s+//;
                   4654:     $name=~s/\s+$//;
                   4655:     $name=~s/\s+/ /g;
                   4656:     return $name;
                   4657: }
                   4658: 
1.84      www      4659: # ------------------------------------------------- Write to course preferences
                   4660: 
                   4661: sub writecoursepref {
                   4662:     my ($courseid,%prefs)=@_;
                   4663:     $courseid=~s/^\///;
                   4664:     $courseid=~s/\_/\//g;
                   4665:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4666:     my $chome=homeserver($cnum,$cdomain);
                   4667:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4668: 	return 'error: no such course';
                   4669:     }
                   4670:     my $cstring='';
1.191     harris41 4671:     foreach (keys %prefs) {
1.84      www      4672: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4673:     }
1.84      www      4674:     $cstring=~s/\&$//;
                   4675:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4676: }
                   4677: 
                   4678: # ---------------------------------------------------------- Make/modify course
                   4679: 
                   4680: sub createcourse {
1.741     raeburn  4681:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4682:         $course_owner,$crstype)=@_;
1.84      www      4683:     $url=&declutter($url);
                   4684:     my $cid='';
1.264     matthew  4685:     unless (&allowed('ccc',$udom)) {
1.84      www      4686:         return 'refused';
                   4687:     }
                   4688: # ------------------------------------------------------------------- Create ID
1.674     www      4689:    my $uname=int(1+rand(9)).
                   4690:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4691:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4692:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4693: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4694:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4695:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4696:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4697:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4698:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4699:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4700:            return 'error: unable to generate unique course-ID';
                   4701:        } 
                   4702:    }
1.264     matthew  4703: # ------------------------------------------------ Check supplied server name
1.620     albertel 4704:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4705:     if (! exists($libserv{$course_server})) {
                   4706:         return 'error:bad server name '.$course_server;
                   4707:     }
1.84      www      4708: # ------------------------------------------------------------- Make the course
                   4709:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4710:                       $course_server);
1.84      www      4711:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4712:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4713:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4714: 	return 'error: no such course';
                   4715:     }
1.271     www      4716: # ----------------------------------------------------------------- Course made
1.516     raeburn  4717: # log existence
                   4718:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4719:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4720:                   &escape($crstype),$uhome);
1.358     www      4721:     &flushcourselogs();
                   4722: # set toplevel url
1.271     www      4723:     my $topurl=$url;
                   4724:     unless ($nonstandard) {
                   4725: # ------------------------------------------ For standard courses, make top url
                   4726:         my $mapurl=&clutter($url);
1.278     www      4727:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4728:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4729: <map>
                   4730: <resource id="1" type="start"></resource>
                   4731: <resource id="2" src="$mapurl"></resource>
                   4732: <resource id="3" type="finish"></resource>
                   4733: <link index="1" from="1" to="2"></link>
                   4734: <link index="2" from="2" to="3"></link>
                   4735: </map>
                   4736: ENDINITMAP
                   4737:         $topurl=&declutter(
1.638     albertel 4738:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4739:                           );
                   4740:     }
                   4741: # ----------------------------------------------------------- Write preferences
1.84      www      4742:     &writecoursepref($udom.'_'.$uname,
                   4743:                      ('description' => $description,
1.271     www      4744:                       'url'         => $topurl));
1.84      www      4745:     return '/'.$udom.'/'.$uname;
                   4746: }
                   4747: 
1.21      www      4748: # ---------------------------------------------------------- Assign Custom Role
                   4749: 
                   4750: sub assigncustomrole {
1.357     www      4751:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4752:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4753:                        $end,$start,$deleteflag);
1.21      www      4754: }
                   4755: 
                   4756: # ----------------------------------------------------------------- Revoke Role
                   4757: 
                   4758: sub revokerole {
1.357     www      4759:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4760:     my $now=time;
1.357     www      4761:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4762: }
                   4763: 
                   4764: # ---------------------------------------------------------- Revoke Custom Role
                   4765: 
                   4766: sub revokecustomrole {
1.357     www      4767:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4768:     my $now=time;
1.357     www      4769:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4770:            $deleteflag);
1.17      www      4771: }
                   4772: 
1.533     banghart 4773: # ------------------------------------------------------------ Disk usage
1.535     albertel 4774: sub diskusage {
1.533     banghart 4775:     my ($udom,$uname,$directoryRoot)=@_;
                   4776:     $directoryRoot =~ s/\/$//;
1.535     albertel 4777:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4778:     return $listing;
1.512     banghart 4779: }
                   4780: 
1.566     banghart 4781: sub is_locked {
                   4782:     my ($file_name, $domain, $user) = @_;
                   4783:     my @check;
                   4784:     my $is_locked;
                   4785:     push @check, $file_name;
1.613     albertel 4786:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4787: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4788:     my ($tmp)=keys(%locked);
                   4789:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4790:     
1.566     banghart 4791:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4792:         $is_locked = 'false';
                   4793:         foreach my $entry (@{$locked{$file_name}}) {
                   4794:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4795:                $is_locked = 'true';
                   4796:                last;
1.745     raeburn  4797:            }
                   4798:        }
1.566     banghart 4799:     } else {
                   4800:         $is_locked = 'false';
                   4801:     }
                   4802: }
                   4803: 
1.759     albertel 4804: sub declutter_portfile {
                   4805:     my ($file) = @_;
                   4806:     &logthis("got $file");
                   4807:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   4808:     &logthis("ret $file");
                   4809:     return $file;
                   4810: }
                   4811: 
1.559     banghart 4812: # ------------------------------------------------------------- Mark as Read Only
                   4813: 
                   4814: sub mark_as_readonly {
                   4815:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4816:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4817:     my ($tmp)=keys(%current_permissions);
                   4818:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4819:     foreach my $file (@{$files}) {
1.759     albertel 4820: 	$file = &declutter_portfile($file);
1.561     banghart 4821:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4822:     }
1.613     albertel 4823:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4824:     return;
                   4825: }
                   4826: 
1.572     banghart 4827: # ------------------------------------------------------------Save Selected Files
                   4828: 
                   4829: sub save_selected_files {
                   4830:     my ($user, $path, @files) = @_;
                   4831:     my $filename = $user."savedfiles";
1.573     banghart 4832:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4833:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4834:     foreach my $file (@files) {
1.620     albertel 4835:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4836:     }
                   4837:     foreach my $file (@other_files) {
1.574     banghart 4838:         print (OUT $file."\n");
1.572     banghart 4839:     }
1.574     banghart 4840:     close (OUT);
1.572     banghart 4841:     return 'ok';
                   4842: }
                   4843: 
1.574     banghart 4844: sub clear_selected_files {
                   4845:     my ($user) = @_;
                   4846:     my $filename = $user."savedfiles";
                   4847:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4848:     print (OUT undef);
                   4849:     close (OUT);
                   4850:     return ("ok");    
                   4851: }
                   4852: 
1.572     banghart 4853: sub files_in_path {
                   4854:     my ($user, $path) = @_;
                   4855:     my $filename = $user."savedfiles";
                   4856:     my %return_files;
1.574     banghart 4857:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4858:     while (my $line_in = <IN>) {
1.574     banghart 4859:         chomp ($line_in);
                   4860:         my @paths_and_file = split (m!/!, $line_in);
                   4861:         my $file_part = pop (@paths_and_file);
                   4862:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4863:         $path_part.='/';
                   4864:         my $path_and_file = $path_part.$file_part;
                   4865:         if ($path_part eq $path) {
                   4866:             $return_files{$file_part}= 'selected';
                   4867:         }
                   4868:     }
1.574     banghart 4869:     close (IN);
                   4870:     return (\%return_files);
1.572     banghart 4871: }
                   4872: 
                   4873: # called in portfolio select mode, to show files selected NOT in current directory
                   4874: sub files_not_in_path {
                   4875:     my ($user, $path) = @_;
                   4876:     my $filename = $user."savedfiles";
                   4877:     my @return_files;
                   4878:     my $path_part;
1.574     banghart 4879:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4880:     while (<IN>) {
                   4881:         #ok, I know it's clunky, but I want it to work
                   4882:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4883:         my $file_part = pop (@paths_and_file);
                   4884:         chomp ($file_part);
                   4885:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4886:         $path_part .= '/';
                   4887:         my $path_and_file = $path_part.$file_part;
                   4888:         if ($path_part ne $path) {
1.574     banghart 4889:             push (@return_files, ($path_and_file));
1.572     banghart 4890:         }
                   4891:     }
1.574     banghart 4892:     close (OUT);
                   4893:     return (@return_files);
1.572     banghart 4894: }
                   4895: 
1.745     raeburn  4896: #----------------------------------------------Get portfolio file permissions
1.629     banghart 4897: 
1.745     raeburn  4898: sub get_portfile_permissions {
                   4899:     my ($domain,$user) = @_;
1.613     albertel 4900:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4901:     my ($tmp)=keys(%current_permissions);
                   4902:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4903:     return \%current_permissions;
                   4904: }
                   4905: 
                   4906: #---------------------------------------------Get portfolio file access controls
                   4907: 
1.749     raeburn  4908: sub get_access_controls {
1.745     raeburn  4909:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 4910:     my %access;
                   4911:     my $real_file = $file;
                   4912:     $file =~ s/\.meta$//;
1.745     raeburn  4913:     if (defined($file)) {
1.749     raeburn  4914:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   4915:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 4916:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  4917:             }
                   4918:         }
1.745     raeburn  4919:     } else {
1.749     raeburn  4920:         foreach my $key (keys(%{$current_permissions})) {
                   4921:             if ($key =~ /\0accesscontrol$/) {
                   4922:                 if (defined($group)) {
                   4923:                     if ($key !~ m-^\Q$group\E/-) {
                   4924:                         next;
                   4925:                     }
                   4926:                 }
                   4927:                 my ($fullpath) = split(/\0/,$key);
                   4928:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   4929:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   4930:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   4931:                     }
                   4932:                 }
                   4933:             }
                   4934:         }
                   4935:     }
                   4936:     return %access;
                   4937: }
                   4938: 
                   4939: sub modify_access_controls {
                   4940:     my ($file_name,$changes,$domain,$user)=@_;
                   4941:     my ($outcome,$deloutcome);
                   4942:     my %store_permissions;
                   4943:     my %new_values;
                   4944:     my %new_control;
                   4945:     my %translation;
                   4946:     my @deletions = ();
                   4947:     my $now = time;
                   4948:     if (exists($$changes{'activate'})) {
                   4949:         if (ref($$changes{'activate'}) eq 'HASH') {
                   4950:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   4951:             my $numnew = scalar(@newitems);
                   4952:             for (my $i=0; $i<$numnew; $i++) {
                   4953:                 my $newkey = $newitems[$i];
                   4954:                 my $newid = &Apache::loncommon::get_cgi_id();
                   4955:                 $newkey =~ s/^(\d+)/$newid/;
                   4956:                 $translation{$1} = $newid;
                   4957:                 $new_values{$file_name."\0".$newkey} = 
                   4958:                                           $$changes{'activate'}{$newitems[$i]};
                   4959:                 $new_control{$newkey} = $now;
                   4960:             }
                   4961:         }
                   4962:     }
                   4963:     my %todelete;
                   4964:     my %changed_items;
                   4965:     foreach my $action ('delete','update') {
                   4966:         if (exists($$changes{$action})) {
                   4967:             if (ref($$changes{$action}) eq 'HASH') {
                   4968:                 foreach my $key (keys(%{$$changes{$action}})) {
                   4969:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   4970:                     if ($action eq 'delete') { 
                   4971:                         $todelete{$itemnum} = 1;
                   4972:                     } else {
                   4973:                         $changed_items{$itemnum} = $key;
                   4974:                     }
                   4975:                 }
1.745     raeburn  4976:             }
                   4977:         }
1.749     raeburn  4978:     }
                   4979:     # get lock on access controls for file.
                   4980:     my $lockhash = {
                   4981:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   4982:                                                        ':'.$env{'user.domain'},
                   4983:                    }; 
                   4984:     my $tries = 0;
                   4985:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   4986:    
                   4987:     while (($gotlock ne 'ok') && $tries <3) {
                   4988:         $tries ++;
                   4989:         sleep 1;
                   4990:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   4991:     }
                   4992:     if ($gotlock eq 'ok') {
                   4993:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   4994:         my ($tmp)=keys(%curr_permissions);
                   4995:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   4996:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   4997:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   4998:             if (ref($curr_controls) eq 'HASH') {
                   4999:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5000:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5001:                     if (defined($todelete{$itemnum})) {
                   5002:                         push(@deletions,$file_name."\0".$control_item);
                   5003:                     } else {
                   5004:                         if (defined($changed_items{$itemnum})) {
                   5005:                             $new_control{$changed_items{$itemnum}} = $now;
                   5006:                             push(@deletions,$file_name."\0".$control_item);
                   5007:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5008:                         } else {
                   5009:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5010:                         }
                   5011:                     }
1.745     raeburn  5012:                 }
                   5013:             }
                   5014:         }
1.749     raeburn  5015:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5016:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5017:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5018:         #  remove lock
                   5019:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5020:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5021:     } else {
                   5022:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5023:     }
1.749     raeburn  5024:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5025: }
                   5026: 
                   5027: #------------------------------------------------------Get Marked as Read Only
                   5028: 
                   5029: sub get_marked_as_readonly {
                   5030:     my ($domain,$user,$what,$group) = @_;
                   5031:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5032:     my @readonly_files;
1.629     banghart 5033:     my $cmp1=$what;
                   5034:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5035:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5036:         if (defined($group)) {
                   5037:             if ($file_name !~ m-^\Q$group\E/-) {
                   5038:                 next;
                   5039:             }
                   5040:         }
1.561     banghart 5041:         if (ref($value) eq "ARRAY"){
                   5042:             foreach my $stored_what (@{$value}) {
1.629     banghart 5043:                 my $cmp2=$stored_what;
1.759     albertel 5044:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5045:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5046:                 }
1.629     banghart 5047:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5048:                     push(@readonly_files, $file_name);
1.745     raeburn  5049:                     last;
1.563     banghart 5050:                 } elsif (!defined($what)) {
                   5051:                     push(@readonly_files, $file_name);
1.745     raeburn  5052:                     last;
1.561     banghart 5053:                 }
                   5054:             }
1.745     raeburn  5055:         }
1.561     banghart 5056:     }
                   5057:     return @readonly_files;
                   5058: }
1.577     banghart 5059: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5060: 
1.577     banghart 5061: sub get_marked_as_readonly_hash {
1.745     raeburn  5062:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5063:     my %readonly_files;
1.745     raeburn  5064:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5065:         if (defined($group)) {
                   5066:             if ($file_name !~ m-^\Q$group\E/-) {
                   5067:                 next;
                   5068:             }
                   5069:         }
1.577     banghart 5070:         if (ref($value) eq "ARRAY"){
                   5071:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5072:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5073:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5074:                         if ($lock_descriptor eq 'graded') {
                   5075:                             $readonly_files{$file_name} = 'graded';
                   5076:                         } elsif ($lock_descriptor eq 'handback') {
                   5077:                             $readonly_files{$file_name} = 'handback';
                   5078:                         } else {
                   5079:                             if (!exists($readonly_files{$file_name})) {
                   5080:                                 $readonly_files{$file_name} = 'locked';
                   5081:                             }
                   5082:                         }
1.745     raeburn  5083:                     }
1.750     banghart 5084:                 } 
1.577     banghart 5085:             }
                   5086:         } 
                   5087:     }
                   5088:     return %readonly_files;
                   5089: }
1.559     banghart 5090: # ------------------------------------------------------------ Unmark as Read Only
                   5091: 
                   5092: sub unmark_as_readonly {
1.629     banghart 5093:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5094:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5095:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5096:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5097:     my $symb_crs = $what;
                   5098:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5099:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5100:     my ($tmp)=keys(%current_permissions);
                   5101:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5102:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5103:     foreach my $file (@readonly_files) {
1.759     albertel 5104: 	my $clean_file = &declutter_portfile($file);
                   5105: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5106: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5107:         my @new_locks;
                   5108:         my @del_keys;
                   5109:         if (ref($current_locks) eq "ARRAY"){
                   5110:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5111:                 my $compare=$locker;
1.749     raeburn  5112:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5113:                     $compare=join('',@{$locker});
1.746     raeburn  5114:                     if ($compare ne $symb_crs) {
                   5115:                         push(@new_locks, $locker);
                   5116:                     }
1.563     banghart 5117:                 }
                   5118:             }
1.650     albertel 5119:             if (scalar(@new_locks) > 0) {
1.563     banghart 5120:                 $current_permissions{$file} = \@new_locks;
                   5121:             } else {
                   5122:                 push(@del_keys, $file);
1.613     albertel 5123:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5124:                 delete($current_permissions{$file});
1.563     banghart 5125:             }
                   5126:         }
1.561     banghart 5127:     }
1.613     albertel 5128:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5129:     return;
                   5130: }
1.512     banghart 5131: 
1.17      www      5132: # ------------------------------------------------------------ Directory lister
                   5133: 
                   5134: sub dirlist {
1.253     stredwic 5135:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5136: 
1.18      www      5137:     $uri=~s/^\///;
                   5138:     $uri=~s/\/$//;
1.253     stredwic 5139:     my ($udom, $uname);
                   5140:     (undef,$udom,$uname)=split(/\//,$uri);
                   5141:     if(defined($userdomain)) {
                   5142:         $udom = $userdomain;
                   5143:     }
                   5144:     if(defined($username)) {
                   5145:         $uname = $username;
                   5146:     }
                   5147: 
                   5148:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5149:     if(defined($alternateDirectoryRoot)) {
                   5150:         $dirRoot = $alternateDirectoryRoot;
                   5151:         $dirRoot =~ s/\/$//;
1.751     banghart 5152:     }
1.253     stredwic 5153: 
                   5154:     if($udom) {
                   5155:         if($uname) {
1.605     matthew  5156:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 5157:                               homeserver($uname,$udom));
1.605     matthew  5158:             my @listing_results;
                   5159:             if ($listing eq 'unknown_cmd') {
                   5160:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   5161:                                homeserver($uname,$udom));
                   5162:                 @listing_results = split(/:/,$listing);
                   5163:             } else {
                   5164:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5165:             }
                   5166:             return @listing_results;
1.253     stredwic 5167:         } elsif(!defined($alternateDirectoryRoot)) {
                   5168:             my $tryserver;
                   5169:             my %allusers=();
                   5170:             foreach $tryserver (keys %libserv) {
                   5171:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  5172:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 5173:                                       $udom, $tryserver);
1.605     matthew  5174:                     my @listing_results;
                   5175:                     if ($listing eq 'unknown_cmd') {
                   5176:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5177:                                        $udom, $tryserver);
                   5178:                         @listing_results = split(/:/,$listing);
                   5179:                     } else {
                   5180:                         @listing_results =
                   5181:                             map { &unescape($_); } split(/:/,$listing);
                   5182:                     }
                   5183:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5184:                         $listing_results[0] ne 'empty'       &&
                   5185:                         $listing_results[0] ne 'con_lost') {
                   5186:                         foreach (@listing_results) {
1.253     stredwic 5187:                             my ($entry,@stat)=split(/&/,$_);
                   5188:                             $allusers{$entry}=1;
                   5189:                         }
                   5190:                     }
1.191     harris41 5191:                 }
1.253     stredwic 5192:             }
                   5193:             my $alluserstr='';
                   5194:             foreach (sort keys %allusers) {
                   5195:                 $alluserstr.=$_.'&user:';
                   5196:             }
                   5197:             $alluserstr=~s/:$//;
                   5198:             return split(/:/,$alluserstr);
                   5199:         } else {
                   5200:             my @emptyResults = ();
                   5201:             push(@emptyResults, 'missing user name');
                   5202:             return split(':',@emptyResults);
                   5203:         }
                   5204:     } elsif(!defined($alternateDirectoryRoot)) {
                   5205:         my $tryserver;
                   5206:         my %alldom=();
                   5207:         foreach $tryserver (keys %libserv) {
                   5208:             $alldom{$hostdom{$tryserver}}=1;
                   5209:         }
                   5210:         my $alldomstr='';
                   5211:         foreach (sort keys %alldom) {
1.397     albertel 5212:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 5213:         }
                   5214:         $alldomstr=~s/:$//;
                   5215:         return split(/:/,$alldomstr);       
                   5216:     } else {
                   5217:         my @emptyResults = ();
                   5218:         push(@emptyResults, 'missing domain');
                   5219:         return split(':',@emptyResults);
1.275     stredwic 5220:     }
                   5221: }
                   5222: 
                   5223: # --------------------------------------------- GetFileTimestamp
                   5224: # This function utilizes dirlist and returns the date stamp for
                   5225: # when it was last modified.  It will also return an error of -1
                   5226: # if an error occurs
                   5227: 
1.410     matthew  5228: ##
                   5229: ## FIXME: This subroutine assumes its caller knows something about the
                   5230: ## directory structure of the home server for the student ($root).
                   5231: ## Not a good assumption to make.  Since this is for looking up files
                   5232: ## in user directories, the full path should be constructed by lond, not
                   5233: ## whatever machine we request data from.
                   5234: ##
1.275     stredwic 5235: sub GetFileTimestamp {
                   5236:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5237:     $studentDomain=~s/\W//g;
                   5238:     $studentName=~s/\W//g;
                   5239:     my $subdir=$studentName.'__';
                   5240:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5241:     my $proname="$studentDomain/$subdir/$studentName";
                   5242:     $proname .= '/'.$filename;
1.375     matthew  5243:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5244:                                               $studentName, $root);
1.275     stredwic 5245:     my @stats = split('&', $fileStat);
                   5246:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5247:         # @stats contains first the filename, then the stat output
                   5248:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5249:     } else {
                   5250:         return -1;
1.253     stredwic 5251:     }
1.26      www      5252: }
                   5253: 
1.712     albertel 5254: sub stat_file {
                   5255:     my ($uri) = @_;
1.722     albertel 5256:     $uri = &clutter($uri);
                   5257: 
                   5258:     # we want just the url part without the unneeded accessor url bits
1.723     banghart 5259:     if ($uri =~ m-^/adm/-) {
                   5260: 	$uri=~s-^/adm/wrapper/-/-;
                   5261: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
1.722     albertel 5262:     }
1.712     albertel 5263:     my ($udom,$uname,$file,$dir);
                   5264:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5265: 	($udom,$uname,$file) =
                   5266: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5267: 	$file = 'userfiles/'.$file;
1.740     www      5268: 	$dir = &propath($udom,$uname);
1.712     albertel 5269:     }
                   5270:     if ($uri =~ m-^/res/-) {
                   5271: 	($udom,$uname) = 
                   5272: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5273: 	$file = $uri;
                   5274:     }
                   5275: 
                   5276:     if (!$udom || !$uname || !$file) {
                   5277: 	# unable to handle the uri
                   5278: 	return ();
                   5279:     }
                   5280: 
                   5281:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5282:     my @stats = split('&', $result);
1.721     banghart 5283:     
1.712     albertel 5284:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5285: 	shift(@stats); #filename is first
                   5286: 	return @stats;
                   5287:     }
                   5288:     return ();
                   5289: }
                   5290: 
1.26      www      5291: # -------------------------------------------------------- Value of a Condition
                   5292: 
1.713     albertel 5293: # gets the value of a specific preevaluated condition
                   5294: #    stored in the string  $env{user.state.<cid>}
                   5295: # or looks up a condition reference in the bighash and if if hasn't
                   5296: # already been evaluated recurses into docondval to get the value of
                   5297: # the condition, then memoizing it to 
                   5298: #   $env{user.state.<cid>.<condition>}
1.40      www      5299: sub directcondval {
                   5300:     my $number=shift;
1.620     albertel 5301:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5302: 	&Apache::lonuserstate::evalstate();
                   5303:     }
1.713     albertel 5304:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5305: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5306:     } elsif ($number =~ /^_/) {
                   5307: 	my $sub_condition;
                   5308: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5309: 		&GDBM_READER(),0640)) {
                   5310: 	    $sub_condition=$bighash{'conditions'.$number};
                   5311: 	    untie(%bighash);
                   5312: 	}
                   5313: 	my $value = &docondval($sub_condition);
                   5314: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5315: 	return $value;
                   5316:     }
1.620     albertel 5317:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5318:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5319:     } else {
                   5320:        return 2;
                   5321:     }
                   5322: }
                   5323: 
1.713     albertel 5324: # get the collection of conditions for this resource
1.26      www      5325: sub condval {
                   5326:     my $condidx=shift;
1.54      www      5327:     my $allpathcond='';
1.713     albertel 5328:     foreach my $cond (split(/\|/,$condidx)) {
                   5329: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5330: 	    $allpathcond.=
                   5331: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5332: 	}
1.191     harris41 5333:     }
1.54      www      5334:     $allpathcond=~s/\|$//;
1.713     albertel 5335:     return &docondval($allpathcond);
                   5336: }
                   5337: 
                   5338: #evaluates an expression of conditions
                   5339: sub docondval {
                   5340:     my ($allpathcond) = @_;
                   5341:     my $result=0;
                   5342:     if ($env{'request.course.id'}
                   5343: 	&& defined($allpathcond)) {
                   5344: 	my $operand='|';
                   5345: 	my @stack;
                   5346: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5347: 	    if ($chunk eq '(') {
                   5348: 		push @stack,($operand,$result);
                   5349: 	    } elsif ($chunk eq ')') {
                   5350: 		my $before=pop @stack;
                   5351: 		if (pop @stack eq '&') {
                   5352: 		    $result=$result>$before?$before:$result;
                   5353: 		} else {
                   5354: 		    $result=$result>$before?$result:$before;
                   5355: 		}
                   5356: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5357: 		$operand=$chunk;
                   5358: 	    } else {
                   5359: 		my $new=directcondval($chunk);
                   5360: 		if ($operand eq '&') {
                   5361: 		    $result=$result>$new?$new:$result;
                   5362: 		} else {
                   5363: 		    $result=$result>$new?$result:$new;
                   5364: 		}
                   5365: 	    }
                   5366: 	}
1.26      www      5367:     }
                   5368:     return $result;
1.421     albertel 5369: }
                   5370: 
                   5371: # ---------------------------------------------------- Devalidate courseresdata
                   5372: 
                   5373: sub devalidatecourseresdata {
                   5374:     my ($coursenum,$coursedomain)=@_;
                   5375:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5376:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5377: }
                   5378: 
1.763     www      5379: 
1.200     www      5380: # --------------------------------------------------- Course Resourcedata Query
                   5381: 
1.624     albertel 5382: sub get_courseresdata {
                   5383:     my ($coursenum,$coursedomain)=@_;
1.200     www      5384:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5385:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5386:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5387:     my %dumpreply;
1.417     albertel 5388:     unless (defined($cached)) {
1.624     albertel 5389: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5390: 	$result=\%dumpreply;
1.251     albertel 5391: 	my ($tmp) = keys(%dumpreply);
                   5392: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5393: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5394: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5395: 	    return $tmp;
1.416     albertel 5396: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5397: 	    $result=undef;
1.599     albertel 5398: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5399: 	}
                   5400:     }
1.624     albertel 5401:     return $result;
                   5402: }
                   5403: 
1.633     albertel 5404: sub devalidateuserresdata {
                   5405:     my ($uname,$udom)=@_;
                   5406:     my $hashid="$udom:$uname";
                   5407:     &devalidate_cache_new('userres',$hashid);
                   5408: }
                   5409: 
1.624     albertel 5410: sub get_userresdata {
                   5411:     my ($uname,$udom)=@_;
                   5412:     #most student don\'t have any data set, check if there is some data
                   5413:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5414: 
                   5415:     my $hashid="$udom:$uname";
                   5416:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5417:     if (!defined($cached)) {
                   5418: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5419: 	$result=\%resourcedata;
                   5420: 	&do_cache_new('userres',$hashid,$result,600);
                   5421:     }
                   5422:     my ($tmp)=keys(%$result);
                   5423:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5424: 	return $result;
                   5425:     }
                   5426:     #error 2 occurs when the .db doesn't exist
                   5427:     if ($tmp!~/error: 2 /) {
1.672     albertel 5428: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5429: 		 " Trying to get resource data for ".
                   5430: 		 $uname." at ".$udom.": ".
                   5431: 		 $tmp."</font>");
                   5432:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5433: 	#&EXT_cache_set($udom,$uname);
                   5434: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5435: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5436:     }
                   5437:     return $tmp;
                   5438: }
                   5439: 
                   5440: sub resdata {
                   5441:     my ($name,$domain,$type,@which)=@_;
                   5442:     my $result;
                   5443:     if ($type eq 'course') {
                   5444: 	$result=&get_courseresdata($name,$domain);
                   5445:     } elsif ($type eq 'user') {
                   5446: 	$result=&get_userresdata($name,$domain);
                   5447:     }
                   5448:     if (!ref($result)) { return $result; }    
1.251     albertel 5449:     foreach my $item (@which) {
1.417     albertel 5450: 	if (defined($result->{$item})) {
                   5451: 	    return $result->{$item};
1.251     albertel 5452: 	}
1.250     albertel 5453:     }
1.291     albertel 5454:     return undef;
1.200     www      5455: }
                   5456: 
1.379     matthew  5457: #
                   5458: # EXT resource caching routines
                   5459: #
                   5460: 
                   5461: sub clear_EXT_cache_status {
1.383     albertel 5462:     &delenv('cache.EXT.');
1.379     matthew  5463: }
                   5464: 
                   5465: sub EXT_cache_status {
                   5466:     my ($target_domain,$target_user) = @_;
1.383     albertel 5467:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5468:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5469:         # We know already the user has no data
                   5470:         return 1;
                   5471:     } else {
                   5472:         return 0;
                   5473:     }
                   5474: }
                   5475: 
                   5476: sub EXT_cache_set {
                   5477:     my ($target_domain,$target_user) = @_;
1.383     albertel 5478:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5479:     #&appenv($cachename => time);
1.379     matthew  5480: }
                   5481: 
1.28      www      5482: # --------------------------------------------------------- Value of a Variable
1.58      www      5483: sub EXT {
1.715     albertel 5484: 
1.395     albertel 5485:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5486:     unless ($varname) { return ''; }
1.218     albertel 5487:     #get real user name/domain, courseid and symb
                   5488:     my $courseid;
1.359     albertel 5489:     my $publicuser;
1.427     www      5490:     if ($symbparm) {
                   5491: 	$symbparm=&get_symb_from_alias($symbparm);
                   5492:     }
1.218     albertel 5493:     if (!($uname && $udom)) {
1.360     albertel 5494:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  5495: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 5496:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5497:     } else {
1.620     albertel 5498: 	$courseid=$env{'request.course.id'};
1.218     albertel 5499:     }
1.48      www      5500:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5501:     my $rest;
1.320     albertel 5502:     if (defined($therest[0])) {
1.48      www      5503:        $rest=join('.',@therest);
                   5504:     } else {
                   5505:        $rest='';
                   5506:     }
1.320     albertel 5507: 
1.57      www      5508:     my $qualifierrest=$qualifier;
                   5509:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5510:     my $spacequalifierrest=$space;
                   5511:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5512:     if ($realm eq 'user') {
1.48      www      5513: # --------------------------------------------------------------- user.resource
                   5514: 	if ($space eq 'resource') {
1.651     albertel 5515: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5516: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5517: 		 &&
1.744     albertel 5518: 		 ($symbparm eq &symbread()) ) {	
                   5519: 		# if we are in the middle of processing the resource the
                   5520: 		# get the value we are planning on committing
                   5521:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5522:                     return $Apache::lonhomework::results{$qualifierrest};
                   5523:                 } else {
                   5524:                     return $Apache::lonhomework::history{$qualifierrest};
                   5525:                 }
1.335     albertel 5526: 	    } else {
1.359     albertel 5527: 		my %restored;
1.620     albertel 5528: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5529: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5530: 		} else {
                   5531: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5532: 		}
1.335     albertel 5533: 		return $restored{$qualifierrest};
                   5534: 	    }
1.48      www      5535: # ----------------------------------------------------------------- user.access
                   5536:         } elsif ($space eq 'access') {
1.218     albertel 5537: 	    # FIXME - not supporting calls for a specific user
1.48      www      5538:             return &allowed($qualifier,$rest);
                   5539: # ------------------------------------------ user.preferences, user.environment
                   5540:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5541: 	    if (($uname eq $env{'user.name'}) &&
                   5542: 		($udom eq $env{'user.domain'})) {
                   5543: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5544: 	    } else {
1.359     albertel 5545: 		my %returnhash;
                   5546: 		if (!$publicuser) {
                   5547: 		    %returnhash=&userenvironment($udom,$uname,
                   5548: 						 $qualifierrest);
                   5549: 		}
1.218     albertel 5550: 		return $returnhash{$qualifierrest};
                   5551: 	    }
1.48      www      5552: # ----------------------------------------------------------------- user.course
                   5553:         } elsif ($space eq 'course') {
1.218     albertel 5554: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5555:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5556: # ------------------------------------------------------------------- user.role
                   5557:         } elsif ($space eq 'role') {
1.218     albertel 5558: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5559:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5560:             if ($qualifier eq 'value') {
                   5561: 		return $role;
                   5562:             } elsif ($qualifier eq 'extent') {
                   5563:                 return $where;
                   5564:             }
                   5565: # ----------------------------------------------------------------- user.domain
                   5566:         } elsif ($space eq 'domain') {
1.218     albertel 5567:             return $udom;
1.48      www      5568: # ------------------------------------------------------------------- user.name
                   5569:         } elsif ($space eq 'name') {
1.218     albertel 5570:             return $uname;
1.48      www      5571: # ---------------------------------------------------- Any other user namespace
1.29      www      5572:         } else {
1.359     albertel 5573: 	    my %reply;
                   5574: 	    if (!$publicuser) {
                   5575: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5576: 	    }
                   5577: 	    return $reply{$qualifierrest};
1.48      www      5578:         }
1.236     www      5579:     } elsif ($realm eq 'query') {
                   5580: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5581:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5582: 						[$spacequalifierrest]);
1.620     albertel 5583: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5584:    } elsif ($realm eq 'request') {
1.48      www      5585: # ------------------------------------------------------------- request.browser
                   5586:         if ($space eq 'browser') {
1.430     www      5587: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5588: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5589: 		    return 1;
                   5590: 		} else {
                   5591: 		    return 0;
                   5592: 		}
                   5593: 	    } else {
1.620     albertel 5594: 		return $env{'browser.'.$qualifier};
1.430     www      5595: 	    }
1.57      www      5596: # ------------------------------------------------------------ request.filename
                   5597:         } else {
1.620     albertel 5598:             return $env{'request.'.$spacequalifierrest};
1.29      www      5599:         }
1.28      www      5600:     } elsif ($realm eq 'course') {
1.48      www      5601: # ---------------------------------------------------------- course.description
1.620     albertel 5602:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5603:     } elsif ($realm eq 'resource') {
1.165     www      5604: 
1.620     albertel 5605: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5606: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5607: 	}
1.693     albertel 5608: 
                   5609: 	if ($space eq 'title') {
                   5610: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5611: 	    return &gettitle($symbparm);
                   5612: 	}
                   5613: 	
                   5614: 	if ($space eq 'map') {
                   5615: 	    my ($map) = &decode_symb($symbparm);
                   5616: 	    return &symbread($map);
                   5617: 	}
                   5618: 
                   5619: 	my ($section, $group, @groups);
1.593     albertel 5620: 	my ($courselevelm,$courselevel);
1.539     albertel 5621: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5622: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5623: 
1.218     albertel 5624: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5625: 
1.60      www      5626: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5627: 	    my $symbp=$symbparm;
1.735     albertel 5628: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5629: 
                   5630: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5631: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5632: 
1.620     albertel 5633: 	    if (($env{'user.name'} eq $uname) &&
                   5634: 		($env{'user.domain'} eq $udom)) {
                   5635: 		$section=$env{'request.course.sec'};
1.733     raeburn  5636:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5637:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5638: 	    } else {
1.539     albertel 5639: 		if (! defined($usection)) {
1.551     albertel 5640: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5641: 		} else {
                   5642: 		    $section = $usection;
                   5643: 		}
1.733     raeburn  5644:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5645: 	    }
                   5646: 
                   5647: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5648: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5649: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5650: 
1.593     albertel 5651: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5652: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5653: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5654: 
1.60      www      5655: # ----------------------------------------------------------- first, check user
1.624     albertel 5656: 
                   5657: 	    my $userreply=&resdata($uname,$udom,'user',
                   5658: 				       ($courselevelr,$courselevelm,
                   5659: 					$courselevel));
                   5660: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5661: 
1.594     albertel 5662: # ------------------------------------------------ second, check some of course
1.684     raeburn  5663:             my $coursereply;
1.691     raeburn  5664:             if (@groups > 0) {
                   5665:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5666:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5667:                 if (defined($coursereply)) { return $coursereply; }
                   5668:             }
1.96      www      5669: 
1.684     raeburn  5670: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5671: 				     $env{'course.'.$courseid.'.domain'},
                   5672: 				     'course',
                   5673: 				     ($seclevelr,$seclevelm,$seclevel,
                   5674: 				      $courselevelr));
1.287     albertel 5675: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5676: 
1.60      www      5677: # ------------------------------------------------------ third, check map parms
1.218     albertel 5678: 	    my %parmhash=();
                   5679: 	    my $thisparm='';
                   5680: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5681: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5682: 		    &GDBM_READER(),0640)) {
1.218     albertel 5683: 		$thisparm=$parmhash{$symbparm};
                   5684: 		untie(%parmhash);
                   5685: 	    }
                   5686: 	    if ($thisparm) { return $thisparm; }
                   5687: 	}
1.594     albertel 5688: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5689: 
1.218     albertel 5690: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5691: 	my $filename;
                   5692: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5693: 	if ($symbparm) {
1.409     www      5694: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5695: 	} else {
1.620     albertel 5696: 	    $filename=$env{'request.filename'};
1.282     albertel 5697: 	}
                   5698: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5699: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5700: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5701: 	if (defined($metadata)) { return $metadata; }
1.142     www      5702: 
1.594     albertel 5703: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5704: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5705: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5706: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5707: 				     $env{'course.'.$courseid.'.domain'},
                   5708: 				     'course',
                   5709: 				     ($courselevelm,$courselevel));
1.593     albertel 5710: 	    if (defined($coursereply)) { return $coursereply; }
                   5711: 	}
1.145     www      5712: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5713: 	unless ($space eq '0') {
1.336     albertel 5714: 	    my @parts=split(/_/,$space);
                   5715: 	    my $id=pop(@parts);
                   5716: 	    my $part=join('_',@parts);
                   5717: 	    if ($part eq '') { $part='0'; }
                   5718: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5719: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5720: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5721: 	}
1.395     albertel 5722: 	if ($recurse) { return undef; }
                   5723: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5724: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5725: 
1.48      www      5726: # ---------------------------------------------------- Any other user namespace
                   5727:     } elsif ($realm eq 'environment') {
                   5728: # ----------------------------------------------------------------- environment
1.620     albertel 5729: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5730: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5731: 	} else {
1.770     albertel 5732: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5733: 		return '';
                   5734: 	    }
1.219     albertel 5735: 	    my %returnhash=&userenvironment($udom,$uname,
                   5736: 					    $spacequalifierrest);
                   5737: 	    return $returnhash{$spacequalifierrest};
                   5738: 	}
1.28      www      5739:     } elsif ($realm eq 'system') {
1.48      www      5740: # ----------------------------------------------------------------- system.time
                   5741: 	if ($space eq 'time') {
                   5742: 	    return time;
                   5743:         }
1.696     albertel 5744:     } elsif ($realm eq 'server') {
                   5745: # ----------------------------------------------------------------- system.time
                   5746: 	if ($space eq 'name') {
                   5747: 	    return $ENV{'SERVER_NAME'};
                   5748:         }
1.28      www      5749:     }
1.48      www      5750:     return '';
1.61      www      5751: }
                   5752: 
1.691     raeburn  5753: sub check_group_parms {
                   5754:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5755:     my @groupitems = ();
                   5756:     my $resultitem;
                   5757:     my @levels = ($symbparm,$mapparm,$what);
                   5758:     foreach my $group (@{$groups}) {
                   5759:         foreach my $level (@levels) {
                   5760:              my $item = $courseid.'.['.$group.'].'.$level;
                   5761:              push(@groupitems,$item);
                   5762:         }
                   5763:     }
                   5764:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5765:                             $env{'course.'.$courseid.'.domain'},
                   5766:                                      'course',@groupitems);
                   5767:     return $coursereply;
                   5768: }
                   5769: 
                   5770: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5771:     my ($courseid,@groups) = @_;
                   5772:     @groups = sort(@groups);
1.691     raeburn  5773:     return @groups;
                   5774: }
                   5775: 
1.395     albertel 5776: sub packages_tab_default {
                   5777:     my ($uri,$varname)=@_;
                   5778:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5779: 
                   5780:     my (@extension,@specifics,$do_default);
                   5781:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5782: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5783: 	if ($pack_type eq 'default') {
                   5784: 	    $do_default=1;
                   5785: 	} elsif ($pack_type eq 'extension') {
                   5786: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5787: 	} else {
                   5788: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5789: 	}
                   5790:     }
                   5791:     # first look for a package that matches the requested part id
                   5792:     foreach my $package (@specifics) {
                   5793: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5794: 	next if ($pack_part ne $part);
                   5795: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5796: 	    return $packagetab{"$pack_type&$name&default"};
                   5797: 	}
                   5798:     }
                   5799:     # look for any possible matching non extension_ package
                   5800:     foreach my $package (@specifics) {
                   5801: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5802: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5803: 	    return $packagetab{"$pack_type&$name&default"};
                   5804: 	}
1.585     albertel 5805: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5806: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5807: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5808: 	}
                   5809:     }
1.738     albertel 5810:     # look for any posible extension_ match
                   5811:     foreach my $package (@extension) {
                   5812: 	my ($package,$pack_type)=@{$package};
                   5813: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5814: 	    return $packagetab{"$pack_type&$name&default"};
                   5815: 	}
                   5816: 	if (defined($packagetab{$package."&$name&default"})) {
                   5817: 	    return $packagetab{$package."&$name&default"};
                   5818: 	}
                   5819:     }
                   5820:     # look for a global default setting
                   5821:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5822: 	return $packagetab{"default&$name&default"};
                   5823:     }
1.395     albertel 5824:     return undef;
                   5825: }
                   5826: 
1.334     albertel 5827: sub add_prefix_and_part {
                   5828:     my ($prefix,$part)=@_;
                   5829:     my $keyroot;
                   5830:     if (defined($prefix) && $prefix !~ /^__/) {
                   5831: 	# prefix that has a part already
                   5832: 	$keyroot=$prefix;
                   5833:     } elsif (defined($prefix)) {
                   5834: 	# prefix that is missing a part
                   5835: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5836:     } else {
                   5837: 	# no prefix at all
                   5838: 	if (defined($part)) { $keyroot='_'.$part; }
                   5839:     }
                   5840:     return $keyroot;
                   5841: }
                   5842: 
1.71      www      5843: # ---------------------------------------------------------------- Get metadata
                   5844: 
1.599     albertel 5845: my %metaentry;
1.71      www      5846: sub metadata {
1.176     www      5847:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5848:     $uri=&declutter($uri);
1.288     albertel 5849:     # if it is a non metadata possible uri return quickly
1.529     albertel 5850:     if (($uri eq '') || 
                   5851: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5852: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5853:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5854: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5855: 	return undef;
1.288     albertel 5856:     }
1.73      www      5857:     my $filename=$uri;
                   5858:     $uri=~s/\.meta$//;
1.172     www      5859: #
                   5860: # Is the metadata already cached?
1.177     www      5861: # Look at timestamp of caching
1.172     www      5862: # Everything is cached by the main uri, libraries are never directly cached
                   5863: #
1.428     albertel 5864:     if (!defined($liburi)) {
1.599     albertel 5865: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5866: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5867:     }
                   5868:     {
1.172     www      5869: #
                   5870: # Is this a recursive call for a library?
                   5871: #
1.599     albertel 5872: #	if (! exists($metacache{$uri})) {
                   5873: #	    $metacache{$uri}={};
                   5874: #	}
1.171     www      5875:         if ($liburi) {
                   5876: 	    $liburi=&declutter($liburi);
                   5877:             $filename=$liburi;
1.401     bowersj2 5878:         } else {
1.599     albertel 5879: 	    &devalidate_cache_new('meta',$uri);
                   5880: 	    undef(%metaentry);
1.401     bowersj2 5881: 	}
1.140     www      5882:         my %metathesekeys=();
1.73      www      5883:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5884: 	my $metastring;
1.768     albertel 5885: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 5886: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5887: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5888: 	    $metastring=&getfile($file);
1.489     albertel 5889: 	}
1.208     albertel 5890:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5891:         my $token;
1.140     www      5892:         undef %metathesekeys;
1.71      www      5893:         while ($token=$parser->get_token) {
1.339     albertel 5894: 	    if ($token->[0] eq 'S') {
                   5895: 		if (defined($token->[2]->{'package'})) {
1.172     www      5896: #
                   5897: # This is a package - get package info
                   5898: #
1.339     albertel 5899: 		    my $package=$token->[2]->{'package'};
                   5900: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5901: 		    if (defined($token->[2]->{'id'})) { 
                   5902: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5903: 		    }
1.599     albertel 5904: 		    if ($metaentry{':packages'}) {
                   5905: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5906: 		    } else {
1.599     albertel 5907: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5908: 		    }
1.736     albertel 5909: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 5910: 			my $part=$keyroot;
                   5911: 			$part=~s/^\_//;
1.736     albertel 5912: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   5913: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   5914: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 5915: 			    # ignore package.tab specified default values
                   5916:                             # here &package_tab_default() will fetch those
                   5917: 			    if ($subp eq 'default') { next; }
1.736     albertel 5918: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 5919: 			    my $unikey;
                   5920: 			    if ($pack =~ /_0$/) {
                   5921: 				$unikey='parameter_0_'.$name;
                   5922: 				$part=0;
                   5923: 			    } else {
                   5924: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5925: 			    }
1.339     albertel 5926: 			    if ($subp eq 'display') {
                   5927: 				$value.=' [Part: '.$part.']';
                   5928: 			    }
1.599     albertel 5929: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5930: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5931: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   5932: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 5933: 			    }
1.599     albertel 5934: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   5935: 				$metaentry{':'.$unikey}=
                   5936: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 5937: 			    }
1.339     albertel 5938: 			}
                   5939: 		    }
                   5940: 		} else {
1.172     www      5941: #
                   5942: # This is not a package - some other kind of start tag
1.339     albertel 5943: #
                   5944: 		    my $entry=$token->[1];
                   5945: 		    my $unikey;
                   5946: 		    if ($entry eq 'import') {
                   5947: 			$unikey='';
                   5948: 		    } else {
                   5949: 			$unikey=$entry;
                   5950: 		    }
                   5951: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5952: 
                   5953: 		    if (defined($token->[2]->{'id'})) { 
                   5954: 			$unikey.='_'.$token->[2]->{'id'}; 
                   5955: 		    }
1.175     www      5956: 
1.339     albertel 5957: 		    if ($entry eq 'import') {
1.175     www      5958: #
                   5959: # Importing a library here
1.339     albertel 5960: #
                   5961: 			if ($depthcount<20) {
                   5962: 			    my $location=$parser->get_text('/import');
                   5963: 			    my $dir=$filename;
                   5964: 			    $dir=~s|[^/]*$||;
                   5965: 			    $location=&filelocation($dir,$location);
1.736     albertel 5966: 			    my $metadata = 
                   5967: 				&metadata($uri,'keys', $location,$unikey,
                   5968: 					  $depthcount+1);
                   5969: 			    foreach my $meta (split(',',$metadata)) {
                   5970: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   5971: 				$metathesekeys{$meta}=1;
1.339     albertel 5972: 			    }
                   5973: 			}
                   5974: 		    } else { 
                   5975: 			
                   5976: 			if (defined($token->[2]->{'name'})) { 
                   5977: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   5978: 			}
                   5979: 			$metathesekeys{$unikey}=1;
1.736     albertel 5980: 			foreach my $param (@{$token->[3]}) {
                   5981: 			    $metaentry{':'.$unikey.'.'.$param} =
                   5982: 				$token->[2]->{$param};
1.339     albertel 5983: 			}
                   5984: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 5985: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 5986: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   5987: 		 # only ws inside the tag, and not in default, so use default
                   5988: 		 # as value
1.599     albertel 5989: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 5990: 			} else {
1.321     albertel 5991: 		  # either something interesting inside the tag or default
                   5992:                   # uninteresting
1.599     albertel 5993: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 5994: 			}
1.172     www      5995: # end of not-a-package not-a-library import
1.339     albertel 5996: 		    }
1.172     www      5997: # end of not-a-package start tag
1.339     albertel 5998: 		}
1.172     www      5999: # the next is the end of "start tag"
1.339     albertel 6000: 	    }
                   6001: 	}
1.483     albertel 6002: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6003: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6004: 	    #no specific packages #how's our extension
                   6005: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6006: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6007: 					 \%metathesekeys);
                   6008: 	}
1.599     albertel 6009: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6010: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6011: 		#no specific packages well let's get default then
                   6012: 		if ($key!~/^default&/) { next; }
1.488     albertel 6013: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6014: 					     \%metathesekeys);
                   6015: 	    }
                   6016: 	}
1.338     www      6017: # are there custom rights to evaluate
1.599     albertel 6018: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6019: 
1.338     www      6020:     #
                   6021:     # Importing a rights file here
1.339     albertel 6022:     #
                   6023: 	    unless ($depthcount) {
1.599     albertel 6024: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6025: 		my $dir=$filename;
                   6026: 		$dir=~s|[^/]*$||;
                   6027: 		$location=&filelocation($dir,$location);
1.736     albertel 6028: 		my $rights_metadata =
                   6029: 		    &metadata($uri,'keys',$location,'_rights',
                   6030: 			      $depthcount+1);
                   6031: 		foreach my $rights (split(',',$rights_metadata)) {
                   6032: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6033: 		    $metathesekeys{$rights}=1;
1.339     albertel 6034: 		}
                   6035: 	    }
                   6036: 	}
1.737     albertel 6037: 	# uniqifiy package listing
                   6038: 	my %seen;
                   6039: 	my @uniq_packages =
                   6040: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6041: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6042: 
                   6043: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6044: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6045: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6046: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6047: # this is the end of "was not already recently cached
1.71      www      6048:     }
1.599     albertel 6049:     return $metaentry{':'.$what};
1.261     albertel 6050: }
                   6051: 
1.488     albertel 6052: sub metadata_create_package_def {
1.483     albertel 6053:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6054:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6055:     if ($subp eq 'default') { next; }
                   6056:     
1.599     albertel 6057:     if (defined($metaentry{':packages'})) {
                   6058: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6059:     } else {
1.599     albertel 6060: 	$metaentry{':packages'}=$package;
1.483     albertel 6061:     }
                   6062:     my $value=$packagetab{$key};
                   6063:     my $unikey;
                   6064:     $unikey='parameter_0_'.$name;
1.599     albertel 6065:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6066:     $$metathesekeys{$unikey}=1;
1.599     albertel 6067:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6068: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6069:     }
1.599     albertel 6070:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6071: 	$metaentry{':'.$unikey}=
                   6072: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6073:     }
                   6074: }
                   6075: 
1.261     albertel 6076: sub metadata_generate_part0 {
                   6077:     my ($metadata,$metacache,$uri) = @_;
                   6078:     my %allnames;
1.737     albertel 6079:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6080: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6081: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6082: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6083: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6084: 	    $allnames{$name}=$part;
                   6085: 	  }
                   6086: 	}
                   6087:     }
                   6088:     foreach my $name (keys(%allnames)) {
                   6089:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6090:       my $key=":parameter_0_$name";
1.261     albertel 6091:       $$metacache{"$key.part"}='0';
                   6092:       $$metacache{"$key.name"}=$name;
1.428     albertel 6093:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6094: 					   $allnames{$name}.'_'.$name.
                   6095: 					   '.type'};
1.428     albertel 6096:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6097: 			     '.display'};
1.644     www      6098:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6099:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6100:       $$metacache{"$key.display"}=$olddis;
                   6101:     }
1.71      www      6102: }
                   6103: 
1.764     albertel 6104: # ------------------------------------------------------ Devalidate title cache
                   6105: 
                   6106: sub devalidate_title_cache {
                   6107:     my ($url)=@_;
                   6108:     if (!$env{'request.course.id'}) { return; }
                   6109:     my $symb=&symbread($url);
                   6110:     if (!$symb) { return; }
                   6111:     my $key=$env{'request.course.id'}."\0".$symb;
                   6112:     &devalidate_cache_new('title',$key);
                   6113: }
                   6114: 
1.301     www      6115: # ------------------------------------------------- Get the title of a resource
                   6116: 
                   6117: sub gettitle {
                   6118:     my $urlsymb=shift;
                   6119:     my $symb=&symbread($urlsymb);
1.534     albertel 6120:     if ($symb) {
1.620     albertel 6121: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6122: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6123: 	if (defined($cached)) { 
                   6124: 	    return $result;
                   6125: 	}
1.534     albertel 6126: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6127: 	my $title='';
                   6128: 	my %bighash;
1.620     albertel 6129: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6130: 		&GDBM_READER(),0640)) {
                   6131: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6132: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6133: 	    untie %bighash;
                   6134: 	}
                   6135: 	$title=~s/\&colon\;/\:/gs;
                   6136: 	if ($title) {
1.599     albertel 6137: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6138: 	}
                   6139: 	$urlsymb=$url;
                   6140:     }
                   6141:     my $title=&metadata($urlsymb,'title');
                   6142:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6143:     return $title;
1.301     www      6144: }
1.613     albertel 6145: 
1.614     albertel 6146: sub get_slot {
                   6147:     my ($which,$cnum,$cdom)=@_;
                   6148:     if (!$cnum || !$cdom) {
                   6149: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 6150: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6151: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6152:     }
1.703     albertel 6153:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6154:     my %slotinfo;
                   6155:     if (exists($remembered{$key})) {
                   6156: 	$slotinfo{$which} = $remembered{$key};
                   6157:     } else {
                   6158: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6159: 	&Apache::lonhomework::showhash(%slotinfo);
                   6160: 	my ($tmp)=keys(%slotinfo);
                   6161: 	if ($tmp=~/^error:/) { return (); }
                   6162: 	$remembered{$key} = $slotinfo{$which};
                   6163:     }
1.616     albertel 6164:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6165: 	return %{$slotinfo{$which}};
                   6166:     }
                   6167:     return $slotinfo{$which};
1.614     albertel 6168: }
1.31      www      6169: # ------------------------------------------------- Update symbolic store links
                   6170: 
                   6171: sub symblist {
                   6172:     my ($mapname,%newhash)=@_;
1.438     www      6173:     $mapname=&deversion(&declutter($mapname));
1.31      www      6174:     my %hash;
1.620     albertel 6175:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6176:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6177:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6178: 	    foreach my $url (keys %newhash) {
                   6179: 		next if ($url eq 'last_known'
                   6180: 			 && $env{'form.no_update_last_known'});
                   6181: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6182: 						    $newhash{$url}->[1],
                   6183: 						    $newhash{$url}->[0]);
1.191     harris41 6184:             }
1.31      www      6185:             if (untie(%hash)) {
                   6186: 		return 'ok';
                   6187:             }
                   6188:         }
                   6189:     }
                   6190:     return 'error';
1.212     www      6191: }
                   6192: 
                   6193: # --------------------------------------------------------------- Verify a symb
                   6194: 
                   6195: sub symbverify {
1.510     www      6196:     my ($symb,$thisurl)=@_;
                   6197:     my $thisfn=$thisurl;
                   6198: # wrapper not part of symbs
                   6199:     $thisfn=~s/^\/adm\/wrapper//;
1.694     albertel 6200:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
1.439     www      6201:     $thisfn=&declutter($thisfn);
1.215     www      6202: # direct jump to resource in page or to a sequence - will construct own symbs
                   6203:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6204: # check URL part
1.409     www      6205:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6206: 
1.431     www      6207:     unless ($url eq $thisfn) { return 0; }
1.213     www      6208: 
1.216     www      6209:     $symb=&symbclean($symb);
1.510     www      6210:     $thisurl=&deversion($thisurl);
1.439     www      6211:     $thisfn=&deversion($thisfn);
1.213     www      6212: 
                   6213:     my %bighash;
                   6214:     my $okay=0;
1.431     www      6215: 
1.620     albertel 6216:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6217:                             &GDBM_READER(),0640)) {
1.510     www      6218:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6219:         unless ($ids) { 
1.510     www      6220:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6221:         }
                   6222:         if ($ids) {
                   6223: # ------------------------------------------------------------------- Has ID(s)
                   6224: 	    foreach (split(/\,/,$ids)) {
1.644     www      6225: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      6226:                if (
                   6227:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6228:    eq $symb) { 
1.620     albertel 6229: 		   if (($env{'request.role.adv'}) ||
                   6230: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 6231: 		       $okay=1; 
                   6232: 		   }
                   6233: 	       }
1.216     www      6234: 	   }
                   6235:         }
1.213     www      6236: 	untie(%bighash);
                   6237:     }
                   6238:     return $okay;
1.31      www      6239: }
                   6240: 
1.210     www      6241: # --------------------------------------------------------------- Clean-up symb
                   6242: 
                   6243: sub symbclean {
                   6244:     my $symb=shift;
1.568     albertel 6245:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6246: # remove version from map
                   6247:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6248: 
1.210     www      6249: # remove version from URL
                   6250:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6251: 
1.507     www      6252: # remove wrapper
                   6253: 
1.510     www      6254:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6255:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6256:     return $symb;
1.409     www      6257: }
                   6258: 
                   6259: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6260: 
                   6261: sub encode_symb {
                   6262:     my ($map,$resid,$url)=@_;
                   6263:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6264: }
1.409     www      6265: 
                   6266: sub decode_symb {
1.568     albertel 6267:     my $symb=shift;
                   6268:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6269:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6270:     return (&fixversion($map),$resid,&fixversion($url));
                   6271: }
                   6272: 
                   6273: sub fixversion {
                   6274:     my $fn=shift;
1.609     banghart 6275:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6276:     my %bighash;
                   6277:     my $uri=&clutter($fn);
1.620     albertel 6278:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6279: # is this cached?
1.599     albertel 6280:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6281:     if (defined($cached)) { return $result; }
                   6282: # unfortunately not cached, or expired
1.620     albertel 6283:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6284: 	    &GDBM_READER(),0640)) {
                   6285:  	if ($bighash{'version_'.$uri}) {
                   6286:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6287:  	    unless (($version eq 'mostrecent') || 
                   6288: 		    ($version==&getversion($uri))) {
1.440     www      6289:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6290:  	    }
                   6291:  	}
                   6292:  	untie %bighash;
1.413     www      6293:     }
1.599     albertel 6294:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6295: }
                   6296: 
                   6297: sub deversion {
                   6298:     my $url=shift;
                   6299:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6300:     return $url;
1.210     www      6301: }
                   6302: 
1.31      www      6303: # ------------------------------------------------------ Return symb list entry
                   6304: 
                   6305: sub symbread {
1.249     www      6306:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6307:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6308:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6309: # no filename provided? try from environment
1.44      www      6310:     unless ($thisfn) {
1.620     albertel 6311:         if ($env{'request.symb'}) {
                   6312: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6313: 	}
1.620     albertel 6314: 	$thisfn=$env{'request.filename'};
1.44      www      6315:     }
1.569     albertel 6316:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6317: # is that filename actually a symb? Verify, clean, and return
                   6318:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6319: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6320: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6321: 	}
1.242     www      6322:     }
1.44      www      6323:     $thisfn=declutter($thisfn);
1.31      www      6324:     my %hash;
1.37      www      6325:     my %bighash;
                   6326:     my $syval='';
1.620     albertel 6327:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6328:         my $targetfn = $thisfn;
1.609     banghart 6329:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6330:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6331:         }
1.687     albertel 6332: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6333: 	    $targetfn=$1;
                   6334: 	}
1.620     albertel 6335:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6336:                       &GDBM_READER(),0640)) {
1.481     raeburn  6337: 	    $syval=$hash{$targetfn};
1.37      www      6338:             untie(%hash);
                   6339:         }
                   6340: # ---------------------------------------------------------- There was an entry
                   6341:         if ($syval) {
1.601     albertel 6342: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6343: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6344: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6345: 		    #return $env{$cache_str}='';
1.601     albertel 6346: 		#}    
                   6347: 		#$syval.=$1;
                   6348: 	    #}
1.37      www      6349:         } else {
                   6350: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6351:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6352:                             &GDBM_READER(),0640)) {
1.37      www      6353: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6354:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6355:               unless ($ids) { 
                   6356:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6357:               }
                   6358:               unless ($ids) {
                   6359: # alias?
                   6360: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6361:               }
1.37      www      6362:               if ($ids) {
                   6363: # ------------------------------------------------------------------- Has ID(s)
                   6364:                  my @possibilities=split(/\,/,$ids);
1.39      www      6365:                  if ($#possibilities==0) {
                   6366: # ----------------------------------------------- There is only one possibility
1.37      www      6367: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6368: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6369: 						    $resid,$thisfn);
1.249     www      6370:                  } elsif (!$donotrecurse) {
1.39      www      6371: # ------------------------------------------ There is more than one possibility
                   6372:                      my $realpossible=0;
1.191     harris41 6373:                      foreach (@possibilities) {
1.39      www      6374: 			 my $file=$bighash{'src_'.$_};
                   6375:                          if (&allowed('bre',$file)) {
                   6376:          		    my ($mapid,$resid)=split(/\./,$_);
                   6377:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6378: 				$realpossible++;
1.626     albertel 6379:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6380: 						    $resid,$thisfn);
1.39      www      6381:                             }
                   6382: 			 }
1.191     harris41 6383:                      }
1.39      www      6384: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6385:                  } else {
                   6386:                      $syval='';
1.37      www      6387:                  }
                   6388: 	      }
                   6389:               untie(%bighash)
1.481     raeburn  6390:            }
1.31      www      6391:         }
1.62      www      6392:         if ($syval) {
1.620     albertel 6393: 	    return $env{$cache_str}=$syval;
1.62      www      6394:         }
1.31      www      6395:     }
1.44      www      6396:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6397:     return $env{$cache_str}='';
1.31      www      6398: }
                   6399: 
                   6400: # ---------------------------------------------------------- Return random seed
                   6401: 
1.32      www      6402: sub numval {
                   6403:     my $txt=shift;
                   6404:     $txt=~tr/A-J/0-9/;
                   6405:     $txt=~tr/a-j/0-9/;
                   6406:     $txt=~tr/K-T/0-9/;
                   6407:     $txt=~tr/k-t/0-9/;
                   6408:     $txt=~tr/U-Z/0-5/;
                   6409:     $txt=~tr/u-z/0-5/;
                   6410:     $txt=~s/\D//g;
1.564     albertel 6411:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6412:     return int($txt);
1.368     albertel 6413: }
                   6414: 
1.484     albertel 6415: sub numval2 {
                   6416:     my $txt=shift;
                   6417:     $txt=~tr/A-J/0-9/;
                   6418:     $txt=~tr/a-j/0-9/;
                   6419:     $txt=~tr/K-T/0-9/;
                   6420:     $txt=~tr/k-t/0-9/;
                   6421:     $txt=~tr/U-Z/0-5/;
                   6422:     $txt=~tr/u-z/0-5/;
                   6423:     $txt=~s/\D//g;
                   6424:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6425:     my $total;
                   6426:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6427:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6428:     return int($total);
                   6429: }
                   6430: 
1.575     albertel 6431: sub numval3 {
                   6432:     use integer;
                   6433:     my $txt=shift;
                   6434:     $txt=~tr/A-J/0-9/;
                   6435:     $txt=~tr/a-j/0-9/;
                   6436:     $txt=~tr/K-T/0-9/;
                   6437:     $txt=~tr/k-t/0-9/;
                   6438:     $txt=~tr/U-Z/0-5/;
                   6439:     $txt=~tr/u-z/0-5/;
                   6440:     $txt=~s/\D//g;
                   6441:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6442:     my $total;
                   6443:     foreach my $val (@txts) { $total+=$val; }
                   6444:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6445:     return $total;
                   6446: }
                   6447: 
1.675     albertel 6448: sub digest {
                   6449:     my ($data)=@_;
                   6450:     my $digest=&Digest::MD5::md5($data);
                   6451:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6452:     my ($e,$f);
                   6453:     {
                   6454:         use integer;
                   6455:         $e=($a+$b);
                   6456:         $f=($c+$d);
                   6457:         if ($_64bit) {
                   6458:             $e=(($e<<32)>>32);
                   6459:             $f=(($f<<32)>>32);
                   6460:         }
                   6461:     }
                   6462:     if (wantarray) {
                   6463: 	return ($e,$f);
                   6464:     } else {
                   6465: 	my $g;
                   6466: 	{
                   6467: 	    use integer;
                   6468: 	    $g=($e+$f);
                   6469: 	    if ($_64bit) {
                   6470: 		$g=(($g<<32)>>32);
                   6471: 	    }
                   6472: 	}
                   6473: 	return $g;
                   6474:     }
                   6475: }
                   6476: 
1.368     albertel 6477: sub latest_rnd_algorithm_id {
1.675     albertel 6478:     return '64bit5';
1.366     albertel 6479: }
1.32      www      6480: 
1.503     albertel 6481: sub get_rand_alg {
                   6482:     my ($courseid)=@_;
                   6483:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   6484:     if ($courseid) {
1.620     albertel 6485: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6486:     }
                   6487:     return &latest_rnd_algorithm_id();
                   6488: }
                   6489: 
1.562     albertel 6490: sub validCODE {
                   6491:     my ($CODE)=@_;
                   6492:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6493:     return 0;
                   6494: }
                   6495: 
1.491     albertel 6496: sub getCODE {
1.620     albertel 6497:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6498:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6499: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6500: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6501: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6502:     }
                   6503:     return undef;
                   6504: }
                   6505: 
1.31      www      6506: sub rndseed {
1.155     albertel 6507:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6508: 
                   6509:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 6510:     if (!$symb) {
1.366     albertel 6511: 	unless ($symb=$wsymb) { return time; }
                   6512:     }
                   6513:     if (!$courseid) { $courseid=$wcourseid; }
                   6514:     if (!$domain) { $domain=$wdomain; }
                   6515:     if (!$username) { $username=$wusername }
1.503     albertel 6516:     my $which=&get_rand_alg();
1.491     albertel 6517:     if (defined(&getCODE())) {
1.675     albertel 6518: 	if ($which eq '64bit5') {
                   6519: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6520: 	} elsif ($which eq '64bit4') {
1.575     albertel 6521: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6522: 	} else {
                   6523: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6524: 	}
1.675     albertel 6525:     } elsif ($which eq '64bit5') {
                   6526: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6527:     } elsif ($which eq '64bit4') {
                   6528: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6529:     } elsif ($which eq '64bit3') {
                   6530: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6531:     } elsif ($which eq '64bit2') {
                   6532: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6533:     } elsif ($which eq '64bit') {
                   6534: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6535:     }
                   6536:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6537: }
                   6538: 
                   6539: sub rndseed_32bit {
                   6540:     my ($symb,$courseid,$domain,$username)=@_;
                   6541:     {
                   6542: 	use integer;
                   6543: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6544: 	my $symbseed=numval($symb) << 22;
                   6545: 	my $namechck=unpack("%32C*",$username) << 17;
                   6546: 	my $nameseed=numval($username) << 12;
                   6547: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6548: 	my $courseseed=unpack("%32C*",$courseid);
                   6549: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   6550: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6551: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6552: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6553: 	return $num;
                   6554:     }
                   6555: }
                   6556: 
                   6557: sub rndseed_64bit {
                   6558:     my ($symb,$courseid,$domain,$username)=@_;
                   6559:     {
                   6560: 	use integer;
                   6561: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6562: 	my $symbseed=numval($symb) << 10;
                   6563: 	my $namechck=unpack("%32S*",$username);
                   6564: 	
                   6565: 	my $nameseed=numval($username) << 21;
                   6566: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6567: 	my $courseseed=unpack("%32S*",$courseid);
                   6568: 	
                   6569: 	my $num1=$symbchck+$symbseed+$namechck;
                   6570: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6571: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6572: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 6573: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6574: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6575: 	return "$num1,$num2";
1.155     albertel 6576:     }
1.366     albertel 6577: }
                   6578: 
1.443     albertel 6579: sub rndseed_64bit2 {
                   6580:     my ($symb,$courseid,$domain,$username)=@_;
                   6581:     {
                   6582: 	use integer;
                   6583: 	# strings need to be an even # of cahracters long, it it is odd the
                   6584:         # last characters gets thrown away
                   6585: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6586: 	my $symbseed=numval($symb) << 10;
                   6587: 	my $namechck=unpack("%32S*",$username.' ');
                   6588: 	
                   6589: 	my $nameseed=numval($username) << 21;
1.501     albertel 6590: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6591: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6592: 	
                   6593: 	my $num1=$symbchck+$symbseed+$namechck;
                   6594: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6595: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6596: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   6597: 	return "$num1,$num2";
                   6598:     }
                   6599: }
                   6600: 
                   6601: sub rndseed_64bit3 {
                   6602:     my ($symb,$courseid,$domain,$username)=@_;
                   6603:     {
                   6604: 	use integer;
                   6605: 	# strings need to be an even # of cahracters long, it it is odd the
                   6606:         # last characters gets thrown away
                   6607: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6608: 	my $symbseed=numval2($symb) << 10;
                   6609: 	my $namechck=unpack("%32S*",$username.' ');
                   6610: 	
                   6611: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6612: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6613: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6614: 	
                   6615: 	my $num1=$symbchck+$symbseed+$namechck;
                   6616: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6617: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 6618: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6619: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6620: 	
1.503     albertel 6621: 	return "$num1:$num2";
1.443     albertel 6622:     }
                   6623: }
                   6624: 
1.575     albertel 6625: sub rndseed_64bit4 {
                   6626:     my ($symb,$courseid,$domain,$username)=@_;
                   6627:     {
                   6628: 	use integer;
                   6629: 	# strings need to be an even # of cahracters long, it it is odd the
                   6630:         # last characters gets thrown away
                   6631: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6632: 	my $symbseed=numval3($symb) << 10;
                   6633: 	my $namechck=unpack("%32S*",$username.' ');
                   6634: 	
                   6635: 	my $nameseed=numval3($username) << 21;
                   6636: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6637: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6638: 	
                   6639: 	my $num1=$symbchck+$symbseed+$namechck;
                   6640: 	my $num2=$nameseed+$domainseed+$courseseed;
                   6641: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6642: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   6643: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6644: 	
                   6645: 	return "$num1:$num2";
                   6646:     }
                   6647: }
                   6648: 
1.675     albertel 6649: sub rndseed_64bit5 {
                   6650:     my ($symb,$courseid,$domain,$username)=@_;
                   6651:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6652:     return "$num1:$num2";
                   6653: }
                   6654: 
1.366     albertel 6655: sub rndseed_CODE_64bit {
                   6656:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6657:     {
1.366     albertel 6658: 	use integer;
1.443     albertel 6659: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6660: 	my $symbseed=numval2($symb);
1.491     albertel 6661: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6662: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6663: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6664: 	my $num1=$symbseed+$CODEchck;
                   6665: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6666: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 6667: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 6668: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6669: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6670: 	return "$num1:$num2";
1.366     albertel 6671:     }
                   6672: }
                   6673: 
1.575     albertel 6674: sub rndseed_CODE_64bit4 {
                   6675:     my ($symb,$courseid,$domain,$username)=@_;
                   6676:     {
                   6677: 	use integer;
                   6678: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6679: 	my $symbseed=numval3($symb);
                   6680: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6681: 	my $CODEseed=numval3(&getCODE());
                   6682: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6683: 	my $num1=$symbseed+$CODEchck;
                   6684: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   6685: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6686: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   6687: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6688: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6689: 	return "$num1:$num2";
                   6690:     }
                   6691: }
                   6692: 
1.675     albertel 6693: sub rndseed_CODE_64bit5 {
                   6694:     my ($symb,$courseid,$domain,$username)=@_;
                   6695:     my $code = &getCODE();
                   6696:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6697:     return "$num1:$num2";
                   6698: }
                   6699: 
1.366     albertel 6700: sub setup_random_from_rndseed {
                   6701:     my ($rndseed)=@_;
1.503     albertel 6702:     if ($rndseed =~/([,:])/) {
                   6703: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6704: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6705:     } else {
                   6706: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6707:     }
1.36      albertel 6708: }
                   6709: 
1.474     albertel 6710: sub latest_receipt_algorithm_id {
                   6711:     return 'receipt2';
                   6712: }
                   6713: 
1.480     www      6714: sub recunique {
                   6715:     my $fucourseid=shift;
                   6716:     my $unique;
1.620     albertel 6717:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6718: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6719:     } else {
                   6720: 	$unique=$perlvar{'lonReceipt'};
                   6721:     }
                   6722:     return unpack("%32C*",$unique);
                   6723: }
                   6724: 
                   6725: sub recprefix {
                   6726:     my $fucourseid=shift;
                   6727:     my $prefix;
1.620     albertel 6728:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6729: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6730:     } else {
                   6731: 	$prefix=$perlvar{'lonHostID'};
                   6732:     }
                   6733:     return unpack("%32C*",$prefix);
                   6734: }
                   6735: 
1.76      www      6736: sub ireceipt {
1.474     albertel 6737:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6738:     my $cuname=unpack("%32C*",$funame);
                   6739:     my $cudom=unpack("%32C*",$fudom);
                   6740:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6741:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6742:     my $cunique=&recunique($fucourseid);
1.474     albertel 6743:     my $cpart=unpack("%32S*",$part);
1.480     www      6744:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6745:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6746: 	$env{'request.state'} eq 'construct') {
1.474     albertel 6747: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   6748: 			       " and ".($cpart%$cudom));
                   6749: 			       
                   6750: 	$return.= ($cunique%$cuname+
                   6751: 		   $cunique%$cudom+
                   6752: 		   $cusymb%$cuname+
                   6753: 		   $cusymb%$cudom+
                   6754: 		   $cucourseid%$cuname+
                   6755: 		   $cucourseid%$cudom+
                   6756: 		   $cpart%$cuname+
                   6757: 		   $cpart%$cudom);
                   6758:     } else {
                   6759: 	$return.= ($cunique%$cuname+
                   6760: 		   $cunique%$cudom+
                   6761: 		   $cusymb%$cuname+
                   6762: 		   $cusymb%$cudom+
                   6763: 		   $cucourseid%$cuname+
                   6764: 		   $cucourseid%$cudom);
                   6765:     }
                   6766:     return $return;
1.76      www      6767: }
                   6768: 
                   6769: sub receipt {
1.474     albertel 6770:     my ($part)=@_;
                   6771:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   6772:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6773: }
1.260     ng       6774: 
1.36      albertel 6775: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6776: # returns either the contents of the file or 
                   6777: # -1 if the file doesn't exist
1.481     raeburn  6778: #
                   6779: # if the target is a file that was uploaded via DOCS, 
                   6780: # a check will be made to see if a current copy exists on the local server,
                   6781: # if it does this will be served, otherwise a copy will be retrieved from
                   6782: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6783: # the local server.   
1.472     albertel 6784: 
1.36      albertel 6785: sub getfile {
1.538     albertel 6786:     my ($file) = @_;
1.609     banghart 6787:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6788:     &repcopy($file);
                   6789:     return &readfile($file);
                   6790: }
                   6791: 
                   6792: sub repcopy_userfile {
                   6793:     my ($file)=@_;
1.609     banghart 6794:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6795:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6796:     my ($cdom,$cnum,$filename) = 
                   6797: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6798:     my ($info,$rtncode);
                   6799:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6800:     if (-e "$file") {
                   6801: 	my @fileinfo = stat($file);
                   6802: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6803: 	if ($lwpresp ne 'ok') {
                   6804: 	    if ($rtncode eq '404') {
1.538     albertel 6805: 		unlink($file);
1.482     albertel 6806: 	    }
1.517     albertel 6807: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6808: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6809: 	    #my $response=$ua->request($request);
                   6810: 	    #if ($response->is_success()) {
                   6811: 	#	return $response->content;
                   6812: 	#    } else {
                   6813: 	#	return -1;
                   6814: 	#    }
1.482     albertel 6815: 	    return -1;
                   6816: 	}
                   6817: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6818: 	    return 'ok';
1.482     albertel 6819: 	}
                   6820: 	$info = '';
1.538     albertel 6821: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6822: 	if ($lwpresp ne 'ok') {
                   6823: 	    return -1;
                   6824: 	}
                   6825:     } else {
1.538     albertel 6826: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6827: 	if ($lwpresp ne 'ok') {
1.517     albertel 6828: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6829: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6830: 	    my $response=$ua->request($request);
                   6831: 	    if ($response->is_success()) {
1.538     albertel 6832: 		$info=$response->content;
1.517     albertel 6833: 	    } else {
                   6834: 		return -1;
                   6835: 	    }
1.482     albertel 6836: 	}
                   6837: 	my @parts = ($cdom,$cnum); 
                   6838: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6839: 	    push @parts, split(/\//,$1);
1.518     albertel 6840: 	}
1.538     albertel 6841: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6842: 	foreach my $part (@parts) {
                   6843: 	    $path .= '/'.$part;
                   6844: 	    if (!-e $path) {
                   6845: 		mkdir($path,0770);
                   6846: 	    }
                   6847: 	}
                   6848:     }
1.538     albertel 6849:     open(FILE,">$file");
1.482     albertel 6850:     print FILE $info;
                   6851:     close(FILE);
1.607     raeburn  6852:     return 'ok';
1.481     raeburn  6853: }
                   6854: 
1.517     albertel 6855: sub tokenwrapper {
                   6856:     my $uri=shift;
1.552     albertel 6857:     $uri=~s|^http\://([^/]+)||;
                   6858:     $uri=~s|^/||;
1.620     albertel 6859:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6860:     my $token=$1;
1.552     albertel 6861:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6862:     if ($udom && $uname && $file) {
                   6863: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6864:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6865:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6866:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6867:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6868:     } else {
                   6869:         return '/adm/notfound.html';
                   6870:     }
                   6871: }
                   6872: 
1.481     raeburn  6873: sub getuploaded {
                   6874:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6875:     $uri=~s/^\///;
                   6876:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6877:     my $ua=new LWP::UserAgent;
                   6878:     my $request=new HTTP::Request($reqtype,$uri);
                   6879:     my $response=$ua->request($request);
                   6880:     $$rtncode = $response->code;
1.482     albertel 6881:     if (! $response->is_success()) {
                   6882: 	return 'failed';
                   6883:     }      
                   6884:     if ($reqtype eq 'HEAD') {
1.486     www      6885: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6886:     } elsif ($reqtype eq 'GET') {
                   6887: 	$$info = $response->content;
1.472     albertel 6888:     }
1.482     albertel 6889:     return 'ok';
1.36      albertel 6890: }
                   6891: 
1.481     raeburn  6892: sub readfile {
                   6893:     my $file = shift;
                   6894:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6895:     my $fh;
                   6896:     open($fh,"<$file");
                   6897:     my $a='';
                   6898:     while (<$fh>) { $a .=$_; }
                   6899:     return $a;
                   6900: }
                   6901: 
1.36      albertel 6902: sub filelocation {
1.590     banghart 6903:     my ($dir,$file) = @_;
                   6904:     my $location;
                   6905:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 6906: 
                   6907:     if ($file =~ m-^/adm/-) {
                   6908: 	$file=~s-^/adm/wrapper/-/-;
                   6909: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   6910:     }
1.590     banghart 6911:     if ($file=~m:^/~:) { # is a contruction space reference
                   6912:         $location = $file;
                   6913:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 6914:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   6915: 	# is a correct contruction space reference
                   6916:         $location = $file;
1.609     banghart 6917:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 6918:         my ($udom,$uname,$filename)=
1.609     banghart 6919:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 6920:         my $home=&homeserver($uname,$udom);
                   6921:         my $is_me=0;
                   6922:         my @ids=&current_machine_ids();
                   6923:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   6924:         if ($is_me) {
1.740     www      6925:   	    $location=&propath($udom,$uname).
1.590     banghart 6926:   	      '/userfiles/'.$filename;
                   6927:         } else {
                   6928:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   6929:   	      $udom.'/'.$uname.'/'.$filename;
                   6930:         }
                   6931:     } else {
                   6932:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   6933:         $file=~s:^/res/:/:;
                   6934:         if ( !( $file =~ m:^/:) ) {
                   6935:             $location = $dir. '/'.$file;
                   6936:         } else {
                   6937:             $location = '/home/httpd/html/res'.$file;
                   6938:         }
1.59      albertel 6939:     }
1.590     banghart 6940:     $location=~s://+:/:g; # remove duplicate /
                   6941:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   6942:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   6943:     return $location;
1.46      www      6944: }
1.36      albertel 6945: 
1.46      www      6946: sub hreflocation {
                   6947:     my ($dir,$file)=@_;
1.460     albertel 6948:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 6949: 	$file=filelocation($dir,$file);
1.700     albertel 6950:     } elsif ($file=~m-^/adm/-) {
                   6951: 	$file=~s-^/adm/wrapper/-/-;
                   6952: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 6953:     }
                   6954:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   6955: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   6956:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 6957: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 6958:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   6959: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   6960: 	    -/uploaded/$1/$2/-x;
1.46      www      6961:     }
1.462     albertel 6962:     return $file;
1.465     albertel 6963: }
                   6964: 
                   6965: sub current_machine_domains {
                   6966:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6967:     my @domains;
                   6968:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6969: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6970: 	if ($hostname eq $name) {
                   6971: 	    push(@domains,$hostdom{$id});
                   6972: 	}
                   6973:     }
                   6974:     return @domains;
                   6975: }
                   6976: 
                   6977: sub current_machine_ids {
                   6978:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   6979:     my @ids;
                   6980:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  6981: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 6982: 	if ($hostname eq $name) {
                   6983: 	    push(@ids,$id);
                   6984: 	}
                   6985:     }
                   6986:     return @ids;
1.31      www      6987: }
                   6988: 
                   6989: # ------------------------------------------------------------- Declutters URLs
                   6990: 
                   6991: sub declutter {
                   6992:     my $thisfn=shift;
1.569     albertel 6993:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 6994:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      6995:     $thisfn=~s/^\///;
1.697     albertel 6996:     $thisfn=~s|^adm/wrapper/||;
                   6997:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      6998:     $thisfn=~s/^res\///;
1.235     www      6999:     $thisfn=~s/\?.+$//;
1.268     www      7000:     return $thisfn;
                   7001: }
                   7002: 
                   7003: # ------------------------------------------------------------- Clutter up URLs
                   7004: 
                   7005: sub clutter {
                   7006:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7007:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7008:        $thisfn='/res'.$thisfn; 
                   7009:     }
1.694     albertel 7010:     if ($thisfn !~m|/adm|) {
1.695     albertel 7011: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7012: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7013: 	} else {
                   7014: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7015: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7016: 	    if ($embstyle eq 'ssi'
                   7017: 		|| ($embstyle eq 'hdn')
                   7018: 		|| ($embstyle eq 'rat')
                   7019: 		|| ($embstyle eq 'prv')
                   7020: 		|| ($embstyle eq 'ign')) {
                   7021: 		#do nothing with these
                   7022: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7023: 		|| ($embstyle eq 'emb')
                   7024: 		|| ($embstyle eq 'wrp')) {
                   7025: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7026: 	    } elsif ($embstyle eq 'unk'
                   7027: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7028: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7029: 	    } else {
1.718     www      7030: #		&logthis("Got a blank emb style");
1.695     albertel 7031: 	    }
1.694     albertel 7032: 	}
                   7033:     }
1.31      www      7034:     return $thisfn;
1.12      www      7035: }
                   7036: 
1.557     albertel 7037: sub freeze_escape {
                   7038:     my ($value)=@_;
                   7039:     if (ref($value)) {
                   7040: 	$value=&nfreeze($value);
                   7041: 	return '__FROZEN__'.&escape($value);
                   7042:     }
                   7043:     return &escape($value);
                   7044: }
                   7045: 
1.11      www      7046: 
1.557     albertel 7047: sub thaw_unescape {
                   7048:     my ($value)=@_;
                   7049:     if ($value =~ /^__FROZEN__/) {
                   7050: 	substr($value,0,10,undef);
                   7051: 	$value=&unescape($value);
                   7052: 	return &thaw($value);
                   7053:     }
                   7054:     return &unescape($value);
                   7055: }
                   7056: 
1.436     albertel 7057: sub correct_line_ends {
                   7058:     my ($result)=@_;
                   7059:     $$result =~s/\r\n/\n/mg;
                   7060:     $$result =~s/\r/\n/mg;
1.415     albertel 7061: }
1.1       albertel 7062: # ================================================================ Main Program
                   7063: 
1.184     www      7064: sub goodbye {
1.204     albertel 7065:    &logthis("Starting Shut down");
1.443     albertel 7066: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7067:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7068: #converted
1.599     albertel 7069: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7070:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7071: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7072: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7073: #1.1 only
1.599     albertel 7074: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7075: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7076: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7077: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7078:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7079:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7080:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7081:    &flushcourselogs();
                   7082:    &logthis("Shutting down");
                   7083: }
                   7084: 
1.179     www      7085: BEGIN {
1.228     harris41 7086: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7087:     unless ($readit) {
1.217     harris41 7088: {
1.781     raeburn  7089:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7090:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7091: }
1.1       albertel 7092: 
1.327     albertel 7093: # ------------------------------------------------------------ Read domain file
                   7094: {
                   7095:     %domaindescription = ();
                   7096:     %domain_auth_def = ();
                   7097:     %domain_auth_arg_def = ();
1.448     albertel 7098:     my $fh;
                   7099:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 7100:        while (<$fh>) {
1.390     matthew  7101:            next if (/^(\#|\s*$)/);
                   7102: #           next if /^\#/;
1.327     albertel 7103:            chomp;
1.403     www      7104:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  7105: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      7106: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7107:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7108: 	   $domaindescription{$domain}=$domain_description;
                   7109: 	   $domain_lang_def{$domain}=$def_lang;
                   7110: 	   $domain_city{$domain}=$city;
                   7111: 	   $domain_longi{$domain}=$longi;
                   7112: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7113:            $domain_primary{$domain}=$primary;
1.403     www      7114: 
1.448     albertel 7115:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7116: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7117: 	}
1.327     albertel 7118:     }
1.448     albertel 7119:     close ($fh);
1.327     albertel 7120: }
                   7121: 
                   7122: 
1.1       albertel 7123: # ------------------------------------------------------------- Read hosts file
                   7124: {
1.448     albertel 7125:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7126: 
                   7127:     while (my $configline=<$config>) {
1.303     matthew  7128:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7129:        chomp($configline);
1.595     albertel 7130:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7131:        $name=~s/\s//g;
1.595     albertel 7132:        if ($id && $domain && $role && $name) {
1.252     albertel 7133: 	 $hostname{$id}=$name;
                   7134: 	 $hostdom{$id}=$domain;
                   7135: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7136:        }
1.1       albertel 7137:     }
1.448     albertel 7138:     close($config);
1.619     albertel 7139:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7140:     #&get_iphost();
1.1       albertel 7141: }
                   7142: 
1.598     albertel 7143: sub get_iphost {
                   7144:     if (%iphost) { return %iphost; }
1.653     albertel 7145:     my %name_to_ip;
1.598     albertel 7146:     foreach my $id (keys(%hostname)) {
                   7147: 	my $name=$hostname{$id};
1.653     albertel 7148: 	my $ip;
                   7149: 	if (!exists($name_to_ip{$name})) {
                   7150: 	    $ip = gethostbyname($name);
                   7151: 	    if (!$ip || length($ip) ne 4) {
                   7152: 		&logthis("Skipping host $id name $name no IP found\n");
                   7153: 		next;
                   7154: 	    }
                   7155: 	    $ip=inet_ntoa($ip);
                   7156: 	    $name_to_ip{$name} = $ip;
                   7157: 	} else {
                   7158: 	    $ip = $name_to_ip{$name};
1.598     albertel 7159: 	}
                   7160: 	push(@{$iphost{$ip}},$id);
                   7161:     }
                   7162:     return %iphost;
                   7163: }
                   7164: 
1.1       albertel 7165: # ------------------------------------------------------ Read spare server file
                   7166: {
1.448     albertel 7167:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7168: 
                   7169:     while (my $configline=<$config>) {
                   7170:        chomp($configline);
1.284     matthew  7171:        if ($configline) {
1.1       albertel 7172:           $spareid{$configline}=1;
                   7173:        }
                   7174:     }
1.448     albertel 7175:     close($config);
1.1       albertel 7176: }
1.11      www      7177: # ------------------------------------------------------------ Read permissions
                   7178: {
1.448     albertel 7179:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7180: 
                   7181:     while (my $configline=<$config>) {
1.448     albertel 7182: 	chomp($configline);
                   7183: 	if ($configline) {
                   7184: 	    my ($role,$perm)=split(/ /,$configline);
                   7185: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7186: 	}
1.11      www      7187:     }
1.448     albertel 7188:     close($config);
1.11      www      7189: }
                   7190: 
                   7191: # -------------------------------------------- Read plain texts for permissions
                   7192: {
1.448     albertel 7193:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7194: 
                   7195:     while (my $configline=<$config>) {
1.448     albertel 7196: 	chomp($configline);
                   7197: 	if ($configline) {
1.742     raeburn  7198: 	    my ($short,@plain)=split(/:/,$configline);
                   7199:             %{$prp{$short}} = ();
                   7200: 	    if (@plain > 0) {
                   7201:                 $prp{$short}{'std'} = $plain[0];
                   7202:                 for (my $i=1; $i<@plain; $i++) {
                   7203:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7204:                 }
                   7205:             }
1.448     albertel 7206: 	}
1.135     www      7207:     }
1.448     albertel 7208:     close($config);
1.135     www      7209: }
                   7210: 
                   7211: # ---------------------------------------------------------- Read package table
                   7212: {
1.448     albertel 7213:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7214: 
                   7215:     while (my $configline=<$config>) {
1.483     albertel 7216: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7217: 	chomp($configline);
                   7218: 	my ($short,$plain)=split(/:/,$configline);
                   7219: 	my ($pack,$name)=split(/\&/,$short);
                   7220: 	if ($plain ne '') {
                   7221: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7222: 	    $packagetab{$short}=$plain; 
                   7223: 	}
1.11      www      7224:     }
1.448     albertel 7225:     close($config);
1.329     matthew  7226: }
                   7227: 
                   7228: # ------------- set up temporary directory
                   7229: {
                   7230:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7231: 
1.11      www      7232: }
                   7233: 
1.599     albertel 7234: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      7235: 
1.281     www      7236: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7237: $dumpcount=0;
1.22      www      7238: 
1.163     harris41 7239: &logtouch();
1.672     albertel 7240: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7241: $readit=1;
1.564     albertel 7242:     {
                   7243: 	use integer;
                   7244: 	my $test=(2**32)+1;
1.568     albertel 7245: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7246: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7247:     }
1.195     www      7248: }
1.1       albertel 7249: }
1.179     www      7250: 
1.1       albertel 7251: 1;
1.191     harris41 7252: __END__
                   7253: 
1.243     albertel 7254: =pod
                   7255: 
1.191     harris41 7256: =head1 NAME
                   7257: 
1.243     albertel 7258: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7259: 
                   7260: =head1 SYNOPSIS
                   7261: 
1.243     albertel 7262: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7263: 
                   7264:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7265: 
1.243     albertel 7266: Common parameters:
                   7267: 
                   7268: =over 4
                   7269: 
                   7270: =item *
                   7271: 
                   7272: $uname : an internal username (if $cname expecting a course Id specifically)
                   7273: 
                   7274: =item *
                   7275: 
                   7276: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7277: 
                   7278: =item *
                   7279: 
                   7280: $symb : a resource instance identifier
                   7281: 
                   7282: =item *
                   7283: 
                   7284: $namespace : the name of a .db file that contains the data needed or
                   7285: being set.
                   7286: 
                   7287: =back
                   7288: 
1.394     bowersj2 7289: =head1 OVERVIEW
1.191     harris41 7290: 
1.394     bowersj2 7291: lonnet provides subroutines which interact with the
                   7292: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7293: about classes, users, and resources.
1.243     albertel 7294: 
                   7295: For many of these objects you can also use this to store data about
                   7296: them or modify them in various ways.
1.191     harris41 7297: 
1.394     bowersj2 7298: =head2 Symbs
1.191     harris41 7299: 
1.394     bowersj2 7300: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7301: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7302: map, the resource number of the resource in the map, and the URL of
                   7303: the resource itself. The latter is somewhat redundant, but might help
                   7304: if maps change.
                   7305: 
                   7306: An example is
                   7307: 
                   7308:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7309: 
                   7310: The respective map entry is
                   7311: 
                   7312:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7313:   title="Problem 2">
                   7314:  </resource>
                   7315: 
                   7316: Symbs are used by the random number generator, as well as to store and
                   7317: restore data specific to a certain instance of for example a problem.
                   7318: 
                   7319: =head2 Storing And Retrieving Data
                   7320: 
                   7321: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7322: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7323: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7324: is is the non-critical message twin of cstore. These functions are for
                   7325: handlers to store a perl hash to a user's permanent data space in an
                   7326: easy manner, and to retrieve it again on another call. It is expected
                   7327: that a handler would use this once at the beginning to retrieve data,
                   7328: and then again once at the end to send only the new data back.
                   7329: 
                   7330: The data is stored in the user's data directory on the user's
                   7331: homeserver under the ID of the course.
                   7332: 
                   7333: The hash that is returned by restore will have all of the previous
                   7334: value for all of the elements of the hash.
                   7335: 
                   7336: Example:
                   7337: 
                   7338:  #creating a hash
                   7339:  my %hash;
                   7340:  $hash{'foo'}='bar';
                   7341: 
                   7342:  #storing it
                   7343:  &Apache::lonnet::cstore(\%hash);
                   7344: 
                   7345:  #changing a value
                   7346:  $hash{'foo'}='notbar';
                   7347: 
                   7348:  #adding a new value
                   7349:  $hash{'bar'}='foo';
                   7350:  &Apache::lonnet::cstore(\%hash);
                   7351: 
                   7352:  #retrieving the hash
                   7353:  my %history=&Apache::lonnet::restore();
                   7354: 
                   7355:  #print the hash
                   7356:  foreach my $key (sort(keys(%history))) {
                   7357:    print("\%history{$key} = $history{$key}");
                   7358:  }
                   7359: 
                   7360: Will print out:
1.191     harris41 7361: 
1.394     bowersj2 7362:  %history{1:foo} = bar
                   7363:  %history{1:keys} = foo:timestamp
                   7364:  %history{1:timestamp} = 990455579
                   7365:  %history{2:bar} = foo
                   7366:  %history{2:foo} = notbar
                   7367:  %history{2:keys} = foo:bar:timestamp
                   7368:  %history{2:timestamp} = 990455580
                   7369:  %history{bar} = foo
                   7370:  %history{foo} = notbar
                   7371:  %history{timestamp} = 990455580
                   7372:  %history{version} = 2
                   7373: 
                   7374: Note that the special hash entries C<keys>, C<version> and
                   7375: C<timestamp> were added to the hash. C<version> will be equal to the
                   7376: total number of versions of the data that have been stored. The
                   7377: C<timestamp> attribute will be the UNIX time the hash was
                   7378: stored. C<keys> is available in every historical section to list which
                   7379: keys were added or changed at a specific historical revision of a
                   7380: hash.
                   7381: 
                   7382: B<Warning>: do not store the hash that restore returns directly. This
                   7383: will cause a mess since it will restore the historical keys as if the
                   7384: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7385: 
1.394     bowersj2 7386: Calling convention:
1.191     harris41 7387: 
1.394     bowersj2 7388:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7389:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7390: 
1.394     bowersj2 7391: For more detailed information, see lonnet specific documentation.
1.191     harris41 7392: 
1.394     bowersj2 7393: =head1 RETURN MESSAGES
1.191     harris41 7394: 
1.394     bowersj2 7395: =over 4
1.191     harris41 7396: 
1.394     bowersj2 7397: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7398: 
1.394     bowersj2 7399: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7400: when the connection is brought back up
1.191     harris41 7401: 
1.394     bowersj2 7402: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7403: for later delivery
1.191     harris41 7404: 
1.394     bowersj2 7405: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7406: 
1.394     bowersj2 7407: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7408: that was requested
1.191     harris41 7409: 
1.243     albertel 7410: =back
1.191     harris41 7411: 
1.243     albertel 7412: =head1 PUBLIC SUBROUTINES
1.191     harris41 7413: 
1.243     albertel 7414: =head2 Session Environment Functions
1.191     harris41 7415: 
1.243     albertel 7416: =over 4
1.191     harris41 7417: 
1.394     bowersj2 7418: =item * 
                   7419: X<appenv()>
                   7420: B<appenv(%hash)>: the value of %hash is written to
                   7421: the user envirnoment file, and will be restored for each access this
1.620     albertel 7422: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7423: process
1.191     harris41 7424: 
                   7425: =item *
1.394     bowersj2 7426: X<delenv()>
                   7427: B<delenv($regexp)>: removes all items from the session
                   7428: environment file that matches the regular expression in $regexp. The
1.620     albertel 7429: values are also delted from the current processes %env.
1.191     harris41 7430: 
1.243     albertel 7431: =back
                   7432: 
                   7433: =head2 User Information
1.191     harris41 7434: 
1.243     albertel 7435: =over 4
1.191     harris41 7436: 
                   7437: =item *
1.394     bowersj2 7438: X<queryauthenticate()>
                   7439: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7440: authentication scheme
                   7441: 
                   7442: =item *
1.394     bowersj2 7443: X<authenticate()>
                   7444: B<authenticate($uname,$upass,$udom)>: try to
                   7445: authenticate user from domain's lib servers (first use the current
                   7446: one). C<$upass> should be the users password.
1.191     harris41 7447: 
                   7448: =item *
1.394     bowersj2 7449: X<homeserver()>
                   7450: B<homeserver($uname,$udom)>: find the server which has
                   7451: the user's directory and files (there must be only one), this caches
                   7452: the answer, and also caches if there is a borken connection.
1.191     harris41 7453: 
                   7454: =item *
1.394     bowersj2 7455: X<idget()>
                   7456: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7457: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7458: username, and only 1 username per ID in a specific domain) (returns
                   7459: hash: id=>name,id=>name)
1.191     harris41 7460: 
                   7461: =item *
1.394     bowersj2 7462: X<idrget()>
                   7463: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7464: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7465: 
                   7466: =item *
1.394     bowersj2 7467: X<idput()>
                   7468: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7469: 
                   7470: =item *
1.394     bowersj2 7471: X<rolesinit()>
                   7472: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7473: 
                   7474: =item *
1.551     albertel 7475: X<getsection()>
                   7476: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7477: course $cname, return section name/number or '' for "not in course"
                   7478: and '-1' for "no section"
                   7479: 
                   7480: =item *
1.394     bowersj2 7481: X<userenvironment()>
                   7482: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7483: passed in @what from the requested user's environment, returns a hash
                   7484: 
                   7485: =back
                   7486: 
                   7487: =head2 User Roles
                   7488: 
                   7489: =over 4
                   7490: 
                   7491: =item *
                   7492: 
                   7493: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7494: actions
                   7495:  F: full access
                   7496:  U,I,K: authentication modes (cxx only)
                   7497:  '': forbidden
                   7498:  1: user needs to choose course
                   7499:  2: browse allowed
1.766     albertel 7500:  A: passphrase authentication needed
1.243     albertel 7501: 
                   7502: =item *
                   7503: 
                   7504: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7505: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7506: and course level
                   7507: 
                   7508: =item *
                   7509: 
                   7510: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7511: explanation of a user role term
                   7512: 
                   7513: =back
                   7514: 
                   7515: =head2 User Modification
                   7516: 
                   7517: =over 4
                   7518: 
                   7519: =item *
                   7520: 
                   7521: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7522: user for the level given by URL.  Optional start and end dates (leave empty
                   7523: string or zero for "no date")
1.191     harris41 7524: 
                   7525: =item *
                   7526: 
1.243     albertel 7527: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7528: change a users, password, possible return values are: ok,
                   7529: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7530: refused
1.191     harris41 7531: 
                   7532: =item *
                   7533: 
1.243     albertel 7534: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7535: 
                   7536: =item *
                   7537: 
1.243     albertel 7538: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7539: modify user
1.191     harris41 7540: 
                   7541: =item *
                   7542: 
1.286     matthew  7543: modifystudent
                   7544: 
                   7545: modify a students enrollment and identification information.
                   7546: The course id is resolved based on the current users environment.  
                   7547: This means the envoking user must be a course coordinator or otherwise
                   7548: associated with a course.
                   7549: 
1.297     matthew  7550: This call is essentially a wrapper for lonnet::modifyuser and
                   7551: lonnet::modify_student_enrollment
1.286     matthew  7552: 
                   7553: Inputs: 
                   7554: 
                   7555: =over 4
                   7556: 
                   7557: =item B<$udom> Students loncapa domain
                   7558: 
                   7559: =item B<$uname> Students loncapa login name
                   7560: 
                   7561: =item B<$uid> Students id/student number
                   7562: 
                   7563: =item B<$umode> Students authentication mode
                   7564: 
                   7565: =item B<$upass> Students password
                   7566: 
                   7567: =item B<$first> Students first name
                   7568: 
                   7569: =item B<$middle> Students middle name
                   7570: 
                   7571: =item B<$last> Students last name
                   7572: 
                   7573: =item B<$gene> Students generation
                   7574: 
                   7575: =item B<$usec> Students section in course
                   7576: 
                   7577: =item B<$end> Unix time of the roles expiration
                   7578: 
                   7579: =item B<$start> Unix time of the roles start date
                   7580: 
                   7581: =item B<$forceid> If defined, allow $uid to be changed
                   7582: 
                   7583: =item B<$desiredhome> server to use as home server for student
                   7584: 
                   7585: =back
1.297     matthew  7586: 
                   7587: =item *
                   7588: 
                   7589: modify_student_enrollment
                   7590: 
                   7591: Change a students enrollment status in a class.  The environment variable
                   7592: 'role.request.course' must be defined for this function to proceed.
                   7593: 
                   7594: Inputs:
                   7595: 
                   7596: =over 4
                   7597: 
                   7598: =item $udom, students domain
                   7599: 
                   7600: =item $uname, students name
                   7601: 
                   7602: =item $uid, students user id
                   7603: 
                   7604: =item $first, students first name
                   7605: 
                   7606: =item $middle
                   7607: 
                   7608: =item $last
                   7609: 
                   7610: =item $gene
                   7611: 
                   7612: =item $usec
                   7613: 
                   7614: =item $end
                   7615: 
                   7616: =item $start
                   7617: 
                   7618: =back
                   7619: 
1.191     harris41 7620: 
                   7621: =item *
                   7622: 
1.243     albertel 7623: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7624: custom role; give a custom role to a user for the level given by URL.  Specify
                   7625: name and domain of role author, and role name
1.191     harris41 7626: 
                   7627: =item *
                   7628: 
1.243     albertel 7629: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7630: 
                   7631: =item *
                   7632: 
1.243     albertel 7633: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7634: 
                   7635: =back
                   7636: 
                   7637: =head2 Course Infomation
                   7638: 
                   7639: =over 4
1.191     harris41 7640: 
                   7641: =item *
                   7642: 
1.631     albertel 7643: coursedescription($courseid) : returns a hash of information about the
                   7644: specified course id, including all environment settings for the
                   7645: course, the description of the course will be in the hash under the
                   7646: key 'description'
1.191     harris41 7647: 
                   7648: =item *
                   7649: 
1.624     albertel 7650: resdata($name,$domain,$type,@which) : request for current parameter
                   7651: setting for a specific $type, where $type is either 'course' or 'user',
                   7652: @what should be a list of parameters to ask about. This routine caches
                   7653: answers for 5 minutes.
1.243     albertel 7654: 
                   7655: =back
                   7656: 
                   7657: =head2 Course Modification
                   7658: 
                   7659: =over 4
1.191     harris41 7660: 
                   7661: =item *
                   7662: 
1.243     albertel 7663: writecoursepref($courseid,%prefs) : write preferences (environment
                   7664: database) for a course
1.191     harris41 7665: 
                   7666: =item *
                   7667: 
1.243     albertel 7668: createcourse($udom,$description,$url) : make/modify course
                   7669: 
                   7670: =back
                   7671: 
                   7672: =head2 Resource Subroutines
                   7673: 
                   7674: =over 4
1.191     harris41 7675: 
                   7676: =item *
                   7677: 
1.243     albertel 7678: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7679: 
                   7680: =item *
                   7681: 
1.243     albertel 7682: repcopy($filename) : subscribes to the requested file, and attempts to
                   7683: replicate from the owning library server, Might return
1.607     raeburn  7684: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7685: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7686: resource. Expects the local filesystem pathname
                   7687: (/home/httpd/html/res/....)
                   7688: 
                   7689: =back
                   7690: 
                   7691: =head2 Resource Information
                   7692: 
                   7693: =over 4
1.191     harris41 7694: 
                   7695: =item *
                   7696: 
1.243     albertel 7697: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7698: a vairety of different possible values, $varname should be a request
                   7699: string, and the other parameters can be used to specify who and what
                   7700: one is asking about.
                   7701: 
                   7702: Possible values for $varname are environment.lastname (or other item
                   7703: from the envirnment hash), user.name (or someother aspect about the
                   7704: user), resource.0.maxtries (or some other part and parameter of a
                   7705: resource)
1.204     albertel 7706: 
                   7707: =item *
                   7708: 
1.243     albertel 7709: directcondval($number) : get current value of a condition; reads from a state
                   7710: string
1.204     albertel 7711: 
                   7712: =item *
                   7713: 
1.243     albertel 7714: condval($condidx) : value of condition index based on state
1.204     albertel 7715: 
                   7716: =item *
                   7717: 
1.243     albertel 7718: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7719: resource's metadata, $what should be either a specific key, or either
                   7720: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7721: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7722: 
                   7723: this function automatically caches all requests
1.191     harris41 7724: 
                   7725: =item *
                   7726: 
1.243     albertel 7727: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7728: network of library servers; returns file handle of where SQL and regex results
                   7729: will be stored for query
1.191     harris41 7730: 
                   7731: =item *
                   7732: 
1.243     albertel 7733: symbread($filename) : return symbolic list entry (filename argument optional);
                   7734: returns the data handle
1.191     harris41 7735: 
                   7736: =item *
                   7737: 
1.243     albertel 7738: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7739: a possible symb for the URL in $thisfn, and if is an encryypted
                   7740: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7741: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7742: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7743: 
1.191     harris41 7744: 
                   7745: =item *
                   7746: 
1.243     albertel 7747: symbclean($symb) : removes versions numbers from a symb, returns the
                   7748: cleaned symb
1.191     harris41 7749: 
                   7750: =item *
                   7751: 
1.243     albertel 7752: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7753: course map, user must be in a course for it to work.
1.191     harris41 7754: 
                   7755: =item *
                   7756: 
1.243     albertel 7757: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7758: 
                   7759: =item *
                   7760: 
1.243     albertel 7761: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7762: a random seed, all arguments are optional, if they aren't sent it uses the
                   7763: environment to derive them. Note: if symb isn't sent and it can't get one
                   7764: from &symbread it will use the current time as its return value
1.191     harris41 7765: 
                   7766: =item *
                   7767: 
1.243     albertel 7768: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7769: unfakeable, receipt
1.191     harris41 7770: 
                   7771: =item *
                   7772: 
1.620     albertel 7773: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7774: 
                   7775: =item *
                   7776: 
1.243     albertel 7777: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7778: 
                   7779: =item *
                   7780: 
1.243     albertel 7781: 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 7782: 
                   7783: =item *
                   7784: 
1.243     albertel 7785: 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 7786: 
                   7787: =item *
                   7788: 
1.243     albertel 7789: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7790: 
                   7791: =item *
                   7792: 
1.243     albertel 7793: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7794: forcing spreadsheet to reevaluate the resource scores next time.
                   7795: 
                   7796: =back
                   7797: 
                   7798: =head2 Storing/Retreiving Data
                   7799: 
                   7800: =over 4
1.191     harris41 7801: 
                   7802: =item *
                   7803: 
1.243     albertel 7804: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7805: for this url; hashref needs to be given and should be a \%hashname; the
                   7806: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7807: be derived from the env
1.191     harris41 7808: 
                   7809: =item *
                   7810: 
1.243     albertel 7811: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7812: uses critical subroutine
1.191     harris41 7813: 
                   7814: =item *
                   7815: 
1.243     albertel 7816: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7817: all args are optional
1.191     harris41 7818: 
                   7819: =item *
                   7820: 
1.717     albertel 7821: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7822: dumps the complete (or key matching regexp) namespace into a hash
                   7823: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7824: normally &store()ed into
                   7825: 
                   7826: $range should be either an integer '100' (give me the first 100
                   7827:                                            matching records)
                   7828:               or be  two integers sperated by a - with no spaces
                   7829:                  '30-50' (give me the 30th through the 50th matching
                   7830:                           records)
                   7831: 
                   7832: 
                   7833: =item *
                   7834: 
                   7835: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7836: replaces a &store() version of data with a replacement set of data
                   7837: for a particular resource in a namespace passed in the $storehash hash 
                   7838: reference
                   7839: 
                   7840: =item *
                   7841: 
1.243     albertel 7842: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7843: works very similar to store/cstore, but all data is stored in a
                   7844: temporary location and can be reset using tmpreset, $storehash should
                   7845: be a hash reference, returns nothing on success
1.191     harris41 7846: 
                   7847: =item *
                   7848: 
1.243     albertel 7849: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7850: similar to restore, but all data is stored in a temporary location and
                   7851: can be reset using tmpreset. Returns a hash of values on success,
                   7852: error string otherwise.
1.191     harris41 7853: 
                   7854: =item *
                   7855: 
1.243     albertel 7856: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7857: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7858: 
                   7859: =item *
                   7860: 
1.243     albertel 7861: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7862: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7863: 
                   7864: =item *
                   7865: 
1.243     albertel 7866: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7867: namesp ($udom and $uname are optional)
1.191     harris41 7868: 
                   7869: =item *
                   7870: 
1.702     albertel 7871: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7872: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7873: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7874: 
1.702     albertel 7875: $range should be either an integer '100' (give me the first 100
                   7876:                                            matching records)
                   7877:               or be  two integers sperated by a - with no spaces
                   7878:                  '30-50' (give me the 30th through the 50th matching
                   7879:                           records)
1.449     matthew  7880: =item *
                   7881: 
                   7882: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   7883: $store can be a scalar, an array reference, or if the amount to be 
                   7884: incremented is > 1, a hash reference.
                   7885: 
                   7886: ($udom and $uname are optional)
1.191     harris41 7887: 
                   7888: =item *
                   7889: 
1.243     albertel 7890: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   7891: ($udom and $uname are optional)
1.191     harris41 7892: 
                   7893: =item *
                   7894: 
1.243     albertel 7895: cput($namespace,$storehash,$udom,$uname) : critical put
                   7896: ($udom and $uname are optional)
1.191     harris41 7897: 
                   7898: =item *
                   7899: 
1.748     albertel 7900: newput($namespace,$storehash,$udom,$uname) :
                   7901: 
                   7902: Attempts to store the items in the $storehash, but only if they don't
                   7903: currently exist, if this succeeds you can be certain that you have 
                   7904: successfully created a new key value pair in the $namespace db.
                   7905: 
                   7906: 
                   7907: Args:
                   7908:  $namespace: name of database to store values to
                   7909:  $storehash: hashref to store to the db
                   7910:  $udom: (optional) domain of user containing the db
                   7911:  $uname: (optional) name of user caontaining the db
                   7912: 
                   7913: Returns:
                   7914:  'ok' -> succeeded in storing all keys of $storehash
                   7915:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   7916:                         least <key> already existed in the db (other
                   7917:                         requested keys may also already exist)
                   7918:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   7919:  'con_lost' -> unable to contact request server
                   7920:  'refused' -> action was not allowed by remote machine
                   7921: 
                   7922: 
                   7923: =item *
                   7924: 
1.243     albertel 7925: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7926: reference filled in from namesp (encrypts the return communication)
                   7927: ($udom and $uname are optional)
1.191     harris41 7928: 
                   7929: =item *
                   7930: 
1.243     albertel 7931: log($udom,$name,$home,$message) : write to permanent log for user; use
                   7932: critical subroutine
                   7933: 
                   7934: =back
                   7935: 
                   7936: =head2 Network Status Functions
                   7937: 
                   7938: =over 4
1.191     harris41 7939: 
                   7940: =item *
                   7941: 
                   7942: dirlist($uri) : return directory list based on URI
                   7943: 
                   7944: =item *
                   7945: 
1.243     albertel 7946: spareserver() : find server with least workload from spare.tab
                   7947: 
                   7948: =back
                   7949: 
                   7950: =head2 Apache Request
                   7951: 
                   7952: =over 4
1.191     harris41 7953: 
                   7954: =item *
                   7955: 
1.243     albertel 7956: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   7957: localhost, posts hash
                   7958: 
                   7959: =back
                   7960: 
                   7961: =head2 Data to String to Data
                   7962: 
                   7963: =over 4
1.191     harris41 7964: 
                   7965: =item *
                   7966: 
1.243     albertel 7967: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   7968: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 7969: 
                   7970: =item *
                   7971: 
1.243     albertel 7972: hashref2str($hashref) : convert a hashref into a string complete with
                   7973: escaping and '=' and '&' separators, supports elements that are
                   7974: arrayrefs and hashrefs
1.191     harris41 7975: 
                   7976: =item *
                   7977: 
1.243     albertel 7978: arrayref2str($arrayref) : convert an arrayref into a string complete
                   7979: with escaping and '&' separators, supports elements that are arrayrefs
                   7980: and hashrefs
1.191     harris41 7981: 
                   7982: =item *
                   7983: 
1.243     albertel 7984: str2hash($string) : convert string to hash using unescaping and
                   7985: splitting on '=' and '&', supports elements that are arrayrefs and
                   7986: hashrefs
1.191     harris41 7987: 
                   7988: =item *
                   7989: 
1.243     albertel 7990: str2array($string) : convert string to hash using unescaping and
                   7991: splitting on '&', supports elements that are arrayrefs and hashrefs
                   7992: 
                   7993: =back
                   7994: 
                   7995: =head2 Logging Routines
                   7996: 
                   7997: =over 4
                   7998: 
                   7999: These routines allow one to make log messages in the lonnet.log and
                   8000: lonnet.perm logfiles.
1.191     harris41 8001: 
                   8002: =item *
                   8003: 
1.243     albertel 8004: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8005: 
                   8006: =item *
                   8007: 
1.243     albertel 8008: logthis() : append message to the normal lonnet.log file, it gets
                   8009: preiodically rolled over and deleted.
1.191     harris41 8010: 
                   8011: =item *
                   8012: 
1.243     albertel 8013: logperm() : append a permanent message to lonnet.perm.log, this log
                   8014: file never gets deleted by any automated portion of the system, only
                   8015: messages of critical importance should go in here.
                   8016: 
                   8017: =back
                   8018: 
                   8019: =head2 General File Helper Routines
                   8020: 
                   8021: =over 4
1.191     harris41 8022: 
                   8023: =item *
                   8024: 
1.481     raeburn  8025: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8026: (a) files in /uploaded
                   8027:   (i) If a local copy of the file exists - 
                   8028:       compares modification date of local copy with last-modified date for 
                   8029:       definitive version stored on home server for course. If local copy is 
                   8030:       stale, requests a new version from the home server and stores it. 
                   8031:       If the original has been removed from the home server, then local copy 
                   8032:       is unlinked.
                   8033:   (ii) If local copy does not exist -
                   8034:       requests the file from the home server and stores it. 
                   8035:   
                   8036:   If $caller is 'uploadrep':  
                   8037:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8038:     for request for files originally uploaded via DOCS. 
                   8039:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8040:   
                   8041:   Otherwise:
                   8042:      This indicates a call from the content generation phase of the request.
                   8043:      -  returns the entire contents of the file or -1.
                   8044:      
                   8045: (b) files in /res
                   8046:    - returns the entire contents of a file or -1; 
                   8047:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8048: 
1.712     albertel 8049: 
                   8050: =item *
                   8051: 
                   8052: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8053:                   reference
                   8054: 
                   8055: returns either a stat() list of data about the file or an empty list
                   8056: if the file doesn't exist or couldn't find out about it (connection
                   8057: problems or user unknown)
                   8058: 
1.191     harris41 8059: =item *
                   8060: 
1.243     albertel 8061: filelocation($dir,$file) : returns file system location of a file
                   8062: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8063: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8064: and a file of ../bob will become /a/bob)
1.191     harris41 8065: 
                   8066: =item *
                   8067: 
                   8068: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8069: filelocation except for hrefs
                   8070: 
                   8071: =item *
                   8072: 
                   8073: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8074: 
1.243     albertel 8075: =back
                   8076: 
1.608     albertel 8077: =head2 Usererfile file routines (/uploaded*)
                   8078: 
                   8079: =over 4
                   8080: 
                   8081: =item *
                   8082: 
                   8083: userfileupload(): main rotine for putting a file in a user or course's
                   8084:                   filespace, arguments are,
                   8085: 
1.620     albertel 8086:  formname - required - this is the name of the element in $env where the
1.608     albertel 8087:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8088:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8089:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8090:  coursedoc - if true, store the file in the course of the active role
                   8091:              of the current user
                   8092:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8093:          if undefined, it will be placed in "unknown"
                   8094: 
                   8095:  (This routine calls clean_filename() to remove any dangerous
                   8096:  characters from the filename, and then calls finuserfileupload() to
                   8097:  complete the transaction)
                   8098: 
                   8099:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8100:  and /adm/notfound.html if unsuccessful
                   8101: 
                   8102: =item *
                   8103: 
                   8104: clean_filename(): routine for cleaing a filename up for storage in
                   8105:                  userfile space, argument is:
                   8106: 
                   8107:  filename - proposed filename
                   8108: 
                   8109: returns: the new clean filename
                   8110: 
                   8111: =item *
                   8112: 
                   8113: finishuserfileupload(): routine that creaes and sends the file to
                   8114: userspace, probably shouldn't be called directly
                   8115: 
                   8116:   docuname: username or courseid of destination for the file
                   8117:   docudom: domain of user/course of destination for the file
                   8118:   formname: same as for userfileupload()
                   8119:   fname: filename (inculding subdirectories) for the file
                   8120: 
                   8121:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8122:  and /adm/notfound.html if unsuccessful
                   8123: 
                   8124: =item *
                   8125: 
                   8126: renameuserfile(): renames an existing userfile to a new name
                   8127: 
                   8128:   Args:
                   8129:    docuname: username or courseid of destination for the file
                   8130:    docudom: domain of user/course of destination for the file
                   8131:    old: current file name (including any subdirs under userfiles)
                   8132:    new: desired file name (including any subdirs under userfiles)
                   8133: 
                   8134: =item *
                   8135: 
                   8136: mkdiruserfile(): creates a directory is a userfiles dir
                   8137: 
                   8138:   Args:
                   8139:    docuname: username or courseid of destination for the file
                   8140:    docudom: domain of user/course of destination for the file
                   8141:    dir: dir to create (including any subdirs under userfiles)
                   8142: 
                   8143: =item *
                   8144: 
                   8145: removeuserfile(): removes a file that exists in userfiles
                   8146: 
                   8147:   Args:
                   8148:    docuname: username or courseid of destination for the file
                   8149:    docudom: domain of user/course of destination for the file
                   8150:    fname: filname to delete (including any subdirs under userfiles)
                   8151: 
                   8152: =item *
                   8153: 
                   8154: removeuploadedurl(): convience function for removeuserfile()
                   8155: 
                   8156:   Args:
                   8157:    url:  a full /uploaded/... url to delete
                   8158: 
1.747     albertel 8159: =item * 
                   8160: 
                   8161: get_portfile_permissions():
                   8162:   Args:
                   8163:     domain: domain of user or course contain the portfolio files
                   8164:     user: name of user or num of course contain the portfolio files
                   8165:   Returns:
                   8166:     hashref of a dump of the proper file_permissions.db
                   8167:    
                   8168: 
                   8169: =item * 
                   8170: 
                   8171: get_access_controls():
                   8172: 
                   8173: Args:
                   8174:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8175:   group: (optional) the group you want the files associated with
                   8176:   file: (optional) the file you want access info on
                   8177: 
                   8178: Returns:
1.749     raeburn  8179:     a hash (keys are file names) of hashes containing
                   8180:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8181:         values are XML containing access control settings (see below) 
1.747     albertel 8182: 
                   8183: Internal notes:
                   8184: 
1.749     raeburn  8185:  access controls are stored in file_permissions.db as key=value pairs.
                   8186:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8187:         where scope -> public,guest,course,group,domains or users.
                   8188:               end -> UNIX time for end of access (0 -> no end date)
                   8189:               start -> UNIX time for start of access
                   8190: 
                   8191:     value -> XML description of access control
                   8192:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8193:             <start></start>
                   8194:             <end></end>
                   8195: 
                   8196:             <password></password>  for scope type = guest
                   8197: 
                   8198:             <domain></domain>     for scope type = course or group
                   8199:             <number></number>
                   8200:             <roles id="">
                   8201:              <role></role>
                   8202:              <access></access>
                   8203:              <section></section>
                   8204:              <group></group>
                   8205:             </roles>
                   8206: 
                   8207:             <dom></dom>         for scope type = domains
                   8208: 
                   8209:             <users>             for scope type = users
                   8210:              <user>
                   8211:               <uname></uname>
                   8212:               <udom></udom>
                   8213:              </user>
                   8214:             </users>
                   8215:            </scope> 
                   8216:               
                   8217:  Access data is also aggregated for each file in an additional key=value pair:
                   8218:  key -> path to file/file_name\0accesscontrol 
                   8219:  value -> reference to hash
                   8220:           hash contains key = value pairs
                   8221:           where key = uniqueID:scope_end_start
                   8222:                 value = UNIX time record was last updated
                   8223: 
                   8224:           Used to improve speed of look-ups of access controls for each file.  
                   8225:  
                   8226:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8227: 
                   8228: modify_access_controls():
                   8229: 
                   8230: Modifies access controls for a portfolio file
                   8231: Args
                   8232: 1. file name
                   8233: 2. reference to hash of required changes,
                   8234: 3. domain
                   8235: 4. username
                   8236:   where domain,username are the domain of the portfolio owner 
                   8237:   (either a user or a course) 
                   8238: 
                   8239: Returns:
                   8240: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8241: 2. result of deletions ('ok' or 'error', with error message).
                   8242: 3. reference to hash of any new or updated access controls.
                   8243: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8244:    key = integer (inbound ID)
                   8245:    value = uniqueID  
1.747     albertel 8246: 
1.608     albertel 8247: =back
                   8248: 
1.243     albertel 8249: =head2 HTTP Helper Routines
                   8250: 
                   8251: =over 4
                   8252: 
1.191     harris41 8253: =item *
                   8254: 
                   8255: escape() : unpack non-word characters into CGI-compatible hex codes
                   8256: 
                   8257: =item *
                   8258: 
                   8259: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8260: 
1.243     albertel 8261: =back
                   8262: 
                   8263: =head1 PRIVATE SUBROUTINES
                   8264: 
                   8265: =head2 Underlying communication routines (Shouldn't call)
                   8266: 
                   8267: =over 4
                   8268: 
                   8269: =item *
                   8270: 
                   8271: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8272: 
                   8273: =item *
                   8274: 
                   8275: reply() : uses subreply to send a message to remote machine, logs all failures
                   8276: 
                   8277: =item *
                   8278: 
                   8279: critical() : passes a critical message to another server; if cannot
                   8280: get through then place message in connection buffer directory and
                   8281: returns con_delayed, if incapable of saving message, returns
                   8282: con_failed
                   8283: 
                   8284: =item *
                   8285: 
                   8286: reconlonc() : tries to reconnect lonc client processes.
                   8287: 
                   8288: =back
                   8289: 
                   8290: =head2 Resource Access Logging
                   8291: 
                   8292: =over 4
                   8293: 
                   8294: =item *
                   8295: 
                   8296: flushcourselogs() : flush (save) buffer logs and access logs
                   8297: 
                   8298: =item *
                   8299: 
                   8300: courselog($what) : save message for course in hash
                   8301: 
                   8302: =item *
                   8303: 
                   8304: courseacclog($what) : save message for course using &courselog().  Perform
                   8305: special processing for specific resource types (problems, exams, quizzes, etc).
                   8306: 
1.191     harris41 8307: =item *
                   8308: 
                   8309: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8310: as a PerlChildExitHandler
1.243     albertel 8311: 
                   8312: =back
                   8313: 
                   8314: =head2 Other
                   8315: 
                   8316: =over 4
                   8317: 
                   8318: =item *
                   8319: 
                   8320: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8321: 
                   8322: =back
                   8323: 
                   8324: =cut

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