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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.23! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.22 2013/04/07 17:48:57 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1172.2.18  raeburn    78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
1.1138    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1160    www        99: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   100: use LONCAPA::Lond;
1.1117    foxr      101: 
1.1090    raeburn   102: use File::Copy;
1.676     albertel  103: 
1.195     www       104: my $readit;
1.550     foxr      105: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  106: 
1.619     albertel  107: require Exporter;
                    108: 
                    109: our @ISA = qw (Exporter);
                    110: our @EXPORT = qw(%env);
                    111: 
1.1172.2.9  raeburn   112: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       113: {
                    114:     my $logid;
1.1172.2.9  raeburn   115:     sub write_log {
                    116: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    117:         if ($context eq 'course') {
                    118:             if (($cnum eq '') || ($cdom eq '')) {
                    119:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    120:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    121:             }
1.957     raeburn   122:         }
1.1172.2.13  raeburn   123: 	$logid ++;
1.957     raeburn   124:         my $now = time();
                    125: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   126:         my $logentry = {
                    127:                          $id => {
                    128:                                   'exe_uname' => $env{'user.name'},
                    129:                                   'exe_udom'  => $env{'user.domain'},
                    130:                                   'exe_time'  => $now,
                    131:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    132:                                   'delflag'   => $delflag,
                    133:                                   'logentry'  => $storehash,
                    134:                                   'uname'     => $uname,
                    135:                                   'udom'      => $udom,
                    136:                                 }
                    137:                        };
                    138:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       139:     }
                    140: }
1.1       albertel  141: 
1.163     harris41  142: sub logtouch {
                    143:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  144:     unless (-e "$execdir/logs/lonnet.log") {	
                    145: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  146: 	close $fh;
                    147:     }
                    148:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    149:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    150: }
                    151: 
1.1       albertel  152: sub logthis {
                    153:     my $message=shift;
                    154:     my $execdir=$perlvar{'lonDaemons'};
                    155:     my $now=time;
                    156:     my $local=localtime($now);
1.448     albertel  157:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      158: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    159: 	print $fh $logstring;
1.448     albertel  160: 	close($fh);
                    161:     }
1.1       albertel  162:     return 1;
                    163: }
                    164: 
                    165: sub logperm {
                    166:     my $message=shift;
                    167:     my $execdir=$perlvar{'lonDaemons'};
                    168:     my $now=time;
                    169:     my $local=localtime($now);
1.448     albertel  170:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    171: 	print $fh "$now:$message:$local\n";
                    172: 	close($fh);
                    173:     }
1.1       albertel  174:     return 1;
                    175: }
                    176: 
1.850     albertel  177: sub create_connection {
1.853     albertel  178:     my ($hostname,$lonid) = @_;
1.851     albertel  179:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  180: 				     Type    => SOCK_STREAM,
                    181: 				     Timeout => 10);
                    182:     return 0 if (!$client);
1.890     albertel  183:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  184:     my $result = <$client>;
                    185:     chomp($result);
                    186:     return 1 if ($result eq 'done');
                    187:     return 0;
                    188: }
                    189: 
1.983     raeburn   190: sub get_server_timezone {
                    191:     my ($cnum,$cdom) = @_;
                    192:     my $home=&homeserver($cnum,$cdom);
                    193:     if ($home ne 'no_host') {
                    194:         my $cachetime = 24*3600;
                    195:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    196:         if (defined($cached)) {
                    197:             return $timezone;
                    198:         } else {
                    199:             my $timezone = &reply('servertimezone',$home);
                    200:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    201:         }
                    202:     }
                    203: }
1.850     albertel  204: 
1.1106    raeburn   205: sub get_server_distarch {
                    206:     my ($lonhost,$ignore_cache) = @_;
                    207:     if (defined($lonhost)) {
                    208:         if (!defined(&hostname($lonhost))) {
                    209:             return;
                    210:         }
                    211:         my $cachetime = 12*3600;
                    212:         if (!$ignore_cache) {
                    213:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    214:             if (defined($cached)) {
                    215:                 return $distarch;
                    216:             }
                    217:         }
                    218:         my $rep = &reply('serverdistarch',$lonhost);
                    219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    221:                 $rep eq '') {
                    222:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    223:         }
                    224:     }
                    225:     return;
                    226: }
                    227: 
1.993     raeburn   228: sub get_server_loncaparev {
1.1073    raeburn   229:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   230:     if (defined($lonhost)) {
                    231:         if (!defined(&hostname($lonhost))) {
                    232:             undef($lonhost);
                    233:         }
                    234:     }
                    235:     if (!defined($lonhost)) {
                    236:         if (defined(&domain($dom,'primary'))) {
                    237:             $lonhost=&domain($dom,'primary');
                    238:             if ($lonhost eq 'no_host') {
                    239:                 undef($lonhost);
                    240:             }
                    241:         }
                    242:     }
                    243:     if (defined($lonhost)) {
1.1073    raeburn   244:         my $cachetime = 12*3600;
                    245:         if (!$ignore_cache) {
                    246:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    247:             if (defined($cached)) {
                    248:                 return $loncaparev;
                    249:             }
                    250:         }
                    251:         my ($answer,$loncaparev);
                    252:         my @ids=&current_machine_ids();
                    253:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    254:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   255:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   256:                 $loncaparev = $1;
                    257:             }
                    258:         } else {
                    259:             $answer = &reply('serverloncaparev',$lonhost);
                    260:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    261:                 if ($caller eq 'loncron') {
                    262:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   263:                     $ua->timeout(4);
1.1073    raeburn   264:                     my $protocol = $protocol{$lonhost};
                    265:                     $protocol = 'http' if ($protocol ne 'https');
                    266:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    267:                     my $request=new HTTP::Request('GET',$url);
                    268:                     my $response=$ua->request($request);
                    269:                     unless ($response->is_error()) {
                    270:                         my $content = $response->content;
1.1081    raeburn   271:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   272:                             $loncaparev = $1;
                    273:                         }
                    274:                     }
                    275:                 } else {
                    276:                     $loncaparev = $loncaparevs{$lonhost};
                    277:                 }
1.1081    raeburn   278:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   279:                 $loncaparev = $1;
                    280:             }
1.993     raeburn   281:         }
1.1073    raeburn   282:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   283:     }
                    284: }
                    285: 
1.1074    raeburn   286: sub get_server_homeID {
                    287:     my ($hostname,$ignore_cache,$caller) = @_;
                    288:     unless ($ignore_cache) {
                    289:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    290:         if (defined($cached)) {
                    291:             return $serverhomeID;
                    292:         }
                    293:     }
                    294:     my $cachetime = 12*3600;
                    295:     my $serverhomeID;
                    296:     if ($caller eq 'loncron') { 
                    297:         my @machine_ids = &machine_ids($hostname);
                    298:         foreach my $id (@machine_ids) {
                    299:             my $response = &reply('serverhomeID',$id);
                    300:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    301:                 $serverhomeID = $response;
                    302:                 last;
                    303:             }
                    304:         }
                    305:         if ($serverhomeID eq '') {
                    306:             $serverhomeID = $machine_ids[-1];
                    307:         }
                    308:     } else {
                    309:         $serverhomeID = $serverhomeIDs{$hostname};
                    310:     }
                    311:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    312: }
                    313: 
1.1121    raeburn   314: sub get_remote_globals {
                    315:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   316:     my ($result,%returnhash,%whatneeded);
                    317:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   318:         foreach my $what (sort(keys(%{$whathash}))) {
                    319:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   320:             my ($response,$cached);
1.1121    raeburn   321:             unless ($ignore_cache) {
1.1125    raeburn   322:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   323:             }
                    324:             if (defined($cached)) {
1.1125    raeburn   325:                 $returnhash{$what} = $response;
1.1121    raeburn   326:             } else {
1.1125    raeburn   327:                 $whatneeded{$what} = 1;
1.1121    raeburn   328:             }
                    329:         }
1.1125    raeburn   330:         if (keys(%whatneeded) == 0) {
                    331:             $result = 'ok';
                    332:         } else {
1.1121    raeburn   333:             my $requested = &freeze_escape(\%whatneeded);
                    334:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   335:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    336:                 ($rep eq 'unknown_cmd')) {
                    337:                 $result = $rep;
                    338:             } else {
                    339:                 $result = 'ok';
1.1121    raeburn   340:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   341:                 foreach my $item (@pairs) {
                    342:                     my ($key,$value)=split(/=/,$item,2);
                    343:                     my $what = &unescape($key);
                    344:                     my $hashid = $lonhost.'-'.$what;
                    345:                     $returnhash{$what}=&thaw_unescape($value);
                    346:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   347:                 }
                    348:             }
                    349:         }
                    350:     }
1.1125    raeburn   351:     return ($result,\%returnhash);
1.1121    raeburn   352: }
                    353: 
1.1124    raeburn   354: sub remote_devalidate_cache {
                    355:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   356:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   357:     return $response;
                    358: }
                    359: 
1.1       albertel  360: # -------------------------------------------------- Non-critical communication
                    361: sub subreply {
                    362:     my ($cmd,$server)=@_;
1.838     albertel  363:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      364:     #
                    365:     #  With loncnew process trimming, there's a timing hole between lonc server
                    366:     #  process exit and the master server picking up the listen on the AF_UNIX
                    367:     #  socket.  In that time interval, a lock file will exist:
                    368: 
                    369:     my $lockfile=$peerfile.".lock";
                    370:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    371: 	sleep(1);
                    372:     }
                    373:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      374:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      375:     #
1.550     foxr      376:     #   We'll give the connection a few tries before abandoning it.  If
                    377:     #   connection is not possible, we'll con_lost back to the client.
                    378:     #   
                    379:     my $client;
                    380:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    381: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    382: 				      Type    => SOCK_STREAM,
                    383: 				      Timeout => 10);
1.869     albertel  384: 	if ($client) {
1.550     foxr      385: 	    last;		# Connected!
1.850     albertel  386: 	} else {
1.853     albertel  387: 	    &create_connection(&hostname($server),$server);
1.550     foxr      388: 	}
1.850     albertel  389:         sleep(1);		# Try again later if failed connection.
1.550     foxr      390:     }
                    391:     my $answer;
                    392:     if ($client) {
1.704     albertel  393: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      394: 	$answer=<$client>;
                    395: 	if (!$answer) { $answer="con_lost"; }
                    396: 	chomp($answer);
                    397:     } else {
                    398: 	$answer = 'con_lost';	# Failed connection.
                    399:     }
1.1       albertel  400:     return $answer;
                    401: }
                    402: 
                    403: sub reply {
                    404:     my ($cmd,$server)=@_;
1.838     albertel  405:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  406:     my $answer=subreply($cmd,$server);
1.65      www       407:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  408:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       409:                 " $cmd to $server returned $answer</font>");
                    410:     }
1.1       albertel  411:     return $answer;
                    412: }
                    413: 
                    414: # ----------------------------------------------------------- Send USR1 to lonc
                    415: 
                    416: sub reconlonc {
1.891     albertel  417:     my ($lonid) = @_;
                    418:     my $hostname = &hostname($lonid);
                    419:     if ($lonid) {
                    420: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    421: 	if ($hostname && -e $peerfile) {
                    422: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    423: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    424: 					     Type    => SOCK_STREAM,
                    425: 					     Timeout => 10);
                    426: 	    if ($client) {
                    427: 		print $client ("reset_retries\n");
                    428: 		my $answer=<$client>;
                    429: 		#reset just this one.
                    430: 	    }
                    431: 	}
                    432: 	return;
                    433:     }
                    434: 
1.836     www       435:     &logthis("Trying to reconnect lonc");
1.1       albertel  436:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  437:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  438: 	my $loncpid=<$fh>;
                    439:         chomp($loncpid);
                    440:         if (kill 0 => $loncpid) {
                    441: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    442:             kill USR1 => $loncpid;
                    443:             sleep 1;
1.836     www       444:          } else {
1.12      www       445: 	    &logthis(
1.672     albertel  446:                "<font color=\"blue\">WARNING:".
1.12      www       447:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  448:         }
                    449:     } else {
1.836     www       450: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  451:     }
                    452: }
                    453: 
                    454: # ------------------------------------------------------ Critical communication
1.12      www       455: 
1.1       albertel  456: sub critical {
                    457:     my ($cmd,$server)=@_;
1.838     albertel  458:     unless (&hostname($server)) {
1.672     albertel  459:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       460:                " Critical message to unknown server ($server)</font>");
                    461:         return 'no_such_host';
                    462:     }
1.1       albertel  463:     my $answer=reply($cmd,$server);
                    464:     if ($answer eq 'con_lost') {
                    465: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  466: 	my $answer=reply($cmd,$server);
1.1       albertel  467:         if ($answer eq 'con_lost') {
                    468:             my $now=time;
                    469:             my $middlename=$cmd;
1.5       www       470:             $middlename=substr($middlename,0,16);
1.1       albertel  471:             $middlename=~s/\W//g;
                    472:             my $dfilename=
1.305     www       473:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    474:             $dumpcount++;
1.1       albertel  475:             {
1.448     albertel  476: 		my $dfh;
                    477: 		if (open($dfh,">$dfilename")) {
                    478: 		    print $dfh "$cmd\n"; 
                    479: 		    close($dfh);
                    480: 		}
1.1       albertel  481:             }
                    482:             sleep 2;
                    483:             my $wcmd='';
                    484:             {
1.448     albertel  485: 		my $dfh;
                    486: 		if (open($dfh,"<$dfilename")) {
                    487: 		    $wcmd=<$dfh>; 
                    488: 		    close($dfh);
                    489: 		}
1.1       albertel  490:             }
                    491:             chomp($wcmd);
1.7       www       492:             if ($wcmd eq $cmd) {
1.672     albertel  493: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       494:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  495:                 &logperm("D:$server:$cmd");
                    496: 	        return 'con_delayed';
                    497:             } else {
1.672     albertel  498:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       499:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  500:                 &logperm("F:$server:$cmd");
                    501:                 return 'con_failed';
                    502:             }
                    503:         }
                    504:     }
                    505:     return $answer;
1.405     albertel  506: }
                    507: 
1.755     albertel  508: # ------------------------------------------- check if return value is an error
                    509: 
                    510: sub error {
                    511:     my ($result) = @_;
1.756     albertel  512:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  513: 	if ($2 == 2) { return undef; }
                    514: 	return $1;
                    515:     }
                    516:     return undef;
                    517: }
                    518: 
1.783     albertel  519: sub convert_and_load_session_env {
                    520:     my ($lonidsdir,$handle)=@_;
                    521:     my @profile;
                    522:     {
1.917     albertel  523: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    524: 	if (!$opened) {
1.915     albertel  525: 	    return 0;
                    526: 	}
1.783     albertel  527: 	flock($idf,LOCK_SH);
                    528: 	@profile=<$idf>;
                    529: 	close($idf);
                    530:     }
                    531:     my %temp_env;
                    532:     foreach my $line (@profile) {
1.786     albertel  533: 	if ($line !~ m/=/) {
                    534: 	    return 0;
                    535: 	}
1.783     albertel  536: 	chomp($line);
                    537: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    538: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    539:     }
                    540:     unlink("$lonidsdir/$handle.id");
                    541:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    542: 	    0640)) {
                    543: 	%disk_env = %temp_env;
                    544: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    545: 	untie(%disk_env);
                    546:     }
1.786     albertel  547:     return 1;
1.783     albertel  548: }
                    549: 
1.374     www       550: # ------------------------------------------- Transfer profile into environment
1.780     albertel  551: my $env_loaded;
                    552: sub transfer_profile_to_env {
1.788     albertel  553:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    554:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       555: 
1.720     albertel  556:     if (!defined($lonidsdir)) {
                    557: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    558:     }
                    559:     if (!defined($handle)) {
                    560:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    561:     }
                    562: 
1.786     albertel  563:     my $convert;
                    564:     {
1.917     albertel  565:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    566: 	if (!$opened) {
1.915     albertel  567: 	    return;
                    568: 	}
1.786     albertel  569: 	flock($idf,LOCK_SH);
                    570: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    571: 		&GDBM_READER(),0640)) {
                    572: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    573: 	    untie(%disk_env);
                    574: 	} else {
                    575: 	    $convert = 1;
                    576: 	}
                    577:     }
                    578:     if ($convert) {
                    579: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    580: 	    &logthis("Failed to load session, or convert session.");
                    581: 	}
1.374     www       582:     }
1.783     albertel  583: 
1.786     albertel  584:     my %remove;
1.783     albertel  585:     while ( my $envname = each(%env) ) {
1.433     matthew   586:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    587:             if ($time < time-300) {
1.783     albertel  588:                 $remove{$key}++;
1.433     matthew   589:             }
                    590:         }
                    591:     }
1.783     albertel  592: 
1.619     albertel  593:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  594:     $env_loaded=1;
1.783     albertel  595:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   596:         &delenv($expired_key);
1.374     www       597:     }
1.1       albertel  598: }
                    599: 
1.916     albertel  600: # ---------------------------------------------------- Check for valid session 
                    601: sub check_for_valid_session {
1.1155    raeburn   602:     my ($r,$name) = @_;
1.916     albertel  603:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   604:     if ($name eq '') {
                    605:         $name = 'lonID';
                    606:     }
                    607:     my $lonid=$cookies{$name};
1.916     albertel  608:     return undef if (!$lonid);
                    609: 
                    610:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   611:     my $lonidsdir;
                    612:     if ($name eq 'lonDAV') {
                    613:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    614:     } else {
                    615:         $lonidsdir=$r->dir_config('lonIDsDir');
                    616:     }
1.916     albertel  617:     return undef if (!-e "$lonidsdir/$handle.id");
                    618: 
1.917     albertel  619:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    620:     return undef if (!$opened);
1.916     albertel  621: 
                    622:     flock($idf,LOCK_SH);
                    623:     my %disk_env;
                    624:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    625: 	    &GDBM_READER(),0640)) {
                    626: 	return undef;	
                    627:     }
                    628: 
                    629:     if (!defined($disk_env{'user.name'})
                    630: 	|| !defined($disk_env{'user.domain'})) {
                    631: 	return undef;
                    632:     }
1.1172.2.18  raeburn   633: 
                    634:     if (($r->user() eq '') && ($apache >= 2.4)) {
                    635:         if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
                    636:             $r->user($disk_env{'user.name'});
                    637:         } else {
                    638:             $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
                    639:         }
                    640:     }
                    641: 
1.916     albertel  642:     return $handle;
                    643: }
                    644: 
1.830     albertel  645: sub timed_flock {
                    646:     my ($file,$lock_type) = @_;
                    647:     my $failed=0;
                    648:     eval {
                    649: 	local $SIG{__DIE__}='DEFAULT';
                    650: 	local $SIG{ALRM}=sub {
                    651: 	    $failed=1;
                    652: 	    die("failed lock");
                    653: 	};
                    654: 	alarm(13);
                    655: 	flock($file,$lock_type);
                    656: 	alarm(0);
                    657:     };
                    658:     if ($failed) {
                    659: 	return undef;
                    660:     } else {
                    661: 	return 1;
                    662:     }
                    663: }
                    664: 
1.5       www       665: # ---------------------------------------------------------- Append Environment
                    666: 
                    667: sub appenv {
1.949     raeburn   668:     my ($newenv,$roles) = @_;
                    669:     if (ref($newenv) eq 'HASH') {
                    670:         foreach my $key (keys(%{$newenv})) {
                    671:             my $refused = 0;
                    672: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    673:                 $refused = 1;
                    674:                 if (ref($roles) eq 'ARRAY') {
                    675:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    676:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    677:                         $refused = 0;
                    678:                     }
                    679:                 }
                    680:             }
                    681:             if ($refused) {
                    682:                 &logthis("<font color=\"blue\">WARNING: ".
                    683:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    684:                          .'</font>');
                    685: 	        delete($newenv->{$key});
                    686:             } else {
                    687:                 $env{$key}=$newenv->{$key};
                    688:             }
                    689:         }
                    690:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    691:         if ($opened
                    692: 	    && &timed_flock($env_file,LOCK_EX)
                    693: 	    &&
                    694: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    695: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    696: 	    while (my ($key,$value) = each(%{$newenv})) {
                    697: 	        $disk_env{$key} = $value;
                    698: 	    }
                    699: 	    untie(%disk_env);
1.35      www       700:         }
1.191     harris41  701:     }
1.56      www       702:     return 'ok';
                    703: }
                    704: # ----------------------------------------------------- Delete from Environment
                    705: 
                    706: sub delenv {
1.1104    raeburn   707:     my ($delthis,$regexp,$roles) = @_;
                    708:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    709:         my $refused = 1;
                    710:         if (ref($roles) eq 'ARRAY') {
                    711:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    712:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    713:                 $refused = 0;
                    714:             }
                    715:         }
                    716:         if ($refused) {
                    717:             &logthis("<font color=\"blue\">WARNING: ".
                    718:                      "Attempt to delete from environment ".$delthis);
                    719:             return 'error';
                    720:         }
1.56      www       721:     }
1.917     albertel  722:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    723:     if ($opened
1.915     albertel  724: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  725: 	&&
                    726: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    727: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  728: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   729: 	    if ($regexp) {
                    730:                 if ($key=~/^$delthis/) {
                    731:                     delete($env{$key});
                    732:                     delete($disk_env{$key});
                    733:                 } 
                    734:             } else {
                    735:                 if ($key=~/^\Q$delthis\E/) {
                    736: 		    delete($env{$key});
                    737: 		    delete($disk_env{$key});
                    738: 	        }
                    739:             }
1.448     albertel  740: 	}
1.783     albertel  741: 	untie(%disk_env);
1.5       www       742:     }
                    743:     return 'ok';
1.369     albertel  744: }
                    745: 
1.790     albertel  746: sub get_env_multiple {
                    747:     my ($name) = @_;
                    748:     my @values;
                    749:     if (defined($env{$name})) {
                    750:         # exists is it an array
                    751:         if (ref($env{$name})) {
                    752:             @values=@{ $env{$name} };
                    753:         } else {
                    754:             $values[0]=$env{$name};
                    755:         }
                    756:     }
                    757:     return(@values);
                    758: }
                    759: 
1.958     www       760: # ------------------------------------------------------------------- Locking
                    761: 
                    762: sub set_lock {
                    763:     my ($text)=@_;
                    764:     $locknum++;
                    765:     my $id=$$.'-'.$locknum;
                    766:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    767:              'session.lock.'.$id => $text});
                    768:     return $id;
                    769: }
                    770: 
                    771: sub get_locks {
                    772:     my $num=0;
                    773:     my %texts=();
                    774:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    775:        if ($lock=~/\w/) {
                    776:           $num++;
                    777:           $texts{$lock}=$env{'session.lock.'.$lock};
                    778:        }
                    779:    }
                    780:    return ($num,%texts);
                    781: }
                    782: 
                    783: sub remove_lock {
                    784:     my ($id)=@_;
                    785:     my $newlocks='';
                    786:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    787:        if (($lock=~/\w/) && ($lock ne $id)) {
                    788:           $newlocks.=','.$lock;
                    789:        }
                    790:     }
                    791:     &appenv({'session.locks' => $newlocks});
                    792:     &delenv('session.lock.'.$id);
                    793: }
                    794: 
                    795: sub remove_all_locks {
                    796:     my $activelocks=$env{'session.locks'};
                    797:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    798:        if ($lock=~/\w/) {
                    799:           &remove_lock($lock);
                    800:        }
                    801:     }
                    802: }
                    803: 
                    804: 
1.369     albertel  805: # ------------------------------------------ Find out current server userload
                    806: sub userload {
                    807:     my $numusers=0;
                    808:     {
                    809: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    810: 	my $filename;
                    811: 	my $curtime=time;
                    812: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  813: 	    next if ($filename eq '.' || $filename eq '..');
                    814: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  815: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  816: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  817: 	}
                    818: 	closedir(LONIDS);
                    819:     }
                    820:     my $userloadpercent=0;
                    821:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    822:     if ($maxuserload) {
1.371     albertel  823: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  824:     }
1.372     albertel  825:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  826:     return $userloadpercent;
1.283     www       827: }
                    828: 
1.1       albertel  829: # ------------------------------ Find server with least workload from spare.tab
1.11      www       830: 
1.1       albertel  831: sub spareserver {
1.1083    raeburn   832:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  833:     my $spare_server;
1.370     albertel  834:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  835:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    836:                                                      :  $userloadpercent;
1.1083    raeburn   837:     my ($uint_dom,$remotesessions);
                    838:     if (($udom ne '') && (&domain($udom) ne '')) {
                    839:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    840:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    841:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    842:         $remotesessions = $udomdefaults{'remotesessions'};
                    843:     }
1.1123    raeburn   844:     my $spareshash = &this_host_spares($udom);
                    845:     if (ref($spareshash) eq 'HASH') {
                    846:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    847:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    848:                 if ($uint_dom) {
                    849:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    850:                                                  $try_server));
                    851:                 }
                    852: 	        ($spare_server, $lowest_load) =
                    853: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    854:             }
1.1083    raeburn   855:         }
1.784     albertel  856: 
1.1123    raeburn   857:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    858: 
                    859:         if (!$found_server) {
                    860:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    861: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    862:                     if ($uint_dom) {
                    863:                         next unless (&spare_can_host($udom,$uint_dom,
                    864:                                                      $remotesessions,$try_server));
                    865:                     }
                    866: 	            ($spare_server, $lowest_load) =
                    867: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    868:                 }
                    869: 	    }
                    870:         }
1.784     albertel  871:     }
                    872: 
                    873:     if (!$want_server_name) {
1.968     raeburn   874:         my $protocol = 'http';
                    875:         if ($protocol{$spare_server} eq 'https') {
                    876:             $protocol = $protocol{$spare_server};
                    877:         }
1.1001    raeburn   878:         if (defined($spare_server)) {
                    879:             my $hostname = &hostname($spare_server);
1.1083    raeburn   880:             if (defined($hostname)) {
1.1001    raeburn   881: 	        $spare_server = $protocol.'://'.$hostname;
                    882:             }
                    883:         }
1.784     albertel  884:     }
                    885:     return $spare_server;
                    886: }
                    887: 
                    888: sub compare_server_load {
                    889:     my ($try_server, $spare_server, $lowest_load) = @_;
                    890: 
                    891:     my $loadans     = &reply('load',    $try_server);
                    892:     my $userloadans = &reply('userload',$try_server);
                    893: 
                    894:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   895: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  896:     }
                    897: 
                    898:     my $load;
                    899:     if ($loadans =~ /\d/) {
                    900: 	if ($userloadans =~ /\d/) {
                    901: 	    #both are numbers, pick the bigger one
                    902: 	    $load = ($loadans > $userloadans) ? $loadans 
                    903: 		                              : $userloadans;
1.411     albertel  904: 	} else {
1.784     albertel  905: 	    $load = $loadans;
1.411     albertel  906: 	}
1.784     albertel  907:     } else {
                    908: 	$load = $userloadans;
                    909:     }
                    910: 
                    911:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    912: 	$spare_server = $try_server;
                    913: 	$lowest_load  = $load;
1.370     albertel  914:     }
1.784     albertel  915:     return ($spare_server,$lowest_load);
1.202     matthew   916: }
1.914     albertel  917: 
                    918: # --------------------------- ask offload servers if user already has a session
                    919: sub find_existing_session {
                    920:     my ($udom,$uname) = @_;
1.1123    raeburn   921:     my $spareshash = &this_host_spares($udom);
                    922:     if (ref($spareshash) eq 'HASH') {
                    923:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    924:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    925:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    926:             }
                    927:         }
                    928:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    929:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    930:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    931:             }
                    932:         }
1.914     albertel  933:     }
                    934:     return;
                    935: }
                    936: 
                    937: # -------------------------------- ask if server already has a session for user
                    938: sub has_user_session {
                    939:     my ($lonid,$udom,$uname) = @_;
                    940:     my $result = &reply(join(':','userhassession',
                    941: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    942:     return 1 if ($result eq 'ok');
                    943: 
                    944:     return 0;
                    945: }
                    946: 
1.1076    raeburn   947: # --------- determine least loaded server in a user's domain which allows login
                    948: 
                    949: sub choose_server {
1.1115    raeburn   950:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   951:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   952:     my %servers = &get_servers($udom);
1.1076    raeburn   953:     my $lowest_load = 30000;
1.1151    raeburn   954:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   955:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   956:         my $loginvia;
                    957:         if ($checkloginvia) {
                    958:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   959:             if ($loginvia) {
                    960:                 my ($server,$path) = split(/:/,$loginvia);
                    961:                 ($login_host, $lowest_load) =
                    962:                     &compare_server_load($server, $login_host, $lowest_load);
                    963:                 if ($login_host eq $server) {
                    964:                     $portal_path = $path;
1.1151    raeburn   965:                     $isredirect = 1;
1.1116    raeburn   966:                 }
                    967:             } else {
                    968:                 ($login_host, $lowest_load) =
                    969:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    970:                 if ($login_host eq $lonhost) {
                    971:                     $portal_path = '';
1.1151    raeburn   972:                     $isredirect = ''; 
1.1116    raeburn   973:                 }
                    974:             }
                    975:         } else {
1.1076    raeburn   976:             ($login_host, $lowest_load) =
1.1116    raeburn   977:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   978:         }
                    979:     }
                    980:     if ($login_host ne '') {
1.1116    raeburn   981:         $hostname = &hostname($login_host);
1.1076    raeburn   982:     }
1.1151    raeburn   983:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   984: }
                    985: 
1.202     matthew   986: # --------------------------------------------- Try to change a user's password
                    987: 
                    988: sub changepass {
1.799     raeburn   989:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   990:     $currentpass = &escape($currentpass);
                    991:     $newpass     = &escape($newpass);
1.1030    raeburn   992:     my $lonhost = $perlvar{'lonHostID'};
                    993:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   994: 		       $server);
                    995:     if (! $answer) {
                    996: 	&logthis("No reply on password change request to $server ".
                    997: 		 "by $uname in domain $udom.");
                    998:     } elsif ($answer =~ "^ok") {
                    999:         &logthis("$uname in $udom successfully changed their password ".
                   1000: 		 "on $server.");
                   1001:     } elsif ($answer =~ "^pwchange_failure") {
                   1002: 	&logthis("$uname in $udom was unable to change their password ".
                   1003: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1004: 		 "or pwchange");
                   1005:     } elsif ($answer =~ "^non_authorized") {
                   1006:         &logthis("$uname in $udom did not get their password correct when ".
                   1007: 		 "attempting to change it on $server.");
                   1008:     } elsif ($answer =~ "^auth_mode_error") {
                   1009:         &logthis("$uname in $udom attempted to change their password despite ".
                   1010: 		 "not being locally or internally authenticated on $server.");
                   1011:     } elsif ($answer =~ "^unknown_user") {
                   1012:         &logthis("$uname in $udom attempted to change their password ".
                   1013: 		 "on $server but were unable to because $server is not ".
                   1014: 		 "their home server.");
                   1015:     } elsif ($answer =~ "^refused") {
                   1016: 	&logthis("$server refused to change $uname in $udom password because ".
                   1017: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1018:     } elsif ($answer =~ "invalid_client") {
                   1019:         &logthis("$server refused to change $uname in $udom password because ".
                   1020:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1021:     }
                   1022:     return $answer;
1.1       albertel 1023: }
                   1024: 
1.169     harris41 1025: # ----------------------- Try to determine user's current authentication scheme
                   1026: 
                   1027: sub queryauthenticate {
                   1028:     my ($uname,$udom)=@_;
1.456     albertel 1029:     my $uhome=&homeserver($uname,$udom);
                   1030:     if (!$uhome) {
                   1031: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1032: 	return 'no_host';
                   1033:     }
                   1034:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1035:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1036: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1037:     }
1.456     albertel 1038:     return $answer;
1.169     harris41 1039: }
                   1040: 
1.1       albertel 1041: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1042: 
1.1       albertel 1043: sub authenticate {
1.1073    raeburn  1044:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1045:     $upass=&escape($upass);
                   1046:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1047:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1048:     my $newhome;
1.836     www      1049:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1050: # Maybe the machine was offline and only re-appeared again recently?
                   1051:         &reconlonc();
                   1052: # One more
1.952     raeburn  1053: 	$uhome=&homeserver($uname,$udom,1);
                   1054:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1055:             if (defined(&domain($udom,'primary'))) {
                   1056:                 $newhome=&domain($udom,'primary');
                   1057:             }
                   1058:             if ($newhome ne '') {
                   1059:                 $uhome = $newhome;
                   1060:             }
                   1061:         }
1.836     www      1062: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1063: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1064: 	    return 'no_host';
                   1065:         }
1.1       albertel 1066:     }
1.1073    raeburn  1067:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1068:     if ($answer eq 'authorized') {
1.952     raeburn  1069:         if ($newhome) {
                   1070:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1071:             return 'no_account_on_host'; 
                   1072:         } else {
                   1073:             &logthis("User $uname at $udom authorized by $uhome");
                   1074:             return $uhome;
                   1075:         }
1.471     albertel 1076:     }
                   1077:     if ($answer eq 'non_authorized') {
                   1078: 	&logthis("User $uname at $udom rejected by $uhome");
                   1079: 	return 'no_host'; 
1.9       www      1080:     }
1.471     albertel 1081:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1082:     return 'no_host';
                   1083: }
                   1084: 
1.1073    raeburn  1085: sub can_host_session {
1.1074    raeburn  1086:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1087:     my $canhost = 1;
1.1074    raeburn  1088:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1089:     if (ref($remotesessions) eq 'HASH') {
                   1090:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1091:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1092:                 $canhost = 0;
                   1093:             } else {
                   1094:                 $canhost = 1;
                   1095:             }
                   1096:         }
                   1097:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1098:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1099:                 $canhost = 1;
                   1100:             } else {
                   1101:                 $canhost = 0;
                   1102:             }
                   1103:         }
                   1104:         if ($canhost) {
                   1105:             if ($remotesessions->{'version'} ne '') {
                   1106:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1107:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1108:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1109:                         my $major = $1;
                   1110:                         my $minor = $2;
                   1111:                         if (($major < $reqmajor ) ||
                   1112:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1113:                             $canhost = 0;
                   1114:                         }
                   1115:                     } else {
                   1116:                         $canhost = 0;
                   1117:                     }
                   1118:                 }
                   1119:             }
                   1120:         }
                   1121:     }
                   1122:     if ($canhost) {
                   1123:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1124:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1125:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1126:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1127:                 if (($uint_dom ne '') && 
                   1128:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1129:                     $canhost = 0;
                   1130:                 } else {
                   1131:                     $canhost = 1;
                   1132:                 }
                   1133:             }
                   1134:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1135:                 if (($uint_dom ne '') && 
                   1136:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1137:                     $canhost = 1;
                   1138:                 } else {
                   1139:                     $canhost = 0;
                   1140:                 }
                   1141:             }
                   1142:         }
                   1143:     }
                   1144:     return $canhost;
                   1145: }
                   1146: 
1.1083    raeburn  1147: sub spare_can_host {
                   1148:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1149:     my $canhost=1;
                   1150:     my @intdoms;
                   1151:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1152:     if (ref($internet_names) eq 'ARRAY') {
                   1153:         @intdoms = @{$internet_names};
                   1154:     }
                   1155:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1156:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1157:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1158:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1159:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1160:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1161:                                      $remotesessions,
                   1162:                                      $defdomdefaults{'hostedsessions'});
                   1163:     }
                   1164:     return $canhost;
                   1165: }
                   1166: 
1.1123    raeburn  1167: sub this_host_spares {
                   1168:     my ($dom) = @_;
1.1126    raeburn  1169:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1170:     my @hosts = &current_machine_ids();
                   1171:     foreach my $lonhost (@hosts) {
                   1172:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1173:             $dom_in_use = $dom;
                   1174:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1175:             last;
                   1176:         }
                   1177:     }
1.1126    raeburn  1178:     if ($dom_in_use ne '') {
                   1179:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1180:     }
                   1181:     if (ref($result) ne 'HASH') {
                   1182:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1183:         $dom_in_use = &host_domain($lonhost_in_use);
                   1184:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1185:         if (ref($result) ne 'HASH') {
                   1186:             $result = \%spareid;
                   1187:         }
                   1188:     }
                   1189:     return $result;
                   1190: }
                   1191: 
                   1192: sub spares_for_offload  {
                   1193:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1194:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1195:     if (defined($cached)) {
                   1196:         return $result;
                   1197:     } else {
1.1126    raeburn  1198:         my $cachetime = 60*60*24;
                   1199:         my %domconfig =
                   1200:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1201:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1202:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1203:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1204:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1205:                 }
                   1206:             }
                   1207:         }
                   1208:     }
1.1126    raeburn  1209:     return;
1.1123    raeburn  1210: }
                   1211: 
1.1129    raeburn  1212: sub get_lonbalancer_config {
                   1213:     my ($servers) = @_;
                   1214:     my ($currbalancer,$currtargets);
                   1215:     if (ref($servers) eq 'HASH') {
                   1216:         foreach my $server (keys(%{$servers})) {
                   1217:             my %what = (
                   1218:                          spareid => 1,
                   1219:                          perlvar => 1,
                   1220:                        );
                   1221:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1222:             if ($result eq 'ok') {
                   1223:                 if (ref($returnhash) eq 'HASH') {
                   1224:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1225:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1226:                             $currbalancer = $server;
                   1227:                             $currtargets = {};
                   1228:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1229:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1230:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1231:                                 }
                   1232:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1233:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1234:                                 }
                   1235:                             }
                   1236:                             last;
                   1237:                         }
                   1238:                     }
                   1239:                 }
                   1240:             }
                   1241:         }
                   1242:     }
                   1243:     return ($currbalancer,$currtargets);
                   1244: }
                   1245: 
                   1246: sub check_loadbalancing {
                   1247:     my ($uname,$udom) = @_;
1.1172.2.12  raeburn  1248:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1249:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1250:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1251:     my @hosts = &current_machine_ids();
1.1129    raeburn  1252:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1253:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1254:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1255:     my $serverhomedom = &host_domain($lonhost);
                   1256: 
                   1257:     my $cachetime = 60*60*24;
                   1258: 
                   1259:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1260:         $dom_in_use = $udom;
                   1261:         $homeintdom = 1;
                   1262:     } else {
                   1263:         $dom_in_use = $serverhomedom;
                   1264:     }
                   1265:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1266:     unless (defined($cached)) {
                   1267:         my %domconfig =
                   1268:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1269:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1270:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1271:         }
                   1272:     }
                   1273:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1274:         ($is_balancer,$currtargets,$currrules) =
                   1275:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1276:         if ($is_balancer) {
                   1277:             if (ref($currrules) eq 'HASH') {
                   1278:                 if ($homeintdom) {
                   1279:                     if ($uname ne '') {
                   1280:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1281:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1282:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1283:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1284:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1285:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1286:                             }
                   1287:                         }
                   1288:                         if ($rule_in_effect eq '') {
                   1289:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1290:                             if ($userenv{'inststatus'} ne '') {
                   1291:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1292:                                 my ($othertitle,$usertypes,$types) =
                   1293:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1294:                                 if (ref($types) eq 'ARRAY') {
                   1295:                                     foreach my $type (@{$types}) {
                   1296:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1297:                                             if (exists($currrules->{$type})) {
                   1298:                                                 $rule_in_effect = $currrules->{$type};
                   1299:                                             }
                   1300:                                         }
                   1301:                                     }
                   1302:                                 }
                   1303:                             } else {
                   1304:                                 if (exists($currrules->{'default'})) {
                   1305:                                     $rule_in_effect = $currrules->{'default'};
                   1306:                                 }
                   1307:                             }
                   1308:                         }
                   1309:                     } else {
                   1310:                         if (exists($currrules->{'default'})) {
                   1311:                             $rule_in_effect = $currrules->{'default'};
                   1312:                         }
                   1313:                     }
                   1314:                 } else {
                   1315:                     if ($currrules->{'_LC_external'} ne '') {
                   1316:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1317:                     }
                   1318:                 }
                   1319:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1320:                                                        $uname,$udom);
                   1321:             }
                   1322:         }
                   1323:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1324:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1325:         unless (defined($cached)) {
                   1326:             my %domconfig =
                   1327:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1328:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1329:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1330:             }
                   1331:         }
                   1332:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1333:             ($is_balancer,$currtargets,$currrules) =
                   1334:                 &check_balancer_result($result,@hosts);
                   1335:             if ($is_balancer) {
1.1129    raeburn  1336:                 if (ref($currrules) eq 'HASH') {
                   1337:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1338:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1339:                     }
                   1340:                 }
                   1341:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1342:                                                        $uname,$udom);
                   1343:             }
                   1344:         } else {
                   1345:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1346:                 $is_balancer = 1;
                   1347:                 $offloadto = &this_host_spares($dom_in_use);
                   1348:             }
                   1349:         }
                   1350:     } else {
                   1351:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1352:             $is_balancer = 1;
                   1353:             $offloadto = &this_host_spares($dom_in_use);
                   1354:         }
                   1355:     }
1.1172.2.5  raeburn  1356:     if ($is_balancer) {
                   1357:         my $lowest_load = 30000;
                   1358:         if (ref($offloadto) eq 'HASH') {
                   1359:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1360:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1361:                     ($otherserver,$lowest_load) =
                   1362:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1363:                 }
1.1129    raeburn  1364:             }
1.1172.2.5  raeburn  1365:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1366: 
1.1172.2.5  raeburn  1367:             if (!$found_server) {
                   1368:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1369:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1370:                         ($otherserver,$lowest_load) =
                   1371:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1372:                     }
                   1373:                 }
                   1374:             }
                   1375:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1376:             if (@{$offloadto} == 1) {
                   1377:                 $otherserver = $offloadto->[0];
                   1378:             } elsif (@{$offloadto} > 1) {
                   1379:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1380:                     ($otherserver,$lowest_load) =
                   1381:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1382:                 }
                   1383:             }
                   1384:         }
1.1172.2.5  raeburn  1385:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1386:             $is_balancer = 0;
                   1387:             if ($uname ne '' && $udom ne '') {
                   1388:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1389: 
                   1390:                     &appenv({'user.loadbalexempt'     => $lonhost,
                   1391:                              'user.loadbalcheck.time' => time});
                   1392:                 }
1.1129    raeburn  1393:             }
                   1394:         }
                   1395:     }
                   1396:     return ($is_balancer,$otherserver);
                   1397: }
                   1398: 
1.1172.2.12  raeburn  1399: sub check_balancer_result {
                   1400:     my ($result,@hosts) = @_;
                   1401:     my ($is_balancer,$currtargets,$currrules);
                   1402:     if (ref($result) eq 'HASH') {
                   1403:         if ($result->{'lonhost'} ne '') {
                   1404:             my $currbalancer = $result->{'lonhost'};
                   1405:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1406:                 $is_balancer = 1;
                   1407:                 $currtargets = $result->{'targets'};
                   1408:                 $currrules = $result->{'rules'};
                   1409:             }
                   1410:         } else {
                   1411:             foreach my $key (keys(%{$result})) {
                   1412:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1413:                     (ref($result->{$key}) eq 'HASH')) {
                   1414:                     $is_balancer = 1;
                   1415:                     $currrules = $result->{$key}{'rules'};
                   1416:                     $currtargets = $result->{$key}{'targets'};
                   1417:                     last;
                   1418:                 }
                   1419:             }
                   1420:         }
                   1421:     }
                   1422:     return ($is_balancer,$currtargets,$currrules);
                   1423: }
                   1424: 
1.1129    raeburn  1425: sub get_loadbalancer_targets {
                   1426:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1427:     my $offloadto;
1.1172.2.4  raeburn  1428:     if ($rule_in_effect eq 'none') {
                   1429:         return [$perlvar{'lonHostID'}];
                   1430:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1431:         $offloadto = $currtargets;
                   1432:     } else {
                   1433:         if ($rule_in_effect eq 'homeserver') {
                   1434:             my $homeserver = &homeserver($uname,$udom);
                   1435:             if ($homeserver ne 'no_host') {
                   1436:                 $offloadto = [$homeserver];
                   1437:             }
                   1438:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1439:             my %domconfig =
                   1440:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1441:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1442:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1443:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1444:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1445:                     }
                   1446:                 }
                   1447:             } else {
1.1172.2.7  raeburn  1448:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1449:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1450:                 if (&hostname($remotebalancer) ne '') {
                   1451:                     $offloadto = [$remotebalancer];
                   1452:                 }
                   1453:             }
                   1454:         } elsif (&hostname($rule_in_effect) ne '') {
                   1455:             $offloadto = [$rule_in_effect];
                   1456:         }
                   1457:     }
                   1458:     return $offloadto;
                   1459: }
                   1460: 
1.1127    raeburn  1461: sub internet_dom_servers {
                   1462:     my ($dom) = @_;
                   1463:     my (%uniqservers,%servers);
                   1464:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1465:     my @machinedoms = &machine_domains($primaryserver);
                   1466:     foreach my $mdom (@machinedoms) {
                   1467:         my %currservers = %servers;
                   1468:         my %server = &get_servers($mdom);
                   1469:         %servers = (%currservers,%server);
                   1470:     }
                   1471:     my %by_hostname;
                   1472:     foreach my $id (keys(%servers)) {
                   1473:         push(@{$by_hostname{$servers{$id}}},$id);
                   1474:     }
                   1475:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1476:         if (@{$by_hostname{$hostname}} > 1) {
                   1477:             my $match = 0;
                   1478:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1479:                 if (&host_domain($id) eq $dom) {
                   1480:                     $uniqservers{$id} = $hostname;
                   1481:                     $match = 1;
                   1482:                 }
                   1483:             }
                   1484:             unless ($match) {
                   1485:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1486:             }
                   1487:         } else {
                   1488:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1489:         }
                   1490:     }
                   1491:     return %uniqservers;
                   1492: }
                   1493: 
1.1       albertel 1494: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1495: 
1.599     albertel 1496: my %homecache;
1.1       albertel 1497: sub homeserver {
1.230     stredwic 1498:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1499:     my $index="$uname:$udom";
1.426     albertel 1500: 
1.599     albertel 1501:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1502: 
                   1503:     my %servers = &get_servers($udom,'library');
                   1504:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1505:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1506: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1507: 
                   1508: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1509: 	if ($answer eq 'found') {
                   1510: 	    delete($badServerCache{$tryserver}); 
                   1511: 	    return $homecache{$index}=$tryserver;
                   1512: 	} elsif ($answer eq 'no_host') {
                   1513: 	    $badServerCache{$tryserver}=1;
                   1514: 	}
1.1       albertel 1515:     }    
                   1516:     return 'no_host';
1.70      www      1517: }
                   1518: 
                   1519: # ------------------------------------- Find the usernames behind a list of IDs
                   1520: 
                   1521: sub idget {
                   1522:     my ($udom,@ids)=@_;
                   1523:     my %returnhash=();
                   1524:     
1.841     albertel 1525:     my %servers = &get_servers($udom,'library');
                   1526:     foreach my $tryserver (keys(%servers)) {
                   1527: 	my $idlist=join('&',@ids);
                   1528: 	$idlist=~tr/A-Z/a-z/; 
                   1529: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1530: 	my @answer=();
                   1531: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1532: 	    @answer=split(/\&/,$reply);
                   1533: 	}                    ;
                   1534: 	my $i;
                   1535: 	for ($i=0;$i<=$#ids;$i++) {
                   1536: 	    if ($answer[$i]) {
                   1537: 		$returnhash{$ids[$i]}=$answer[$i];
                   1538: 	    } 
                   1539: 	}
                   1540:     } 
1.70      www      1541:     return %returnhash;
                   1542: }
                   1543: 
                   1544: # ------------------------------------- Find the IDs behind a list of usernames
                   1545: 
                   1546: sub idrget {
                   1547:     my ($udom,@unames)=@_;
                   1548:     my %returnhash=();
1.800     albertel 1549:     foreach my $uname (@unames) {
                   1550:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1551:     }
1.70      www      1552:     return %returnhash;
                   1553: }
                   1554: 
                   1555: # ------------------------------- Store away a list of names and associated IDs
                   1556: 
                   1557: sub idput {
                   1558:     my ($udom,%ids)=@_;
                   1559:     my %servers=();
1.800     albertel 1560:     foreach my $uname (keys(%ids)) {
                   1561: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1562:         my $uhom=&homeserver($uname,$udom);
1.70      www      1563:         if ($uhom ne 'no_host') {
1.800     albertel 1564:             my $id=&escape($ids{$uname});
1.70      www      1565:             $id=~tr/A-Z/a-z/;
1.800     albertel 1566:             my $esc_unam=&escape($uname);
1.70      www      1567: 	    if ($servers{$uhom}) {
1.800     albertel 1568: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1569:             } else {
1.800     albertel 1570:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1571:             }
                   1572:         }
1.191     harris41 1573:     }
1.800     albertel 1574:     foreach my $server (keys(%servers)) {
                   1575:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1576:     }
1.344     www      1577: }
                   1578: 
1.1023    raeburn  1579: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1580: sub dump_dom {
1.1165    droeschl 1581:     my ($namespace, $udom, $regexp) = @_;
                   1582: 
                   1583:     $udom ||= $env{'user.domain'};
                   1584: 
                   1585:     return () unless $udom;
                   1586: 
                   1587:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1588: }
                   1589: 
1.1023    raeburn  1590: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1591: 
                   1592: sub get_dom {
1.860     raeburn  1593:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1594:     my $items='';
                   1595:     foreach my $item (@$storearr) {
                   1596:         $items.=&escape($item).'&';
                   1597:     }
                   1598:     $items=~s/\&$//;
1.860     raeburn  1599:     if (!$udom) {
                   1600:         $udom=$env{'user.domain'};
                   1601:         if (defined(&domain($udom,'primary'))) {
                   1602:             $uhome=&domain($udom,'primary');
                   1603:         } else {
1.874     albertel 1604:             undef($uhome);
1.860     raeburn  1605:         }
                   1606:     } else {
                   1607:         if (!$uhome) {
                   1608:             if (defined(&domain($udom,'primary'))) {
                   1609:                 $uhome=&domain($udom,'primary');
                   1610:             }
                   1611:         }
                   1612:     }
                   1613:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1614:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1615:         my %returnhash;
1.875     albertel 1616:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1617:             return %returnhash;
                   1618:         }
1.806     raeburn  1619:         my @pairs=split(/\&/,$rep);
                   1620:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1621:             return @pairs;
                   1622:         }
                   1623:         my $i=0;
                   1624:         foreach my $item (@$storearr) {
                   1625:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1626:             $i++;
                   1627:         }
                   1628:         return %returnhash;
                   1629:     } else {
1.880     banghart 1630:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1631:     }
                   1632: }
                   1633: 
                   1634: # -------------------------------------------- put items in domain db files 
                   1635: 
                   1636: sub put_dom {
1.860     raeburn  1637:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1638:     if (!$udom) {
                   1639:         $udom=$env{'user.domain'};
                   1640:         if (defined(&domain($udom,'primary'))) {
                   1641:             $uhome=&domain($udom,'primary');
                   1642:         } else {
1.874     albertel 1643:             undef($uhome);
1.860     raeburn  1644:         }
                   1645:     } else {
                   1646:         if (!$uhome) {
                   1647:             if (defined(&domain($udom,'primary'))) {
                   1648:                 $uhome=&domain($udom,'primary');
                   1649:             }
                   1650:         }
                   1651:     } 
                   1652:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1653:         my $items='';
                   1654:         foreach my $item (keys(%$storehash)) {
                   1655:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1656:         }
                   1657:         $items=~s/\&$//;
                   1658:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1659:     } else {
1.860     raeburn  1660:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1661:     }
                   1662: }
                   1663: 
1.1023    raeburn  1664: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1665: sub newput_dom {
1.1023    raeburn  1666:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1667:     my $result;
                   1668:     if (!$udom) {
                   1669:         $udom=$env{'user.domain'};
                   1670:     }
1.1023    raeburn  1671:     if ($udom) {
                   1672:         my $uname = &get_domainconfiguser($udom);
                   1673:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1674:     }
                   1675:     return $result;
                   1676: }
                   1677: 
1.1023    raeburn  1678: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1679: sub del_dom {
1.1023    raeburn  1680:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1681:     if (ref($storearr) eq 'ARRAY') {
                   1682:         if (!$udom) {
                   1683:             $udom=$env{'user.domain'};
                   1684:         }
1.1023    raeburn  1685:         if ($udom) {
                   1686:             my $uname = &get_domainconfiguser($udom); 
                   1687:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1688:         }
                   1689:     }
                   1690: }
                   1691: 
1.1023    raeburn  1692: # ----------------------------------construct domainconfig user for a domain 
                   1693: sub get_domainconfiguser {
                   1694:     my ($udom) = @_;
                   1695:     return $udom.'-domainconfig';
                   1696: }
                   1697: 
1.837     raeburn  1698: sub retrieve_inst_usertypes {
                   1699:     my ($udom) = @_;
                   1700:     my (%returnhash,@order);
1.989     raeburn  1701:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1702:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1703:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1704:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1705:         @order = @{$domdefs{'inststatusorder'}};
                   1706:     } else {
                   1707:         if (defined(&domain($udom,'primary'))) {
                   1708:             my $uhome=&domain($udom,'primary');
                   1709:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1710:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1711:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1712:                 return (\%returnhash,\@order);
                   1713:             }
                   1714:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1715:             my @pairs=split(/\&/,$hashitems);
                   1716:             foreach my $item (@pairs) {
                   1717:                 my ($key,$value)=split(/=/,$item,2);
                   1718:                 $key = &unescape($key);
                   1719:                 next if ($key =~ /^error: 2 /);
                   1720:                 $returnhash{$key}=&thaw_unescape($value);
                   1721:             }
                   1722:             my @esc_order = split(/\&/,$orderitems);
                   1723:             foreach my $item (@esc_order) {
                   1724:                 push(@order,&unescape($item));
                   1725:             }
                   1726:         } else {
                   1727:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1728:         }
                   1729:     }
                   1730:     return (\%returnhash,\@order);
                   1731: }
                   1732: 
1.868     raeburn  1733: sub is_domainimage {
                   1734:     my ($url) = @_;
                   1735:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1736:         if (&domain($1) ne '') {
                   1737:             return '1';
                   1738:         }
                   1739:     }
                   1740:     return;
                   1741: }
                   1742: 
1.899     raeburn  1743: sub inst_directory_query {
                   1744:     my ($srch) = @_;
                   1745:     my $udom = $srch->{'srchdomain'};
                   1746:     my %results;
                   1747:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1748:     my $outcome;
1.899     raeburn  1749:     if ($homeserver ne '') {
1.904     albertel 1750: 	my $queryid=&reply("querysend:instdirsearch:".
                   1751: 			   &escape($srch->{'srchby'}).':'.
                   1752: 			   &escape($srch->{'srchterm'}).':'.
                   1753: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1754: 	my $host=&hostname($homeserver);
                   1755: 	if ($queryid !~/^\Q$host\E\_/) {
                   1756: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1757: 	    return;
                   1758: 	}
                   1759: 	my $response = &get_query_reply($queryid);
                   1760: 	my $maxtries = 5;
                   1761: 	my $tries = 1;
                   1762: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1763: 	    $response = &get_query_reply($queryid);
                   1764: 	    $tries ++;
                   1765: 	}
                   1766: 
                   1767:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1768:             if ($response eq 'unavailable') {
                   1769:                 $outcome = $response;
                   1770:             } else {
                   1771:                 $outcome = 'ok';
                   1772:                 my @matches = split(/\n/,$response);
                   1773:                 foreach my $match (@matches) {
                   1774:                     my ($key,$value) = split(/=/,$match);
                   1775:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1776:                 }
1.899     raeburn  1777:             }
                   1778:         }
                   1779:     }
1.909     raeburn  1780:     return ($outcome,%results);
1.899     raeburn  1781: }
                   1782: 
                   1783: sub usersearch {
                   1784:     my ($srch) = @_;
                   1785:     my $dom = $srch->{'srchdomain'};
                   1786:     my %results;
                   1787:     my %libserv = &all_library();
                   1788:     my $query = 'usersearch';
                   1789:     foreach my $tryserver (keys(%libserv)) {
                   1790:         if (&host_domain($tryserver) eq $dom) {
                   1791:             my $host=&hostname($tryserver);
                   1792:             my $queryid=
1.911     raeburn  1793:                 &reply("querysend:".&escape($query).':'.
                   1794:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1795:                        &escape($srch->{'srchtype'}).':'.
                   1796:                        &escape($srch->{'srchterm'}),$tryserver);
                   1797:             if ($queryid !~/^\Q$host\E\_/) {
                   1798:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1799:                 next;
1.899     raeburn  1800:             }
                   1801:             my $reply = &get_query_reply($queryid);
                   1802:             my $maxtries = 1;
                   1803:             my $tries = 1;
                   1804:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1805:                 $reply = &get_query_reply($queryid);
                   1806:                 $tries ++;
                   1807:             }
                   1808:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1809:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1810:             } else {
1.911     raeburn  1811:                 my @matches;
                   1812:                 if ($reply =~ /\n/) {
                   1813:                     @matches = split(/\n/,$reply);
                   1814:                 } else {
                   1815:                     @matches = split(/\&/,$reply);
                   1816:                 }
1.899     raeburn  1817:                 foreach my $match (@matches) {
                   1818:                     my ($uname,$udom,%userhash);
1.911     raeburn  1819:                     foreach my $entry (split(/:/,$match)) {
                   1820:                         my ($key,$value) =
                   1821:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1822:                         $userhash{$key} = $value;
                   1823:                         if ($key eq 'username') {
                   1824:                             $uname = $value;
                   1825:                         } elsif ($key eq 'domain') {
                   1826:                             $udom = $value;
1.911     raeburn  1827:                         }
1.899     raeburn  1828:                     }
                   1829:                     $results{$uname.':'.$udom} = \%userhash;
                   1830:                 }
                   1831:             }
                   1832:         }
                   1833:     }
                   1834:     return %results;
                   1835: }
                   1836: 
1.912     raeburn  1837: sub get_instuser {
                   1838:     my ($udom,$uname,$id) = @_;
                   1839:     my $homeserver = &domain($udom,'primary');
                   1840:     my ($outcome,%results);
                   1841:     if ($homeserver ne '') {
                   1842:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1843:                            &escape($id).':'.&escape($udom),$homeserver);
                   1844:         my $host=&hostname($homeserver);
                   1845:         if ($queryid !~/^\Q$host\E\_/) {
                   1846:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1847:             return;
                   1848:         }
                   1849:         my $response = &get_query_reply($queryid);
                   1850:         my $maxtries = 5;
                   1851:         my $tries = 1;
                   1852:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1853:             $response = &get_query_reply($queryid);
                   1854:             $tries ++;
                   1855:         }
                   1856:         if (!&error($response) && $response ne 'refused') {
                   1857:             if ($response eq 'unavailable') {
                   1858:                 $outcome = $response;
                   1859:             } else {
                   1860:                 $outcome = 'ok';
                   1861:                 my @matches = split(/\n/,$response);
                   1862:                 foreach my $match (@matches) {
                   1863:                     my ($key,$value) = split(/=/,$match);
                   1864:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1865:                 }
                   1866:             }
                   1867:         }
                   1868:     }
                   1869:     my %userinfo;
                   1870:     if (ref($results{$uname}) eq 'HASH') {
                   1871:         %userinfo = %{$results{$uname}};
                   1872:     } 
                   1873:     return ($outcome,%userinfo);
                   1874: }
                   1875: 
                   1876: sub inst_rulecheck {
1.923     raeburn  1877:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1878:     my %returnhash;
                   1879:     if ($udom ne '') {
                   1880:         if (ref($rules) eq 'ARRAY') {
                   1881:             @{$rules} = map {&escape($_);} (@{$rules});
                   1882:             my $rulestr = join(':',@{$rules});
                   1883:             my $homeserver=&domain($udom,'primary');
                   1884:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1885:                 my $response;
                   1886:                 if ($item eq 'username') {                
                   1887:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1888:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1889:                                               $homeserver));
1.923     raeburn  1890:                 } elsif ($item eq 'id') {
                   1891:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1892:                                               ':'.&escape($id).':'.$rulestr,
                   1893:                                               $homeserver));
1.945     raeburn  1894:                 } elsif ($item eq 'selfcreate') {
                   1895:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1896:                                                &escape($udom).':'.&escape($uname).
                   1897:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1898:                 }
1.912     raeburn  1899:                 if ($response ne 'refused') {
                   1900:                     my @pairs=split(/\&/,$response);
                   1901:                     foreach my $item (@pairs) {
                   1902:                         my ($key,$value)=split(/=/,$item,2);
                   1903:                         $key = &unescape($key);
                   1904:                         next if ($key =~ /^error: 2 /);
                   1905:                         $returnhash{$key}=&thaw_unescape($value);
                   1906:                     }
                   1907:                 }
                   1908:             }
                   1909:         }
                   1910:     }
                   1911:     return %returnhash;
                   1912: }
                   1913: 
                   1914: sub inst_userrules {
1.923     raeburn  1915:     my ($udom,$check) = @_;
1.912     raeburn  1916:     my (%ruleshash,@ruleorder);
                   1917:     if ($udom ne '') {
                   1918:         my $homeserver=&domain($udom,'primary');
                   1919:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1920:             my $response;
                   1921:             if ($check eq 'id') {
                   1922:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1923:                                  $homeserver);
1.943     raeburn  1924:             } elsif ($check eq 'email') {
                   1925:                 $response=&reply('instemailrules:'.&escape($udom),
                   1926:                                  $homeserver);
1.923     raeburn  1927:             } else {
                   1928:                 $response=&reply('instuserrules:'.&escape($udom),
                   1929:                                  $homeserver);
                   1930:             }
1.912     raeburn  1931:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1932:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1933:                 ($response ne 'no_such_host')) {
                   1934:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1935:                 my @pairs=split(/\&/,$hashitems);
                   1936:                 foreach my $item (@pairs) {
                   1937:                     my ($key,$value)=split(/=/,$item,2);
                   1938:                     $key = &unescape($key);
                   1939:                     next if ($key =~ /^error: 2 /);
                   1940:                     $ruleshash{$key}=&thaw_unescape($value);
                   1941:                 }
                   1942:                 my @esc_order = split(/\&/,$orderitems);
                   1943:                 foreach my $item (@esc_order) {
                   1944:                     push(@ruleorder,&unescape($item));
                   1945:                 }
                   1946:             }
                   1947:         }
                   1948:     }
                   1949:     return (\%ruleshash,\@ruleorder);
                   1950: }
                   1951: 
1.976     raeburn  1952: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1953: 
                   1954: sub get_domain_defaults {
                   1955:     my ($domain) = @_;
                   1956:     my $cachetime = 60*60*24;
                   1957:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1958:     if (defined($cached)) {
                   1959:         if (ref($result) eq 'HASH') {
                   1960:             return %{$result};
                   1961:         }
                   1962:     }
                   1963:     my %domdefaults;
                   1964:     my %domconfig =
1.989     raeburn  1965:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1966:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  1967:                                   'coursedefaults','usersessions',
                   1968:                                   'requestauthor'],$domain);
1.943     raeburn  1969:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1970:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1971:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1972:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1973:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1974:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1975:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1976:     } else {
                   1977:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1978:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1979:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1980:     }
1.976     raeburn  1981:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1982:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1983:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1984:         } else {
                   1985:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1986:         } 
1.1172.2.6  raeburn  1987:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  1988:         foreach my $item (@usertools) {
                   1989:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1990:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1991:             }
                   1992:         }
                   1993:     }
1.985     raeburn  1994:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1995:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1996:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1997:         }
                   1998:     }
1.1172.2.9  raeburn  1999:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2000:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2001:     }
1.989     raeburn  2002:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   2003:         foreach my $item ('inststatustypes','inststatusorder') {
                   2004:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2005:         }
                   2006:     }
1.1047    raeburn  2007:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.19  raeburn  2008:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2009:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
                   2010:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
1.1047    raeburn  2011:         }
                   2012:     }
1.1073    raeburn  2013:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2014:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2015:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2016:         }
                   2017:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2018:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2019:         }
                   2020:     }
1.1172.2.23! raeburn  2021:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2022:     return %domdefaults;
                   2023: }
                   2024: 
1.344     www      2025: # --------------------------------------------------- Assign a key to a student
                   2026: 
                   2027: sub assign_access_key {
1.364     www      2028: #
                   2029: # a valid key looks like uname:udom#comments
                   2030: # comments are being appended
                   2031: #
1.498     www      2032:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2033:     $kdom=
1.620     albertel 2034:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2035:     $knum=
1.620     albertel 2036:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2037:     $cdom=
1.620     albertel 2038:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2039:     $cnum=
1.620     albertel 2040:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2041:     $udom=$env{'user.name'} unless (defined($udom));
                   2042:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2043:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2044:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2045:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2046:                                                   # assigned to this person
                   2047:                                                   # - this should not happen,
1.345     www      2048:                                                   # unless something went wrong
                   2049:                                                   # the first time around
                   2050: # ready to assign
1.364     www      2051:         $logentry=$1.'; '.$logentry;
1.496     www      2052:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2053:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2054: # key now belongs to user
1.346     www      2055: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2056:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2057:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2058:                 return 'ok';
                   2059:             } else {
                   2060:                 return 
                   2061:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2062: 	    }
                   2063:         } else {
                   2064:             return 'error: Could not assign key, try again later.';
                   2065:         }
1.364     www      2066:     } elsif (!$existing{$ckey}) {
1.345     www      2067: # the key does not exist
                   2068: 	return 'error: The key does not exist';
                   2069:     } else {
                   2070: # the key is somebody else's
                   2071: 	return 'error: The key is already in use';
                   2072:     }
1.344     www      2073: }
                   2074: 
1.364     www      2075: # ------------------------------------------ put an additional comment on a key
                   2076: 
                   2077: sub comment_access_key {
                   2078: #
                   2079: # a valid key looks like uname:udom#comments
                   2080: # comments are being appended
                   2081: #
                   2082:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2083:     $cdom=
1.620     albertel 2084:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2085:     $cnum=
1.620     albertel 2086:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2087:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2088:     if ($existing{$ckey}) {
                   2089:         $existing{$ckey}.='; '.$logentry;
                   2090: # ready to assign
1.367     www      2091:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2092:                                                  $cdom,$cnum) eq 'ok') {
                   2093: 	    return 'ok';
                   2094:         } else {
                   2095: 	    return 'error: Count not store comment.';
                   2096:         }
                   2097:     } else {
                   2098: # the key does not exist
                   2099: 	return 'error: The key does not exist';
                   2100:     }
                   2101: }
                   2102: 
1.344     www      2103: # ------------------------------------------------------ Generate a set of keys
                   2104: 
                   2105: sub generate_access_keys {
1.364     www      2106:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2107:     $cdom=
1.620     albertel 2108:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2109:     $cnum=
1.620     albertel 2110:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2111:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2112:     unless (($cdom) && ($cnum)) { return 0; }
                   2113:     if ($number>10000) { return 0; }
                   2114:     sleep(2); # make sure don't get same seed twice
                   2115:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2116:     my $total=0;
                   2117:     for (my $i=1;$i<=$number;$i++) {
                   2118:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2119:                   sprintf("%lx",int(100000*rand)).'-'.
                   2120:                   sprintf("%lx",int(100000*rand));
                   2121:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2122:        $newkey=~s/0/h/g; # and also 0 and O
                   2123:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2124:        if ($existing{$newkey}) {
                   2125:            $i--;
                   2126:        } else {
1.364     www      2127: 	  if (&put('accesskeys',
                   2128:               { $newkey => '# generated '.localtime().
1.620     albertel 2129:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2130:                            '; '.$logentry },
                   2131: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2132:               $total++;
                   2133: 	  }
                   2134:        }
                   2135:     }
1.620     albertel 2136:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2137:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2138:     return $total;
                   2139: }
                   2140: 
                   2141: # ------------------------------------------------------- Validate an accesskey
                   2142: 
                   2143: sub validate_access_key {
                   2144:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2145:     $cdom=
1.620     albertel 2146:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2147:     $cnum=
1.620     albertel 2148:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2149:     $udom=$env{'user.domain'} unless (defined($udom));
                   2150:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2151:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2152:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2153: }
                   2154: 
                   2155: # ------------------------------------- Find the section of student in a course
1.652     albertel 2156: sub devalidate_getsection_cache {
                   2157:     my ($udom,$unam,$courseid)=@_;
                   2158:     my $hashid="$udom:$unam:$courseid";
                   2159:     &devalidate_cache_new('getsection',$hashid);
                   2160: }
1.298     matthew  2161: 
1.815     albertel 2162: sub courseid_to_courseurl {
                   2163:     my ($courseid) = @_;
                   2164:     #already url style courseid
                   2165:     return $courseid if ($courseid =~ m{^/});
                   2166: 
                   2167:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2168: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2169: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2170: 	return "/$cdom/$cnum";
                   2171:     }
                   2172: 
                   2173:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2174:     if (exists($courseinfo{'num'})) {
                   2175: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2176:     }
                   2177: 
                   2178:     return undef;
                   2179: }
                   2180: 
1.298     matthew  2181: sub getsection {
                   2182:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2183:     my $cachetime=1800;
1.551     albertel 2184: 
                   2185:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2186:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2187:     if (defined($cached)) { return $result; }
                   2188: 
1.298     matthew  2189:     my %Pending; 
                   2190:     my %Expired;
                   2191:     #
                   2192:     # Each role can either have not started yet (pending), be active, 
                   2193:     #    or have expired.
                   2194:     #
                   2195:     # If there is an active role, we are done.
                   2196:     #
                   2197:     # If there is more than one role which has not started yet, 
                   2198:     #     choose the one which will start sooner
                   2199:     # If there is one role which has not started yet, return it.
                   2200:     #
                   2201:     # If there is more than one expired role, choose the one which ended last.
                   2202:     # If there is a role which has expired, return it.
                   2203:     #
1.815     albertel 2204:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2205:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2206:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2207:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2208:         my $section=$1;
                   2209:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2210:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2211:         my $now=time;
1.548     albertel 2212:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2213:             $Expired{$end}=$section;
                   2214:             next;
                   2215:         }
1.548     albertel 2216:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2217:             $Pending{$start}=$section;
                   2218:             next;
                   2219:         }
1.599     albertel 2220:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2221:     }
                   2222:     #
                   2223:     # Presumedly there will be few matching roles from the above
                   2224:     # loop and the sorting time will be negligible.
                   2225:     if (scalar(keys(%Pending))) {
                   2226:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2227:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2228:     } 
                   2229:     if (scalar(keys(%Expired))) {
                   2230:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2231:         my $time = pop(@sorted);
1.599     albertel 2232:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2233:     }
1.599     albertel 2234:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2235: }
1.70      www      2236: 
1.599     albertel 2237: sub save_cache {
                   2238:     &purge_remembered();
1.722     albertel 2239:     #&Apache::loncommon::validate_page();
1.620     albertel 2240:     undef(%env);
1.780     albertel 2241:     undef($env_loaded);
1.599     albertel 2242: }
1.452     albertel 2243: 
1.599     albertel 2244: my $to_remember=-1;
                   2245: my %remembered;
                   2246: my %accessed;
                   2247: my $kicks=0;
                   2248: my $hits=0;
1.849     albertel 2249: sub make_key {
                   2250:     my ($name,$id) = @_;
1.872     albertel 2251:     if (length($id) > 65 
                   2252: 	&& length(&escape($id)) > 200) {
                   2253: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2254:     }
1.849     albertel 2255:     return &escape($name.':'.$id);
                   2256: }
                   2257: 
1.599     albertel 2258: sub devalidate_cache_new {
                   2259:     my ($name,$id,$debug) = @_;
                   2260:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2261:     $id=&make_key($name,$id);
1.599     albertel 2262:     $memcache->delete($id);
                   2263:     delete($remembered{$id});
                   2264:     delete($accessed{$id});
                   2265: }
                   2266: 
                   2267: sub is_cached_new {
                   2268:     my ($name,$id,$debug) = @_;
1.849     albertel 2269:     $id=&make_key($name,$id);
1.599     albertel 2270:     if (exists($remembered{$id})) {
1.1133    foxr     2271: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2272: 	$accessed{$id}=[&gettimeofday()];
                   2273: 	$hits++;
                   2274: 	return ($remembered{$id},1);
                   2275:     }
                   2276:     my $value = $memcache->get($id);
                   2277:     if (!(defined($value))) {
                   2278: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2279: 	return (undef,undef);
1.416     albertel 2280:     }
1.599     albertel 2281:     if ($value eq '__undef__') {
                   2282: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2283: 	$value=undef;
                   2284:     }
                   2285:     &make_room($id,$value,$debug);
                   2286:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2287:     return ($value,1);
                   2288: }
                   2289: 
                   2290: sub do_cache_new {
                   2291:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2292:     $id=&make_key($name,$id);
1.599     albertel 2293:     my $setvalue=$value;
                   2294:     if (!defined($setvalue)) {
                   2295: 	$setvalue='__undef__';
                   2296:     }
1.623     albertel 2297:     if (!defined($time) ) {
                   2298: 	$time=600;
                   2299:     }
1.599     albertel 2300:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2301:     my $result = $memcache->set($id,$setvalue,$time);
                   2302:     if (! $result) {
1.872     albertel 2303: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2304: 	$memcache->disconnect_all();
1.872     albertel 2305:     }
1.600     albertel 2306:     # need to make a copy of $value
1.919     albertel 2307:     &make_room($id,$value,$debug);
1.599     albertel 2308:     return $value;
                   2309: }
                   2310: 
                   2311: sub make_room {
                   2312:     my ($id,$value,$debug)=@_;
1.919     albertel 2313: 
                   2314:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2315:                                     : $value;
1.599     albertel 2316:     if ($to_remember<0) { return; }
                   2317:     $accessed{$id}=[&gettimeofday()];
                   2318:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2319:     my $to_kick;
                   2320:     my $max_time=0;
                   2321:     foreach my $other (keys(%accessed)) {
                   2322: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2323: 	    $to_kick=$other;
                   2324: 	    $max_time=&tv_interval($accessed{$other});
                   2325: 	}
                   2326:     }
                   2327:     delete($remembered{$to_kick});
                   2328:     delete($accessed{$to_kick});
                   2329:     $kicks++;
                   2330:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2331:     return;
                   2332: }
                   2333: 
1.599     albertel 2334: sub purge_remembered {
1.604     albertel 2335:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2336:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2337:     undef(%remembered);
                   2338:     undef(%accessed);
1.428     albertel 2339: }
1.70      www      2340: # ------------------------------------- Read an entry from a user's environment
                   2341: 
                   2342: sub userenvironment {
                   2343:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2344:     my $items;
                   2345:     foreach my $item (@what) {
                   2346:         $items.=&escape($item).'&';
                   2347:     }
                   2348:     $items=~s/\&$//;
1.70      www      2349:     my %returnhash=();
1.1009    raeburn  2350:     my $uhome = &homeserver($unam,$udom);
                   2351:     unless ($uhome eq 'no_host') {
                   2352:         my @answer=split(/\&/, 
                   2353:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2354:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2355:             return %returnhash;
                   2356:         }
1.1009    raeburn  2357:         my $i;
                   2358:         for ($i=0;$i<=$#what;$i++) {
                   2359: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2360:         }
1.70      www      2361:     }
                   2362:     return %returnhash;
1.1       albertel 2363: }
                   2364: 
1.617     albertel 2365: # ---------------------------------------------------------- Get a studentphoto
                   2366: sub studentphoto {
                   2367:     my ($udom,$unam,$ext) = @_;
                   2368:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2369:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2370:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2371:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2372:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2373:             } else {
                   2374:                 my ($result,$perm_reqd)=
1.707     albertel 2375: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2376:                 if ($result eq 'ok') {
                   2377:                     if (!($perm_reqd eq 'yes')) {
                   2378:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2379:                     }
                   2380:                 }
                   2381:             }
                   2382:         }
                   2383:     } else {
                   2384:         my ($result,$perm_reqd) = 
1.707     albertel 2385: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2386:         if ($result eq 'ok') {
                   2387:             if (!($perm_reqd eq 'yes')) {
                   2388:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2389:             }
                   2390:         }
                   2391:     }
                   2392:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2393: }
                   2394: 
                   2395: sub retrievestudentphoto {
                   2396:     my ($udom,$unam,$ext,$type) = @_;
                   2397:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2398:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2399:     if ($ret eq 'ok') {
                   2400:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2401:         if ($type eq 'thumbnail') {
                   2402:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2403:         }
                   2404:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2405:         return $tokenurl;
                   2406:     } else {
                   2407:         if ($type eq 'thumbnail') {
                   2408:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2409:         } else { 
                   2410:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2411:         }
1.617     albertel 2412:     }
                   2413: }
                   2414: 
1.263     www      2415: # -------------------------------------------------------------------- New chat
                   2416: 
                   2417: sub chatsend {
1.724     raeburn  2418:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2419:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2420:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2421:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2422:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2423: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2424: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2425: }
                   2426: 
                   2427: # ------------------------------------------ Find current version of a resource
                   2428: 
                   2429: sub getversion {
                   2430:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2431:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2432:     return &currentversion(&filelocation('',$fname));
                   2433: }
                   2434: 
                   2435: sub currentversion {
                   2436:     my $fname=shift;
                   2437:     my $author=$fname;
                   2438:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2439:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2440:     my $home=&homeserver($uname,$udom);
1.292     www      2441:     if ($home eq 'no_host') { 
                   2442:         return -1; 
                   2443:     }
1.1112    www      2444:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2445:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2446: 	return -1;
                   2447:     }
1.1112    www      2448:     return $answer;
1.263     www      2449: }
                   2450: 
1.1111    www      2451: #
                   2452: # Return special version number of resource if set by override, empty otherwise
                   2453: #
                   2454: sub usedversion {
                   2455:     my $fname=shift;
                   2456:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2457:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2458:     if ($urlversion) { return $urlversion; }
                   2459:     return '';
                   2460: }
                   2461: 
1.1       albertel 2462: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2463: 
1.1       albertel 2464: sub subscribe {
                   2465:     my $fname=shift;
1.761     raeburn  2466:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2467:     $fname=~s/[\n\r]//g;
1.1       albertel 2468:     my $author=$fname;
                   2469:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2470:     my ($udom,$uname)=split(/\//,$author);
                   2471:     my $home=homeserver($uname,$udom);
1.335     albertel 2472:     if ($home eq 'no_host') {
                   2473:         return 'not_found';
1.1       albertel 2474:     }
                   2475:     my $answer=reply("sub:$fname",$home);
1.64      www      2476:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2477: 	$answer.=' by '.$home;
                   2478:     }
1.1       albertel 2479:     return $answer;
                   2480: }
                   2481:     
1.8       www      2482: # -------------------------------------------------------------- Replicate file
                   2483: 
                   2484: sub repcopy {
                   2485:     my $filename=shift;
1.23      www      2486:     $filename=~s/\/+/\//g;
1.1142    raeburn  2487:     my $londocroot = $perlvar{'lonDocRoot'};
                   2488:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2489:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2490:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2491: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2492: 	return &repcopy_userfile($filename);
                   2493:     }
1.532     albertel 2494:     $filename=~s/[\n\r]//g;
1.8       www      2495:     my $transname="$filename.in.transfer";
1.828     www      2496: # FIXME: this should flock
1.607     raeburn  2497:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2498:     my $remoteurl=subscribe($filename);
1.64      www      2499:     if ($remoteurl =~ /^con_lost by/) {
                   2500: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2501:            return 'unavailable';
1.8       www      2502:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2503: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2504: 	   return 'not_found';
1.64      www      2505:     } elsif ($remoteurl =~ /^rejected by/) {
                   2506: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2507:            return 'forbidden';
1.20      www      2508:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2509:            return 'ok';
1.8       www      2510:     } else {
1.290     www      2511:         my $author=$filename;
                   2512:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2513:         my ($udom,$uname)=split(/\//,$author);
                   2514:         my $home=homeserver($uname,$udom);
                   2515:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2516:            my @parts=split(/\//,$filename);
                   2517:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2518:            if ($path ne "$londocroot/res") {
1.8       www      2519:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2520: 	       return 'bad_request';
1.8       www      2521:            }
                   2522:            my $count;
                   2523:            for ($count=5;$count<$#parts;$count++) {
                   2524:                $path.="/$parts[$count]";
                   2525:                if ((-e $path)!=1) {
                   2526: 		   mkdir($path,0777);
                   2527:                }
                   2528:            }
                   2529:            my $ua=new LWP::UserAgent;
                   2530:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2531:            my $response=$ua->request($request,$transname);
                   2532:            if ($response->is_error()) {
                   2533: 	       unlink($transname);
                   2534:                my $message=$response->status_line;
1.672     albertel 2535:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2536:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2537:                return 'unavailable';
1.8       www      2538:            } else {
1.16      www      2539: 	       if ($remoteurl!~/\.meta$/) {
                   2540:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2541:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2542:                   if ($mresponse->is_error()) {
                   2543: 		      unlink($filename.'.meta');
                   2544:                       &logthis(
1.672     albertel 2545:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2546:                   }
                   2547: 	       }
1.8       www      2548:                rename($transname,$filename);
1.607     raeburn  2549:                return 'ok';
1.8       www      2550:            }
1.290     www      2551:        }
1.8       www      2552:     }
1.330     www      2553: }
                   2554: 
                   2555: # ------------------------------------------------ Get server side include body
                   2556: sub ssi_body {
1.381     albertel 2557:     my ($filelink,%form)=@_;
1.606     matthew  2558:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2559:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2560:     }
1.953     www      2561:     my $output='';
                   2562:     my $response;
1.980     raeburn  2563:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2564:        ($output,$response)=&externalssi($filelink);
1.953     www      2565:     } else {
1.1004    droeschl 2566:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2567:        $filelink .= 'inhibitmenu=yes';
1.953     www      2568:        ($output,$response)=&ssi($filelink,%form);
                   2569:     }
1.778     albertel 2570:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2571:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2572:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2573:     if (wantarray) {
                   2574:         return ($output, $response);
                   2575:     } else {
                   2576:         return $output;
                   2577:     }
1.8       www      2578: }
                   2579: 
1.15      www      2580: # --------------------------------------------------------- Server Side Include
                   2581: 
1.782     albertel 2582: sub absolute_url {
                   2583:     my ($host_name) = @_;
                   2584:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2585:     if ($host_name eq '') {
                   2586: 	$host_name = $ENV{'SERVER_NAME'};
                   2587:     }
                   2588:     return $protocol.$host_name;
                   2589: }
                   2590: 
1.942     foxr     2591: #
                   2592: #   Server side include.
                   2593: # Parameters:
                   2594: #  fn     Possibly encrypted resource name/id.
                   2595: #  form   Hash that describes how the rendering should be done
                   2596: #         and other things.
1.944     foxr     2597: # Returns:
1.950     raeburn  2598: #   Scalar context: The content of the response.
                   2599: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2600: #     
1.15      www      2601: sub ssi {
                   2602: 
1.944     foxr     2603:     my ($fn,%form)=@_;
1.15      www      2604:     my $ua=new LWP::UserAgent;
1.23      www      2605:     my $request;
1.711     albertel 2606: 
                   2607:     $form{'no_update_last_known'}=1;
1.895     albertel 2608:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2609:     if (%form) {
1.782     albertel 2610:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2611:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2612:     } else {
1.782     albertel 2613:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2614:     }
                   2615: 
1.15      www      2616:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2617:     my $response= $ua->request($request);
1.944     foxr     2618:     if (wantarray) {
1.1172.2.3  raeburn  2619: 	return ($response->content, $response);
1.944     foxr     2620:     } else {
1.1172.2.3  raeburn  2621: 	return $response->content;
1.942     foxr     2622:     }
1.324     www      2623: }
                   2624: 
                   2625: sub externalssi {
                   2626:     my ($url)=@_;
                   2627:     my $ua=new LWP::UserAgent;
                   2628:     my $request=new HTTP::Request('GET',$url);
                   2629:     my $response=$ua->request($request);
1.954     raeburn  2630:     if (wantarray) {
                   2631:         return ($response->content, $response);
                   2632:     } else {
                   2633:         return $response->content;
                   2634:     }
1.15      www      2635: }
1.254     www      2636: 
1.492     albertel 2637: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2638: 
                   2639: sub allowuploaded {
                   2640:     my ($srcurl,$url)=@_;
                   2641:     $url=&clutter(&declutter($url));
                   2642:     my $dir=$url;
                   2643:     $dir=~s/\/[^\/]+$//;
                   2644:     my %httpref=();
                   2645:     my $httpurl=&hreflocation('',$url);
                   2646:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2647:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2648: }
1.477     raeburn  2649: 
1.1172.2.13  raeburn  2650: #
                   2651: # Determine if the current user should be able to edit a particular resource,
                   2652: # when viewing in course context.
                   2653: # (a) When viewing resource used to determine if "Edit" item is included in
                   2654: #     Functions.
                   2655: # (b) When displaying folder contents in course editor, used to determine if
                   2656: #     "Edit" link will be displayed alongside resource.
                   2657: #
                   2658: #  input: six args -- filename (decluttered), course number, course domain,
                   2659: #                   url, symb (if registered) and group (if this is a group
                   2660: #                   item -- e.g., bulletin board, group page etc.).
                   2661: #  output: array of five scalars --
                   2662: #          $cfile -- url for file editing if editable on current server
                   2663: #          $home -- homeserver of resource (i.e., for author if published,
                   2664: #                                           or course if uploaded.).
                   2665: #          $switchserver --  1 if server switch will be needed.
                   2666: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2667: #          $forceview -- 1 if icon/link should be to go to view mode
                   2668: #
                   2669: 
                   2670: sub can_edit_resource {
                   2671:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2672:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2673: #
                   2674: # For aboutme pages user can only edit his/her own.
                   2675: #
                   2676:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2677:         my ($sdom,$sname) = ($1,$2);
                   2678:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2679:             $home = $env{'user.home'};
                   2680:             $cfile = $resurl;
                   2681:             if ($env{'form.forceedit'}) {
                   2682:                 $forceview = 1;
                   2683:             } else {
                   2684:                 $forceedit = 1;
                   2685:             }
                   2686:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2687:         } else {
                   2688:             return;
                   2689:         }
                   2690:     }
                   2691: 
                   2692:     if ($env{'request.course.id'}) {
                   2693:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2694:         if ($group ne '') {
                   2695: # if this is a group homepage or group bulletin board, check group privs
                   2696:             my $allowed = 0;
                   2697:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2698:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2699:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2700:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2701:                     $allowed = 1;
                   2702:                 }
                   2703:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2704:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2705:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2706:                     $allowed = 1;
                   2707:                 }
                   2708:             }
                   2709:             if ($allowed) {
                   2710:                 $home=&homeserver($cnum,$cdom);
                   2711:                 if ($env{'form.forceedit'}) {
                   2712:                     $forceview = 1;
                   2713:                 } else {
                   2714:                     $forceedit = 1;
                   2715:                 }
                   2716:                 $cfile = $resurl;
                   2717:             } else {
                   2718:                 return;
                   2719:             }
                   2720:         } else {
1.1172.2.15  raeburn  2721:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2722:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2723:                     return;
                   2724:                 }
                   2725:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2726: #
                   2727: # No edit allowed where CC has switched to student role.
                   2728: #
                   2729:                 return;
                   2730:             }
                   2731:         }
                   2732:     }
                   2733: 
                   2734:     if ($file ne '') {
                   2735:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2736:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2737:                 $uploaded = 1;
                   2738:                 $incourse = 1;
                   2739:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2740:                     $cfile = &hreflocation('',$file);
                   2741:                     if ($env{'form.forceedit'}) {
                   2742:                         $forceview = 1;
                   2743:                     } else {
                   2744:                         $forceedit = 1;
                   2745:                     }
                   2746:                 }
                   2747:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2748:                 $incourse = 1;
                   2749:                 if ($env{'form.forceedit'}) {
                   2750:                     $forceview = 1;
                   2751:                 } else {
                   2752:                     $forceedit = 1;
                   2753:                 }
                   2754:                 $cfile = $resurl;
                   2755:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2756:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2757:                     $incourse = 1;
                   2758:                     if ($env{'form.forceedit'}) {
                   2759:                         $forceview = 1;
                   2760:                     } else {
                   2761:                         $forceedit = 1;
                   2762:                     }
                   2763:                     $cfile = $resurl;
                   2764:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2765:                     $incourse = 1;
                   2766:                     $cfile = $resurl.'/smpedit';
                   2767:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2768:                     $incourse = 1;
                   2769:                     if ($env{'form.forceedit'}) {
                   2770:                         $forceview = 1;
                   2771:                     } else {
                   2772:                         $forceedit = 1;
                   2773:                     }
                   2774:                     $cfile = $resurl;
1.1172.2.15  raeburn  2775:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2776:                     $incourse = 1;
                   2777:                     if ($env{'form.forceedit'}) {
                   2778:                         $forceview = 1;
                   2779:                     } else {
                   2780:                         $forceedit = 1;
                   2781:                     }
                   2782:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2783:                 }
                   2784:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2785:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2786:                 if (&is_on_map($template)) {
                   2787:                     $incourse = 1;
                   2788:                     $forceview = 1;
                   2789:                     $cfile = $template;
                   2790:                 }
                   2791:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   2792:                     $incourse = 1;
                   2793:                     if ($env{'form.forceedit'}) {
                   2794:                         $forceview = 1;
                   2795:                     } else {
                   2796:                         $forceedit = 1;
                   2797:                     }
                   2798:                     $cfile = $resurl;
                   2799:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   2800:                 $incourse = 1;
                   2801:                 $forceview = 1;
                   2802:                 if ($symb) {
                   2803:                     my ($map,$id,$res)=&decode_symb($symb);
                   2804:                     $env{'request.symb'} = $symb;
                   2805:                     $cfile = &clutter($res);
                   2806:                 } else {
                   2807:                     $cfile = $env{'form.suppurl'};
                   2808:                     $cfile =~ s{^http://}{};
                   2809:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   2810:                 }
                   2811:             }
                   2812:         }
                   2813:         if ($uploaded || $incourse) {
                   2814:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  2815:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  2816:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   2817:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   2818:             # Check that the user has permission to edit this resource
                   2819:             my $setpriv = 1;
                   2820:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   2821:             if (defined($cfudom)) {
                   2822:                 $home=&homeserver($cfuname,$cfudom);
                   2823:                 $cfile=$file;
                   2824:             }
                   2825:         }
                   2826:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   2827:             (($home ne '') && ($home ne 'no_host'))) {
                   2828:             my @ids=&current_machine_ids();
                   2829:             unless (grep(/^\Q$home\E$/,@ids)) {
                   2830:                 $switchserver=1;
                   2831:             }
                   2832:         }
                   2833:     }
                   2834:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2835: }
                   2836: 
                   2837: sub is_course_upload {
                   2838:     my ($file,$cnum,$cdom) = @_;
                   2839:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   2840:     $uploadpath =~ s{^\/}{};
                   2841:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   2842:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   2843:         return 1;
                   2844:     }
                   2845:     return;
                   2846: }
                   2847: 
                   2848: sub in_course {
                   2849:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   2850:     if ($hideprivileged) {
                   2851:         my $skipuser;
1.1172.2.23! raeburn  2852:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
        !          2853:         my @possdoms = ($cdom);
        !          2854:         if ($coursehash{'checkforpriv'}) {
        !          2855:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
        !          2856:         }
        !          2857:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  2858:             $skipuser = 1;
                   2859:             if ($coursehash{'nothideprivileged'}) {
                   2860:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2861:                     my $user;
                   2862:                     if ($item =~ /:/) {
                   2863:                         $user = $item;
                   2864:                     } else {
                   2865:                         $user = join(':',split(/[\@]/,$item));
                   2866:                     }
                   2867:                     if ($user eq $uname.':'.$udom) {
                   2868:                         undef($skipuser);
                   2869:                         last;
                   2870:                     }
                   2871:                 }
                   2872:             }
                   2873:             if ($skipuser) {
                   2874:                 return 0;
                   2875:             }
                   2876:         }
                   2877:     }
                   2878:     $type ||= 'any';
                   2879:     if (!defined($cdom) || !defined($cnum)) {
                   2880:         my $cid  = $env{'request.course.id'};
                   2881:         $cdom = $env{'course.'.$cid.'.domain'};
                   2882:         $cnum = $env{'course.'.$cid.'.num'};
                   2883:     }
                   2884:     my $typesref;
                   2885:     if (($type eq 'any') || ($type eq 'all')) {
                   2886:         $typesref = ['active','previous','future'];
                   2887:     } elsif ($type eq 'previous' || $type eq 'future') {
                   2888:         $typesref = [$type];
                   2889:     }
                   2890:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   2891:                               $typesref,undef,[$cdom]);
                   2892:     my ($tmp) = keys(%roles);
                   2893:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   2894:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   2895:     if (@course_roles > 0) {
                   2896:         return 1;
                   2897:     }
                   2898:     return 0;
                   2899: }
                   2900: 
1.478     albertel 2901: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2902: # input: action, courseID, current domain, intended
1.637     raeburn  2903: #        path to file, source of file, instruction to parse file for objects,
                   2904: #        ref to hash for embedded objects,
                   2905: #        ref to hash for codebase of java objects.
1.1095    raeburn  2906: #        reference to scalar to accommodate mime type determined
                   2907: #          from File::MMagic if $parser = parse.
1.637     raeburn  2908: #
1.485     raeburn  2909: # output: url to file (if action was uploaddoc), 
                   2910: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2911: #
1.478     albertel 2912: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2913: # course.
1.477     raeburn  2914: #
1.478     albertel 2915: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2916: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2917: #          course's home server.
1.477     raeburn  2918: #
1.478     albertel 2919: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2920: #          be copied from $source (current location) to 
                   2921: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2922: #         and will then be copied to
                   2923: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2924: #         course's home server.
1.485     raeburn  2925: #
1.481     raeburn  2926: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2927: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2928: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2929: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2930: #         in course's home server.
1.637     raeburn  2931: #
1.477     raeburn  2932: 
                   2933: sub process_coursefile {
1.1095    raeburn  2934:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2935:         $mimetype)=@_;
1.477     raeburn  2936:     my $fetchresult;
1.638     albertel 2937:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2938:     if ($action eq 'propagate') {
1.638     albertel 2939:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2940: 			     $home);
1.481     raeburn  2941:     } else {
1.477     raeburn  2942:         my $fpath = '';
                   2943:         my $fname = $file;
1.478     albertel 2944:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2945:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2946:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2947:         if ($action eq 'copy') {
                   2948:             if ($source eq '') {
                   2949:                 $fetchresult = 'no source file';
                   2950:                 return $fetchresult;
                   2951:             } else {
                   2952:                 my $destination = $filepath.'/'.$fname;
                   2953:                 rename($source,$destination);
                   2954:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2955:                                  $home);
1.481     raeburn  2956:             }
                   2957:         } elsif ($action eq 'uploaddoc') {
                   2958:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2959:             print $fh $env{'form.'.$source};
1.481     raeburn  2960:             close($fh);
1.637     raeburn  2961:             if ($parser eq 'parse') {
1.1024    raeburn  2962:                 my $mm = new File::MMagic;
1.1095    raeburn  2963:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2964:                 if ($type eq 'text/html') {
1.1024    raeburn  2965:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2966:                     unless ($parse_result eq 'ok') {
                   2967:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2968:                     }
1.637     raeburn  2969:                 }
1.1095    raeburn  2970:                 if (ref($mimetype)) {
                   2971:                     $$mimetype = $type;
                   2972:                 } 
1.637     raeburn  2973:             }
1.477     raeburn  2974:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2975:                                  $home);
1.481     raeburn  2976:             if ($fetchresult eq 'ok') {
                   2977:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2978:             } else {
                   2979:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2980:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2981:                 return '/adm/notfound.html';
                   2982:             }
1.477     raeburn  2983:         }
                   2984:     }
1.485     raeburn  2985:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2986:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2987:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2988:     }
                   2989:     return $fetchresult;
                   2990: }
                   2991: 
1.637     raeburn  2992: sub build_filepath {
                   2993:     my ($fpath) = @_;
                   2994:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2995:     unless ($fpath eq '') {
                   2996:         my @parts=split('/',$fpath);
                   2997:         foreach my $part (@parts) {
                   2998:             $filepath.= '/'.$part;
                   2999:             if ((-e $filepath)!=1) {
                   3000:                 mkdir($filepath,0777);
                   3001:             }
                   3002:         }
                   3003:     }
                   3004:     return $filepath;
                   3005: }
                   3006: 
                   3007: sub store_edited_file {
1.638     albertel 3008:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3009:     my $file = $primary_url;
                   3010:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3011:     my $fpath = '';
                   3012:     my $fname = $file;
                   3013:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3014:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3015:     my $filepath = &build_filepath($fpath);
                   3016:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3017:     print $fh $content;
                   3018:     close($fh);
1.638     albertel 3019:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3020:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3021: 			  $home);
1.637     raeburn  3022:     if ($$fetchresult eq 'ok') {
                   3023:         return '/uploaded/'.$fpath.'/'.$fname;
                   3024:     } else {
1.638     albertel 3025:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3026: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3027:         return '/adm/notfound.html';
                   3028:     }
                   3029: }
                   3030: 
1.531     albertel 3031: sub clean_filename {
1.831     albertel 3032:     my ($fname,$args)=@_;
1.315     www      3033: # Replace Windows backslashes by forward slashes
1.257     www      3034:     $fname=~s/\\/\//g;
1.831     albertel 3035:     if (!$args->{'keep_path'}) {
                   3036:         # Get rid of everything but the actual filename
                   3037: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3038:     }
1.315     www      3039: # Replace spaces by underscores
                   3040:     $fname=~s/\s+/\_/g;
                   3041: # Replace all other weird characters by nothing
1.831     albertel 3042:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3043: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3044: # numbers
                   3045:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3046:     return $fname;
                   3047: }
1.1051    raeburn  3048: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3049: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3050: # image with the same aspect ratio as the original, but with dimensions which do 
                   3051: # not exceed $resizewidth and $resizeheight.
                   3052:  
1.984     neumanie 3053: sub resizeImage {
1.1051    raeburn  3054:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3055:     my $ima = Image::Magick->new;
                   3056:     my $resized;
                   3057:     if (-e $img_path) {
                   3058:         $ima->Read($img_path);
                   3059:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3060:             my $width = $ima->Get('width');
                   3061:             my $height = $ima->Get('height');
                   3062:             if ($width > $resizewidth) {
                   3063: 	        my $factor = $width/$resizewidth;
                   3064:                 my $newheight = $height/$factor;
                   3065:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3066:                 $resized = 1;
                   3067:             }
                   3068:         }
                   3069:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3070:             my $width = $ima->Get('width');
                   3071:             my $height = $ima->Get('height');
                   3072:             if ($height > $resizeheight) {
                   3073:                 my $factor = $height/$resizeheight;
                   3074:                 my $newwidth = $width/$factor;
                   3075:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3076:                 $resized = 1;
                   3077:             }
                   3078:         }
                   3079:         if ($resized) {
                   3080:             $ima->Write($img_path);
                   3081:         }
                   3082:     }
                   3083:     return;
1.977     amueller 3084: }
                   3085: 
1.608     albertel 3086: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3087: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3088: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3089: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3090: #                                    canceloverwrite, or ''. 
                   3091: #                   if 'coursedoc': upload to the current course
                   3092: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3093: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3094: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3095: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3096: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3097: #        $allfiles - reference to hash for embedded objects
                   3098: #        $codebase - reference to hash for codebase of java objects
                   3099: #        $desuname - username for permanent storage of uploaded file
                   3100: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3101: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3102: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3103: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3104: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3105: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3106: #                    from File::MMagic.
1.858     raeburn  3107: # 
1.686     albertel 3108: # output: url of file in userspace, or error: <message> 
                   3109: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3110: 
1.531     albertel 3111: sub userfileupload {
1.1090    raeburn  3112:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3113:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3114:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3115:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3116:     $fname=&clean_filename($fname);
1.1090    raeburn  3117:     # See if there is anything left
1.257     www      3118:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3119:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3120:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3121:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3122:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3123:         my $now = time;
1.1090    raeburn  3124:         my $filepath;
1.1095    raeburn  3125:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3126:              $filepath = 'tmp/helprequests/'.$now;
                   3127:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3128:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3129:                          '_'.$env{'user.domain'}.'/pending';
                   3130:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3131:             my ($docuname,$docudom);
                   3132:             if ($destudom) {
                   3133:                 $docudom = $destudom;
                   3134:             } else {
                   3135:                 $docudom = $env{'user.domain'};
                   3136:             }
                   3137:             if ($destuname) {
                   3138:                 $docuname = $destuname;
                   3139:             } else {
                   3140:                 $docuname = $env{'user.name'};
                   3141:             }
                   3142:             if (exists($env{'form.group'})) {
                   3143:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3144:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3145:             }
                   3146:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3147:             if ($context eq 'canceloverwrite') {
                   3148:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3149:                 if (-e  $tempfile) {
                   3150:                     my @info = stat($tempfile);
                   3151:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3152:                         unlink($tempfile);
                   3153:                     }
                   3154:                 }
                   3155:                 return;
1.523     raeburn  3156:             }
                   3157:         }
1.1090    raeburn  3158:         # Create the directory if not present
1.741     raeburn  3159:         my @parts=split(/\//,$filepath);
                   3160:         my $fullpath = $perlvar{'lonDaemons'};
                   3161:         for (my $i=0;$i<@parts;$i++) {
                   3162:             $fullpath .= '/'.$parts[$i];
                   3163:             if ((-e $fullpath)!=1) {
                   3164:                 mkdir($fullpath,0777);
                   3165:             }
                   3166:         }
                   3167:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3168:         print $fh $env{'form.'.$formname};
                   3169:         close($fh);
1.1090    raeburn  3170:         if ($context eq 'existingfile') {
                   3171:             my @info = stat($fullpath.'/'.$fname);
                   3172:             return ($fullpath.'/'.$fname,$info[9]);
                   3173:         } else {
                   3174:             return $fullpath.'/'.$fname;
                   3175:         }
1.523     raeburn  3176:     }
1.995     raeburn  3177:     if ($subdir eq 'scantron') {
                   3178:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3179:     } else {
1.995     raeburn  3180:         $fname="$subdir/$fname";
                   3181:     }
1.1090    raeburn  3182:     if ($context eq 'coursedoc') {
1.638     albertel 3183: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3184: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3185:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3186:             return &finishuserfileupload($docuname,$docudom,
                   3187: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3188: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3189:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3190:         } else {
1.1172.2.21  raeburn  3191:             if ($env{'form.folder'}) {
                   3192:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3193:             }
1.638     albertel 3194:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3195: 				       $fname,$formname,$parser,
1.1095    raeburn  3196: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3197:         }
1.719     banghart 3198:     } elsif (defined($destuname)) {
                   3199:         my $docuname=$destuname;
                   3200:         my $docudom=$destudom;
1.860     raeburn  3201: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3202: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3203:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3204:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3205:     } else {
1.638     albertel 3206:         my $docuname=$env{'user.name'};
                   3207:         my $docudom=$env{'user.domain'};
1.1172.2.23! raeburn  3208:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3209:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3210:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3211:         }
1.860     raeburn  3212: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3213: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3214:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3215:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3216:     }
1.271     www      3217: }
                   3218: 
                   3219: sub finishuserfileupload {
1.860     raeburn  3220:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3221:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3222:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3223:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3224:   
1.860     raeburn  3225:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3226:     $file=$fname;
                   3227:     if ($fname=~m|/|) {
                   3228:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3229: 	$path.=$fnamepath.'/';
                   3230:     }
1.259     www      3231:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3232:     my $count;
                   3233:     for ($count=4;$count<=$#parts;$count++) {
                   3234:         $filepath.="/$parts[$count]";
                   3235:         if ((-e $filepath)!=1) {
                   3236: 	    mkdir($filepath,0777);
                   3237:         }
                   3238:     }
1.984     neumanie 3239: 
1.258     www      3240: # Save the file
                   3241:     {
1.701     albertel 3242: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3243: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3244: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3245: 	    return '/adm/notfound.html';
                   3246: 	}
1.1090    raeburn  3247:         if ($context eq 'overwrite') {
1.1117    foxr     3248:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3249:             my $target = $filepath.'/'.$file;
                   3250:             if (-e $source) {
                   3251:                 my @info = stat($source);
                   3252:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3253:                     unless (&File::Copy::move($source,$target)) {
                   3254:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3255:                         return "Moving from $source failed";
                   3256:                     }
                   3257:                 } else {
                   3258:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3259:                 }
                   3260:             } else {
                   3261:                 return "Temporary file: $source missing";
                   3262:             }
                   3263:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3264: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3265: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3266: 	    return '/adm/notfound.html';
                   3267: 	}
1.570     albertel 3268: 	close(FH);
1.1051    raeburn  3269:         if ($resizewidth && $resizeheight) {
                   3270:             my $mm = new File::MMagic;
                   3271:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3272:             if ($mime_type =~ m{^image/}) {
                   3273: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3274:             }  
1.977     amueller 3275: 	}
1.258     www      3276:     }
1.1152    raeburn  3277:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3278:         if (ref($mimetype)) {
                   3279:             if ($$mimetype eq '') {
                   3280:                 my $mm = new File::MMagic;
                   3281:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3282:                 $$mimetype = $type;
                   3283:             }
                   3284:         }
                   3285:     }
1.637     raeburn  3286:     if ($parser eq 'parse') {
1.1152    raeburn  3287:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3288:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3289:                                                        $allfiles,$codebase);
                   3290:             unless ($parse_result eq 'ok') {
                   3291:                 &logthis('Failed to parse '.$filepath.$file.
                   3292: 	   	         ' for embedded media: '.$parse_result); 
                   3293:             }
1.637     raeburn  3294:         }
                   3295:     }
1.860     raeburn  3296:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3297:         my $input = $filepath.'/'.$file;
                   3298:         my $output = $filepath.'/'.'tn-'.$file;
                   3299:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3300:         system("convert -sample $thumbsize $input $output");
                   3301:         if (-e $filepath.'/'.'tn-'.$file) {
                   3302:             $fetchthumb  = 1; 
                   3303:         }
                   3304:     }
1.858     raeburn  3305:  
1.259     www      3306: # Notify homeserver to grep it
                   3307: #
1.984     neumanie 3308:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3309:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3310:     if ($fetchresult eq 'ok') {
1.860     raeburn  3311:         if ($fetchthumb) {
                   3312:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3313:             if ($thumbresult ne 'ok') {
                   3314:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3315:                          $docuhome.': '.$thumbresult);
                   3316:             }
                   3317:         }
1.259     www      3318: #
1.258     www      3319: # Return the URL to it
1.494     albertel 3320:         return '/uploaded/'.$path.$file;
1.263     www      3321:     } else {
1.494     albertel 3322:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3323: 		 ': '.$fetchresult);
1.263     www      3324:         return '/adm/notfound.html';
1.858     raeburn  3325:     }
1.493     albertel 3326: }
                   3327: 
1.637     raeburn  3328: sub extract_embedded_items {
1.961     raeburn  3329:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3330:     my @state = ();
1.1164    raeburn  3331:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3332:     my %javafiles = (
                   3333:                       codebase => '',
                   3334:                       code => '',
                   3335:                       archive => ''
                   3336:                     );
                   3337:     my %mediafiles = (
                   3338:                       src => '',
                   3339:                       movie => '',
                   3340:                      );
1.648     raeburn  3341:     my $p;
                   3342:     if ($content) {
                   3343:         $p = HTML::LCParser->new($content);
                   3344:     } else {
1.961     raeburn  3345:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3346:     }
1.641     albertel 3347:     while (my $t=$p->get_token()) {
1.640     albertel 3348: 	if ($t->[0] eq 'S') {
                   3349: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3350: 	    push(@state, $tagname);
1.648     raeburn  3351:             if (lc($tagname) eq 'allow') {
                   3352:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3353:             }
1.640     albertel 3354: 	    if (lc($tagname) eq 'img') {
                   3355: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3356: 	    }
1.886     albertel 3357: 	    if (lc($tagname) eq 'a') {
                   3358: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3359: 	    }
1.645     raeburn  3360:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3361:                 my $src;
1.645     raeburn  3362:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3363:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3364:                 } else {
1.1164    raeburn  3365:                     if ($attr->{'src'} ne '') {
                   3366:                         $src = $attr->{'src'};
                   3367:                         &add_filetype($allfiles,$src,'src');
                   3368:                     }
                   3369:                 }
                   3370:                 my $text = $p->get_trimmed_text();
                   3371:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3372:                     my @swfargs = split(/,/,$1);
                   3373:                     foreach my $item (@swfargs) {
                   3374:                         $item =~ s/["']//g;
                   3375:                         $item =~ s/^\s+//;
                   3376:                         $item =~ s/\s+$//;
                   3377:                     }
                   3378:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3379:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3380:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3381:                         } else {
                   3382:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3383:                         }
                   3384:                     }
1.645     raeburn  3385:                 }
                   3386:             }
                   3387:             if (lc($tagname) eq 'link') {
                   3388:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3389:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3390:                 }
                   3391:             }
1.640     albertel 3392: 	    if (lc($tagname) eq 'object' ||
                   3393: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3394: 		foreach my $item (keys(%javafiles)) {
                   3395: 		    $javafiles{$item} = '';
                   3396: 		}
1.1164    raeburn  3397:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3398:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3399:                 }
1.640     albertel 3400: 	    }
                   3401: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3402: 		my $name = lc($attr->{'name'});
                   3403: 		foreach my $item (keys(%javafiles)) {
                   3404: 		    if ($name eq $item) {
                   3405: 			$javafiles{$item} = $attr->{'value'};
                   3406: 			last;
                   3407: 		    }
                   3408: 		}
1.1164    raeburn  3409:                 my $pathfrom;
1.640     albertel 3410: 		foreach my $item (keys(%mediafiles)) {
                   3411: 		    if ($name eq $item) {
1.1164    raeburn  3412:                         $pathfrom = $attr->{'value'};
                   3413:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3414: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3415: 			last;
                   3416: 		    }
                   3417: 		}
1.1164    raeburn  3418:                 if ($name eq 'flashvars') {
                   3419:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3420:                 }
                   3421:                 if ($pathfrom ne '') {
                   3422:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3423:                                          $pathfrom);
                   3424:                 }
1.640     albertel 3425: 	    }
                   3426: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3427: 		foreach my $item (keys(%javafiles)) {
                   3428: 		    if ($attr->{$item}) {
                   3429: 			$javafiles{$item} = $attr->{$item};
                   3430: 			last;
                   3431: 		    }
                   3432: 		}
                   3433: 		foreach my $item (keys(%mediafiles)) {
                   3434: 		    if ($attr->{$item}) {
                   3435: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3436: 			last;
                   3437: 		    }
                   3438: 		}
1.1164    raeburn  3439:                 if (lc($tagname) eq 'embed') {
                   3440:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3441:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3442:                                              $attr->{'src'});
                   3443:                     }
                   3444:                 }
1.640     albertel 3445: 	    }
1.1164    raeburn  3446:             if ($t->[4] =~ m{/>$}) {
                   3447:                 pop(@state);  
                   3448:             }
1.640     albertel 3449: 	} elsif ($t->[0] eq 'E') {
                   3450: 	    my ($tagname) = ($t->[1]);
                   3451: 	    if ($javafiles{'codebase'} ne '') {
                   3452: 		$javafiles{'codebase'} .= '/';
                   3453: 	    }  
                   3454: 	    if (lc($tagname) eq 'applet' ||
                   3455: 		lc($tagname) eq 'object' ||
                   3456: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3457: 		) {
                   3458: 		foreach my $item (keys(%javafiles)) {
                   3459: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3460: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3461: 			&add_filetype($allfiles,$file,$item);
                   3462: 		    }
                   3463: 		}
                   3464: 	    } 
                   3465: 	    pop @state;
                   3466: 	}
                   3467:     }
1.1164    raeburn  3468:     foreach my $id (sort(keys(%flashvars))) {
                   3469:         if ($shockwave{$id} ne '') {
                   3470:             my @pairs = split(/\&/,$flashvars{$id});
                   3471:             foreach my $pair (@pairs) {
                   3472:                 my ($key,$value) = split(/\=/,$pair);
                   3473:                 if ($key eq 'thumb') {
                   3474:                     &add_filetype($allfiles,$value,$key);
                   3475:                 } elsif ($key eq 'content') {
                   3476:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3477:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3478:                     if ($ext ne '') {
                   3479:                         &add_filetype($allfiles,$path.$value,$ext);
                   3480:                     }
                   3481:                 }
                   3482:             }
                   3483:         }
                   3484:     }
1.637     raeburn  3485:     return 'ok';
                   3486: }
                   3487: 
1.639     albertel 3488: sub add_filetype {
                   3489:     my ($allfiles,$file,$type)=@_;
                   3490:     if (exists($allfiles->{$file})) {
                   3491: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3492: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3493: 	}
                   3494:     } else {
                   3495: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3496:     }
                   3497: }
                   3498: 
1.1164    raeburn  3499: sub embedded_dependency {
                   3500:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3501:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3502:         if (($identifier ne '') &&
                   3503:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3504:             ($pathfrom ne '')) {
                   3505:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3506:             foreach my $dep (@{$related->{$identifier}}) {
                   3507:                 &add_filetype($allfiles,$path.$dep,'object');
                   3508:             }
                   3509:         }
                   3510:     }
                   3511:     return;
                   3512: }
                   3513: 
1.493     albertel 3514: sub removeuploadedurl {
1.984     neumanie 3515:     my ($url)=@_;	
                   3516:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3517:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3518: }
                   3519: 
                   3520: sub removeuserfile {
                   3521:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3522:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3523:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3524:     if ($result eq 'ok') {	
1.798     raeburn  3525:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3526:             my $metafile = $fname.'.meta';
                   3527:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3528: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3529:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3530:             my $sqlresult = 
1.823     albertel 3531:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3532:                                         'portfolio_metadata',$group,
                   3533:                                         'delete');
1.798     raeburn  3534:         }
                   3535:     }
                   3536:     return $result;
1.257     www      3537: }
1.15      www      3538: 
1.530     albertel 3539: sub mkdiruserfile {
                   3540:     my ($docuname,$docudom,$dir)=@_;
                   3541:     my $home=&homeserver($docuname,$docudom);
                   3542:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3543: }
                   3544: 
1.531     albertel 3545: sub renameuserfile {
                   3546:     my ($docuname,$docudom,$old,$new)=@_;
                   3547:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3548:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3549:                         &escape("$old").':'.&escape("$new"),$home);
                   3550:     if ($result eq 'ok') {
                   3551:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3552:             my $oldmeta = $old.'.meta';
                   3553:             my $newmeta = $new.'.meta';
                   3554:             my $metaresult = 
                   3555:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3556: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3557:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3558:             my $sqlresult = 
1.823     albertel 3559:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3560:                                         'portfolio_metadata',$group,
                   3561:                                         'delete');
1.798     raeburn  3562:         }
                   3563:     }
                   3564:     return $result;
1.531     albertel 3565: }
                   3566: 
1.14      www      3567: # ------------------------------------------------------------------------- Log
                   3568: 
                   3569: sub log {
                   3570:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3571:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3572: }
                   3573: 
                   3574: # ------------------------------------------------------------------ Course Log
1.352     www      3575: #
                   3576: # This routine flushes several buffers of non-mission-critical nature
                   3577: #
1.157     www      3578: 
                   3579: sub flushcourselogs {
1.352     www      3580:     &logthis('Flushing log buffers');
                   3581: #
                   3582: # course logs
                   3583: # This is a log of all transactions in a course, which can be used
                   3584: # for data mining purposes
                   3585: #
                   3586: # It also collects the courseid database, which lists last transaction
                   3587: # times and course titles for all courseids
                   3588: #
                   3589:     my %courseidbuffer=();
1.921     raeburn  3590:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3591:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3592: 		          &escape($courselogs{$crsid}),
                   3593: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3594: 	    delete $courselogs{$crsid};
                   3595:         } else {
                   3596:             &logthis('Failed to flush log buffer for '.$crsid);
                   3597:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3598:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3599:                         " exceeded maximum size, deleting.</font>");
                   3600:                delete $courselogs{$crsid};
                   3601:             }
1.352     www      3602:         }
1.920     raeburn  3603:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3604:             'description' => $coursedescrbuf{$crsid},
                   3605:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3606:             'type'        => $coursetypebuf{$crsid},
                   3607:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3608:         };
1.191     harris41 3609:     }
1.352     www      3610: #
                   3611: # Write course id database (reverse lookup) to homeserver of courses 
                   3612: # Is used in pickcourse
                   3613: #
1.840     albertel 3614:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3615:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3616:                                     $courseidbuffer{$crs_home},
                   3617:                                     $crs_home,'timeonly');
1.352     www      3618:     }
                   3619: #
                   3620: # File accesses
                   3621: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3622: #
1.449     matthew  3623:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3624:         if ($entry =~ /___count$/) {
                   3625:             my ($dom,$name);
1.807     albertel 3626:             ($dom,$name,undef)=
1.811     albertel 3627: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3628:             if (! defined($dom) || $dom eq '' || 
                   3629:                 ! defined($name) || $name eq '') {
1.620     albertel 3630:                 my $cid = $env{'request.course.id'};
                   3631:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3632:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3633:             }
1.450     matthew  3634:             my $value = $accesshash{$entry};
                   3635:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3636:             my %temphash=($url => $value);
1.449     matthew  3637:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3638:             if ($result eq 'ok') {
                   3639:                 delete $accesshash{$entry};
                   3640:             }
                   3641:         } else {
1.811     albertel 3642:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3643:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3644:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3645:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3646:                 delete $accesshash{$entry};
                   3647:             }
1.185     www      3648:         }
1.191     harris41 3649:     }
1.352     www      3650: #
                   3651: # Roles
                   3652: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3653: #
1.800     albertel 3654:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3655:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3656: 	    split(/\:/,$entry);
                   3657:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3658:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3659:                 $rudom,$runame) eq 'ok') {
                   3660: 	    delete $userrolehash{$entry};
                   3661:         }
                   3662:     }
1.662     raeburn  3663: #
                   3664: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3665: #
                   3666:     my %domrolebuffer = ();
1.1000    raeburn  3667:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3668:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3669:         if ($domrolebuffer{$rudom}) {
                   3670:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3671:                       '='.&escape($domainrolehash{$entry});
                   3672:         } else {
                   3673:             $domrolebuffer{$rudom}.=&escape($entry).
                   3674:                       '='.&escape($domainrolehash{$entry});
                   3675:         }
                   3676:         delete $domainrolehash{$entry};
                   3677:     }
                   3678:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3679: 	my %servers = &get_servers($dom,'library');
                   3680: 	foreach my $tryserver (keys(%servers)) {
                   3681: 	    unless (&reply('domroleput:'.$dom.':'.
                   3682: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3683: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3684: 	    }
1.662     raeburn  3685:         }
                   3686:     }
1.186     www      3687:     $dumpcount++;
1.157     www      3688: }
                   3689: 
                   3690: sub courselog {
                   3691:     my $what=shift;
1.158     www      3692:     $what=time.':'.$what;
1.620     albertel 3693:     unless ($env{'request.course.id'}) { return ''; }
                   3694:     $coursedombuf{$env{'request.course.id'}}=
                   3695:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3696:     $coursenumbuf{$env{'request.course.id'}}=
                   3697:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3698:     $coursehombuf{$env{'request.course.id'}}=
                   3699:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3700:     $coursedescrbuf{$env{'request.course.id'}}=
                   3701:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3702:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3703:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3704:     $courseownerbuf{$env{'request.course.id'}}=
                   3705:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3706:     $coursetypebuf{$env{'request.course.id'}}=
                   3707:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3708:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3709: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3710:     } else {
1.620     albertel 3711: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3712:     }
1.620     albertel 3713:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3714: 	&flushcourselogs();
                   3715:     }
1.158     www      3716: }
                   3717: 
                   3718: sub courseacclog {
                   3719:     my $fnsymb=shift;
1.620     albertel 3720:     unless ($env{'request.course.id'}) { return ''; }
                   3721:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3722:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3723:         $what.=':POST';
1.583     matthew  3724:         # FIXME: Probably ought to escape things....
1.800     albertel 3725: 	foreach my $key (keys(%env)) {
                   3726:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3727:                 my $formitem = $1;
                   3728:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3729:                     $what.=':'.$formitem.'='.$env{$key};
                   3730:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3731:                     $what.=':'.$formitem.'='.$env{$key};
                   3732:                 }
1.158     www      3733:             }
1.191     harris41 3734:         }
1.583     matthew  3735:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3736:         # FIXME: We should not be depending on a form parameter that someone
                   3737:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3738:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3739:             $what.= ':POST';
                   3740:             # FIXME: Probably ought to escape things....
                   3741:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3742:                                  'crsdiscuss') {
1.620     albertel 3743:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3744:             }
                   3745:         }
1.158     www      3746:     }
                   3747:     &courselog($what);
1.149     www      3748: }
                   3749: 
1.185     www      3750: sub countacc {
                   3751:     my $url=&declutter(shift);
1.458     matthew  3752:     return if (! defined($url) || $url eq '');
1.620     albertel 3753:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3754: #
                   3755: # Mark that this url was used in this course
                   3756: #
1.620     albertel 3757:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3758: #
                   3759: # Increase the access count for this resource in this child process
                   3760: #
1.281     www      3761:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3762:     $accesshash{$key}++;
1.185     www      3763: }
1.349     www      3764: 
1.361     www      3765: sub linklog {
                   3766:     my ($from,$to)=@_;
                   3767:     $from=&declutter($from);
                   3768:     $to=&declutter($to);
                   3769:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3770:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3771: }
1.1160    www      3772: 
                   3773: sub statslog {
                   3774:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3775:     if ($users<2) { return; }
                   3776:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3777:             'course'       => $env{'request.course.id'},
                   3778:             'sections'     => '"all"',
                   3779:             'num_students' => $users,
                   3780:             'part'         => $part,
                   3781:             'symb'         => $symb,
                   3782:             'mean_tries'   => $av_attempts,
                   3783:             'deg_of_diff'  => $degdiff});
                   3784:     foreach my $key (keys(%dynstore)) {
                   3785:         $accesshash{$key}=$dynstore{$key};
                   3786:     }
                   3787: }
1.361     www      3788:   
1.349     www      3789: sub userrolelog {
                   3790:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3791:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3792:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3793:        $userrolehash
                   3794:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3795:                     =$tend.':'.$tstart;
1.662     raeburn  3796:     }
1.1169    droeschl 3797:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3798:        $userrolehash
                   3799:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3800:                     =$tend.':'.$tstart;
                   3801:     }
1.1169    droeschl 3802:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3803:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3804:        $domainrolehash
                   3805:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3806:                     = $tend.':'.$tstart;
                   3807:     }
1.351     www      3808: }
                   3809: 
1.957     raeburn  3810: sub courserolelog {
                   3811:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  3812:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3813:         my $cdom = $1;
                   3814:         my $cnum = $2;
                   3815:         my $sec = $3;
                   3816:         my $namespace = 'rolelog';
                   3817:         my %storehash = (
                   3818:                            role    => $trole,
                   3819:                            start   => $tstart,
                   3820:                            end     => $tend,
                   3821:                            selfenroll => $selfenroll,
                   3822:                            context    => $context,
                   3823:                         );
                   3824:         if ($trole eq 'gr') {
                   3825:             $namespace = 'groupslog';
                   3826:             $storehash{'group'} = $sec;
                   3827:         } else {
                   3828:             $storehash{'section'} = $sec;
                   3829:         }
                   3830:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   3831:                    $domain,$cnum,$cdom);
                   3832:         if (($trole ne 'st') || ($sec ne '')) {
                   3833:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3834:         }
                   3835:     }
                   3836:     return;
                   3837: }
                   3838: 
1.1172.2.9  raeburn  3839: sub domainrolelog {
                   3840:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3841:     if ($area =~ m{^/($match_domain)/$}) {
                   3842:         my $cdom = $1;
                   3843:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   3844:         my $namespace = 'rolelog';
                   3845:         my %storehash = (
                   3846:                            role    => $trole,
                   3847:                            start   => $tstart,
                   3848:                            end     => $tend,
                   3849:                            context => $context,
                   3850:                         );
                   3851:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   3852:                    $domain,$domconfiguser,$cdom);
                   3853:     }
                   3854:     return;
                   3855: 
                   3856: }
                   3857: 
                   3858: sub coauthorrolelog {
                   3859:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   3860:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   3861:         my $audom = $1;
                   3862:         my $auname = $2;
                   3863:         my $namespace = 'rolelog';
                   3864:         my %storehash = (
                   3865:                            role    => $trole,
                   3866:                            start   => $tstart,
                   3867:                            end     => $tend,
                   3868:                            context => $context,
                   3869:                         );
                   3870:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   3871:                    $domain,$auname,$audom);
                   3872:     }
                   3873:     return;
                   3874: }
                   3875: 
1.351     www      3876: sub get_course_adv_roles {
1.948     raeburn  3877:     my ($cid,$codes) = @_;
1.620     albertel 3878:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3879:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3880:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3881:     my %nothide=();
1.800     albertel 3882:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3883:         if ($user !~ /:/) {
                   3884: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3885:         } else {
                   3886:             $nothide{$user}=1;
                   3887:         }
1.470     www      3888:     }
1.1172.2.23! raeburn  3889:     my @possdoms = ($coursehash{'domain'});
        !          3890:     if ($coursehash{'checkforpriv'}) {
        !          3891:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
        !          3892:     }
1.351     www      3893:     my %returnhash=();
                   3894:     my %dumphash=
                   3895:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3896:     my $now=time;
1.997     raeburn  3897:     my %privileged;
1.1000    raeburn  3898:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3899: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3900:         if (($tstart) && ($tstart<0)) { next; }
                   3901:         if (($tend) && ($tend<$now)) { next; }
                   3902:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3903:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3904: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23! raeburn  3905:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  3906:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3907: 	if ($role eq 'cr') { next; }
1.948     raeburn  3908:         if ($codes) {
                   3909:             if ($section) { $role .= ':'.$section; }
                   3910:             if ($returnhash{$role}) {
                   3911:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3912:             } else {
                   3913:                 $returnhash{$role}=$username.':'.$domain;
                   3914:             }
1.351     www      3915:         } else {
1.988     raeburn  3916:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3917:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3918:             if ($returnhash{$key}) {
                   3919: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3920:             } else {
                   3921:                 $returnhash{$key}=$username.':'.$domain;
                   3922:             }
1.351     www      3923:         }
1.948     raeburn  3924:     }
1.400     www      3925:     return %returnhash;
                   3926: }
                   3927: 
                   3928: sub get_my_roles {
1.937     raeburn  3929:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3930:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3931:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3932:     my (%dumphash,%nothide);
1.1086    raeburn  3933:     if ($context eq 'userroles') {
1.1166    raeburn  3934:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3935:     } else {
1.1172.2.23! raeburn  3936:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3937:         if ($hidepriv) {
                   3938:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3939:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3940:                 if ($user !~ /:/) {
                   3941:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3942:                 } else {
                   3943:                     $nothide{$user} = 1;
                   3944:                 }
                   3945:             }
                   3946:         }
1.858     raeburn  3947:     }
1.400     www      3948:     my %returnhash=();
                   3949:     my $now=time;
1.999     raeburn  3950:     my %privileged;
1.800     albertel 3951:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3952:         my ($role,$tend,$tstart);
                   3953:         if ($context eq 'userroles') {
1.1149    raeburn  3954:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3955: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3956:         } else {
                   3957:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3958:         }
1.400     www      3959:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3960:         my $status = 'active';
1.939     raeburn  3961:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3962:             $status = 'previous';
                   3963:         } 
                   3964:         if (($tstart) && ($now<$tstart)) {
                   3965:             $status = 'future';
                   3966:         }
                   3967:         if (ref($types) eq 'ARRAY') {
                   3968:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3969:                 next;
                   3970:             } 
                   3971:         } else {
                   3972:             if ($status ne 'active') {
                   3973:                 next;
                   3974:             }
                   3975:         }
1.867     raeburn  3976:         my ($rolecode,$username,$domain,$section,$area);
                   3977:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  3978:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  3979:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3980:         } else {
                   3981:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3982:         }
1.832     raeburn  3983:         if (ref($roledoms) eq 'ARRAY') {
                   3984:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3985:                 next;
                   3986:             }
                   3987:         }
                   3988:         if (ref($roles) eq 'ARRAY') {
                   3989:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3990:                 if ($role =~ /^cr\//) {
                   3991:                     if (!grep(/^cr$/,@{$roles})) {
                   3992:                         next;
                   3993:                     }
1.1104    raeburn  3994:                 } elsif ($role =~ /^gr\//) {
                   3995:                     if (!grep(/^gr$/,@{$roles})) {
                   3996:                         next;
                   3997:                     }
1.922     raeburn  3998:                 } else {
                   3999:                     next;
                   4000:                 }
1.832     raeburn  4001:             }
1.867     raeburn  4002:         }
1.937     raeburn  4003:         if ($hidepriv) {
1.1172.2.23! raeburn  4004:             my @privroles = ('dc','su');
1.999     raeburn  4005:             if ($context eq 'userroles') {
1.1172.2.23! raeburn  4006:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4007:             } else {
1.1172.2.23! raeburn  4008:                 my $possdoms = [$domain];
        !          4009:                 if (ref($roledoms) eq 'ARRAY') {
        !          4010:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4011:                 }
1.1172.2.23! raeburn  4012:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4013:                     if (!$nothide{$username.':'.$domain}) {
                   4014:                         next;
                   4015:                     }
                   4016:                 }
1.937     raeburn  4017:             }
                   4018:         }
1.933     raeburn  4019:         if ($withsec) {
                   4020:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4021:                 $tstart.':'.$tend;
                   4022:         } else {
                   4023:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4024:         }
1.832     raeburn  4025:     }
1.373     www      4026:     return %returnhash;
1.399     www      4027: }
                   4028: 
                   4029: # ----------------------------------------------------- Frontpage Announcements
                   4030: #
                   4031: #
                   4032: 
                   4033: sub postannounce {
                   4034:     my ($server,$text)=@_;
1.844     albertel 4035:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4036:     unless ($text=~/\w/) { $text=''; }
                   4037:     return &reply('setannounce:'.&escape($text),$server);
                   4038: }
                   4039: 
                   4040: sub getannounce {
1.448     albertel 4041: 
                   4042:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4043: 	my $announcement='';
1.800     albertel 4044: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4045: 	close($fh);
1.399     www      4046: 	if ($announcement=~/\w/) { 
                   4047: 	    return 
                   4048:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4049:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4050: 	} else {
                   4051: 	    return '';
                   4052: 	}
                   4053:     } else {
                   4054: 	return '';
                   4055:     }
1.351     www      4056: }
1.353     www      4057: 
                   4058: # ---------------------------------------------------------- Course ID routines
                   4059: # Deal with domain's nohist_courseid.db files
                   4060: #
                   4061: 
                   4062: sub courseidput {
1.921     raeburn  4063:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4064:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4065:     my $outcome;
                   4066:     if ($caller eq 'timeonly') {
                   4067:         my $cids = '';
                   4068:         foreach my $item (keys(%$storehash)) {
                   4069:             $cids.=&escape($item).'&';
                   4070:         }
                   4071:         $cids=~s/\&$//;
                   4072:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4073:                           $coursehome);       
                   4074:     } else {
                   4075:         my $items = '';
                   4076:         foreach my $item (keys(%$storehash)) {
                   4077:             $items.= &escape($item).'='.
                   4078:                      &freeze_escape($$storehash{$item}).'&';
                   4079:         }
                   4080:         $items=~s/\&$//;
                   4081:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4082:                           $coursehome);
1.918     raeburn  4083:     }
                   4084:     if ($outcome eq 'unknown_cmd') {
                   4085:         my $what;
                   4086:         foreach my $cid (keys(%$storehash)) {
                   4087:             $what .= &escape($cid).'=';
1.921     raeburn  4088:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4089:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4090:             }
                   4091:             $what =~ s/\:$/&/;
                   4092:         }
                   4093:         $what =~ s/\&$//;  
                   4094:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4095:     } else {
                   4096:         return $outcome;
                   4097:     }
1.353     www      4098: }
                   4099: 
                   4100: sub courseiddump {
1.921     raeburn  4101:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4102:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4103:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  4104:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  4105:     my $as_hash = 1;
                   4106:     my %returnhash;
                   4107:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4108:     my %libserv = &all_library();
                   4109:     foreach my $tryserver (keys(%libserv)) {
                   4110:         if ( (  $hostidflag == 1 
                   4111: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4112: 	     || (!defined($hostidflag)) ) {
                   4113: 
1.918     raeburn  4114: 	    if (($domfilter eq '') ||
                   4115: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4116:                 my $rep;
                   4117:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4118:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4119:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4120:                                 &escape($descfilter), &escape($instcodefilter),
                   4121:                                 &escape($ownerfilter), &escape($coursefilter),
                   4122:                                 &escape($typefilter), &escape($regexp_ok),
                   4123:                                 $as_hash, &escape($selfenrollonly),
                   4124:                                 &escape($catfilter), $showhidden, $caller,
                   4125:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4126:                                 &escape($createdbefore), &escape($createdafter),
                   4127:                                 &escape($creationcontext), $domcloner)));
                   4128:                 } else {
                   4129:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4130:                              $sincefilter.':'.&escape($descfilter).':'.
                   4131:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4132:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4133:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4134:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4135:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4136:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4137:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   4138:                              &escape($creationcontext).':'.$domcloner,
                   4139:                              $tryserver);
                   4140:                 }
                   4141: 
1.918     raeburn  4142:                 my @pairs=split(/\&/,$rep);
                   4143:                 foreach my $item (@pairs) {
                   4144:                     my ($key,$value)=split(/\=/,$item,2);
                   4145:                     $key = &unescape($key);
                   4146:                     next if ($key =~ /^error: 2 /);
                   4147:                     my $result = &thaw_unescape($value);
                   4148:                     if (ref($result) eq 'HASH') {
                   4149:                         $returnhash{$key}=$result;
                   4150:                     } else {
1.921     raeburn  4151:                         my @responses = split(/:/,$value);
                   4152:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4153:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4154:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4155:                         }
1.1008    raeburn  4156:                     }
1.353     www      4157:                 }
                   4158:             }
                   4159:         }
                   4160:     }
                   4161:     return %returnhash;
                   4162: }
                   4163: 
1.1055    raeburn  4164: sub courselastaccess {
                   4165:     my ($cdom,$cnum,$hostidref) = @_;
                   4166:     my %returnhash;
                   4167:     if ($cdom && $cnum) {
                   4168:         my $chome = &homeserver($cnum,$cdom);
                   4169:         if ($chome ne 'no_host') {
                   4170:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4171:             &extract_lastaccess(\%returnhash,$rep);
                   4172:         }
                   4173:     } else {
                   4174:         if (!$cdom) { $cdom=''; }
                   4175:         my %libserv = &all_library();
                   4176:         foreach my $tryserver (keys(%libserv)) {
                   4177:             if (ref($hostidref) eq 'ARRAY') {
                   4178:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4179:             } 
                   4180:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4181:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4182:                 &extract_lastaccess(\%returnhash,$rep);
                   4183:             }
                   4184:         }
                   4185:     }
                   4186:     return %returnhash;
                   4187: }
                   4188: 
                   4189: sub extract_lastaccess {
                   4190:     my ($returnhash,$rep) = @_;
                   4191:     if (ref($returnhash) eq 'HASH') {
                   4192:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4193:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4194:                  $rep eq '') {
                   4195:             my @pairs=split(/\&/,$rep);
                   4196:             foreach my $item (@pairs) {
                   4197:                 my ($key,$value)=split(/\=/,$item,2);
                   4198:                 $key = &unescape($key);
                   4199:                 next if ($key =~ /^error: 2 /);
                   4200:                 $returnhash->{$key} = &thaw_unescape($value);
                   4201:             }
                   4202:         }
                   4203:     }
                   4204:     return;
                   4205: }
                   4206: 
1.658     raeburn  4207: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4208: 
                   4209: sub dcmailput {
1.685     raeburn  4210:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4211:     my $status = &Apache::lonnet::critical(
1.740     www      4212:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4213:        &escape($message),$server);
1.662     raeburn  4214:     return $status;
                   4215: }
                   4216: 
1.658     raeburn  4217: sub dcmaildump {
                   4218:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4219:     my %returnhash=();
1.846     albertel 4220: 
                   4221:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4222:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4223:                                                          &escape($enddate).':';
                   4224: 	my @esc_senders=map { &escape($_)} @$senders;
                   4225: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4226: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4227:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4228:             if (($key) && ($value)) {
                   4229:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4230:             }
                   4231:         }
                   4232:     }
                   4233:     return %returnhash;
                   4234: }
1.662     raeburn  4235: # ---------------------------------------------------------- Domain roles
                   4236: 
                   4237: sub get_domain_roles {
                   4238:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4239:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4240:         $startdate = '.';
                   4241:     }
1.1018    raeburn  4242:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4243:         $enddate = '.';
                   4244:     }
1.922     raeburn  4245:     my $rolelist;
                   4246:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23! raeburn  4247:         $rolelist = join('&',@{$roles});
1.922     raeburn  4248:     }
1.662     raeburn  4249:     my %personnel = ();
1.841     albertel 4250: 
                   4251:     my %servers = &get_servers($dom,'library');
                   4252:     foreach my $tryserver (keys(%servers)) {
                   4253: 	%{$personnel{$tryserver}}=();
                   4254: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4255: 					    &escape($startdate).':'.
                   4256: 					    &escape($enddate).':'.
                   4257: 					    &escape($rolelist), $tryserver))) {
                   4258: 	    my ($key,$value) = split(/\=/,$line,2);
                   4259: 	    if (($key) && ($value)) {
                   4260: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4261: 	    }
                   4262: 	}
1.662     raeburn  4263:     }
                   4264:     return %personnel;
                   4265: }
1.658     raeburn  4266: 
1.1057    www      4267: # ----------------------------------------------------------- Interval timing 
1.149     www      4268: 
1.1153    www      4269: {
                   4270: # Caches needed for speedup of navmaps
                   4271: # We don't want to cache this for very long at all (5 seconds at most)
                   4272: # 
                   4273: # The user for whom we cache
                   4274: my $cachedkey='';
                   4275: # The cached times for this user
                   4276: my %cachedtimes=();
                   4277: # When this was last done
                   4278: my $cachedtime=();
                   4279: 
                   4280: sub load_all_first_access {
1.1154    raeburn  4281:     my ($uname,$udom)=@_;
1.1156    www      4282:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4283:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4284:         return;
                   4285:     }
                   4286:     $cachedtime=time;
                   4287:     $cachedkey=$uname.':'.$udom;
                   4288:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4289: }
                   4290: 
1.504     albertel 4291: sub get_first_access {
1.1162    raeburn  4292:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4293:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4294:     if ($argsymb) { $symb=$argsymb; }
                   4295:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4296:     if ($argmap) { $map = $argmap; }
1.926     albertel 4297:     if ($type eq 'course') {
                   4298: 	$res='course';
                   4299:     } elsif ($type eq 'map') {
1.588     albertel 4300: 	$res=&symbread($map);
                   4301:     } else {
                   4302: 	$res=$symb;
                   4303:     }
1.1153    www      4304:     &load_all_first_access($uname,$udom);
                   4305:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4306: }
                   4307: 
                   4308: sub set_first_access {
1.1162    raeburn  4309:     my ($type,$interval)=@_;
1.790     albertel 4310:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4311:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4312:     if ($type eq 'course') {
                   4313: 	$res='course';
                   4314:     } elsif ($type eq 'map') {
1.588     albertel 4315: 	$res=&symbread($map);
                   4316:     } else {
                   4317: 	$res=$symb;
                   4318:     }
1.1153    www      4319:     $cachedkey='';
1.1162    raeburn  4320:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4321:     if (!$firstaccess) {
1.1162    raeburn  4322:         my $start = time;
                   4323: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4324:                           $udom,$uname);
                   4325:         if ($putres eq 'ok') {
                   4326:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4327:                  $udom,$uname); 
                   4328:             &appenv(
                   4329:                      {
                   4330:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4331:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4332:                      }
                   4333:                   );
                   4334:         }
                   4335:         return $putres;
1.505     albertel 4336:     }
                   4337:     return 'already_set';
1.504     albertel 4338: }
1.1153    www      4339: }
1.110     www      4340: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4341: 
                   4342: sub expirespread {
                   4343:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4344:     my $cid=$env{'request.course.id'}; 
1.110     www      4345:     if ($cid) {
                   4346:        my $now=time;
                   4347:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4348:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4349:                             $env{'course.'.$cid.'.num'}.
1.110     www      4350: 	        	    ':nohist_expirationdates:'.
                   4351:                             &escape($key).'='.$now,
1.620     albertel 4352:                             $env{'course.'.$cid.'.home'})
1.110     www      4353:     }
                   4354:     return 'ok';
1.14      www      4355: }
                   4356: 
1.109     www      4357: # ----------------------------------------------------- Devalidate Spreadsheets
                   4358: 
                   4359: sub devalidate {
1.325     www      4360:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4361:     my $cid=$env{'request.course.id'}; 
1.109     www      4362:     if ($cid) {
1.391     matthew  4363:         # delete the stored spreadsheets for
                   4364:         # - the student level sheet of this user in course's homespace
                   4365:         # - the assessment level sheet for this resource 
                   4366:         #   for this user in user's homespace
1.553     albertel 4367: 	# - current conditional state info
1.325     www      4368: 	my $key=$uname.':'.$udom.':';
1.109     www      4369:         my $status=
1.299     matthew  4370: 	    &del('nohist_calculatedsheets',
1.391     matthew  4371: 		 [$key.'studentcalc:'],
1.620     albertel 4372: 		 $env{'course.'.$cid.'.domain'},
                   4373: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4374: 		.' '.
                   4375: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4376: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4377:         unless ($status eq 'ok ok') {
                   4378:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4379:                     $uname.' at '.$udom.' for '.
1.109     www      4380: 		    $symb.': '.$status);
1.133     albertel 4381:         }
1.553     albertel 4382: 	&delenv('user.state.'.$cid);
1.109     www      4383:     }
                   4384: }
                   4385: 
1.265     albertel 4386: sub get_scalar {
                   4387:     my ($string,$end) = @_;
                   4388:     my $value;
                   4389:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4390: 	$value = $1;
                   4391:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4392: 	$value = $1;
                   4393:     }
                   4394:     return &unescape($value);
                   4395: }
                   4396: 
                   4397: sub array2str {
                   4398:   my (@array) = @_;
                   4399:   my $result=&arrayref2str(\@array);
                   4400:   $result=~s/^__ARRAY_REF__//;
                   4401:   $result=~s/__END_ARRAY_REF__$//;
                   4402:   return $result;
                   4403: }
                   4404: 
1.204     albertel 4405: sub arrayref2str {
                   4406:   my ($arrayref) = @_;
1.265     albertel 4407:   my $result='__ARRAY_REF__';
1.204     albertel 4408:   foreach my $elem (@$arrayref) {
1.265     albertel 4409:     if(ref($elem) eq 'ARRAY') {
                   4410:       $result.=&arrayref2str($elem).'&';
                   4411:     } elsif(ref($elem) eq 'HASH') {
                   4412:       $result.=&hashref2str($elem).'&';
                   4413:     } elsif(ref($elem)) {
                   4414:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4415:     } else {
                   4416:       $result.=&escape($elem).'&';
                   4417:     }
                   4418:   }
                   4419:   $result=~s/\&$//;
1.265     albertel 4420:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4421:   return $result;
                   4422: }
                   4423: 
1.168     albertel 4424: sub hash2str {
1.204     albertel 4425:   my (%hash) = @_;
                   4426:   my $result=&hashref2str(\%hash);
1.265     albertel 4427:   $result=~s/^__HASH_REF__//;
                   4428:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4429:   return $result;
                   4430: }
                   4431: 
                   4432: sub hashref2str {
                   4433:   my ($hashref)=@_;
1.265     albertel 4434:   my $result='__HASH_REF__';
1.800     albertel 4435:   foreach my $key (sort(keys(%$hashref))) {
                   4436:     if (ref($key) eq 'ARRAY') {
                   4437:       $result.=&arrayref2str($key).'=';
                   4438:     } elsif (ref($key) eq 'HASH') {
                   4439:       $result.=&hashref2str($key).'=';
                   4440:     } elsif (ref($key)) {
1.265     albertel 4441:       $result.='=';
1.800     albertel 4442:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4443:     } else {
1.1132    raeburn  4444: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4445:     }
                   4446: 
1.800     albertel 4447:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4448:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4449:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4450:       $result.=&hashref2str($hashref->{$key}).'&';
                   4451:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4452:        $result.='&';
1.800     albertel 4453:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4454:     } else {
1.800     albertel 4455:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4456:     }
                   4457:   }
1.168     albertel 4458:   $result=~s/\&$//;
1.265     albertel 4459:   $result .= '__END_HASH_REF__';
1.168     albertel 4460:   return $result;
                   4461: }
                   4462: 
                   4463: sub str2hash {
1.265     albertel 4464:     my ($string)=@_;
                   4465:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4466:     return %$hash;
                   4467: }
                   4468: 
                   4469: sub str2hashref {
1.168     albertel 4470:   my ($string) = @_;
1.265     albertel 4471: 
                   4472:   my %hash;
                   4473: 
                   4474:   if($string !~ /^__HASH_REF__/) {
                   4475:       if (! ($string eq '' || !defined($string))) {
                   4476: 	  $hash{'error'}='Not hash reference';
                   4477:       }
                   4478:       return (\%hash, $string);
                   4479:   }
                   4480: 
                   4481:   $string =~ s/^__HASH_REF__//;
                   4482: 
                   4483:   while($string !~ /^__END_HASH_REF__/) {
                   4484:       #key
                   4485:       my $key='';
                   4486:       if($string =~ /^__HASH_REF__/) {
                   4487:           ($key, $string)=&str2hashref($string);
                   4488:           if(defined($key->{'error'})) {
                   4489:               $hash{'error'}='Bad data';
                   4490:               return (\%hash, $string);
                   4491:           }
                   4492:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4493:           ($key, $string)=&str2arrayref($string);
                   4494:           if($key->[0] eq 'Array reference error') {
                   4495:               $hash{'error'}='Bad data';
                   4496:               return (\%hash, $string);
                   4497:           }
                   4498:       } else {
                   4499:           $string =~ s/^(.*?)=//;
1.267     albertel 4500: 	  $key=&unescape($1);
1.265     albertel 4501:       }
                   4502:       $string =~ s/^=//;
                   4503: 
                   4504:       #value
                   4505:       my $value='';
                   4506:       if($string =~ /^__HASH_REF__/) {
                   4507:           ($value, $string)=&str2hashref($string);
                   4508:           if(defined($value->{'error'})) {
                   4509:               $hash{'error'}='Bad data';
                   4510:               return (\%hash, $string);
                   4511:           }
                   4512:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4513:           ($value, $string)=&str2arrayref($string);
                   4514:           if($value->[0] eq 'Array reference error') {
                   4515:               $hash{'error'}='Bad data';
                   4516:               return (\%hash, $string);
                   4517:           }
                   4518:       } else {
                   4519: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4520:       }
                   4521:       $string =~ s/^&//;
                   4522: 
                   4523:       $hash{$key}=$value;
1.204     albertel 4524:   }
1.265     albertel 4525: 
                   4526:   $string =~ s/^__END_HASH_REF__//;
                   4527: 
                   4528:   return (\%hash, $string);
1.204     albertel 4529: }
                   4530: 
                   4531: sub str2array {
1.265     albertel 4532:     my ($string)=@_;
                   4533:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4534:     return @$array;
                   4535: }
                   4536: 
                   4537: sub str2arrayref {
1.204     albertel 4538:   my ($string) = @_;
1.265     albertel 4539:   my @array;
                   4540: 
                   4541:   if($string !~ /^__ARRAY_REF__/) {
                   4542:       if (! ($string eq '' || !defined($string))) {
                   4543: 	  $array[0]='Array reference error';
                   4544:       }
                   4545:       return (\@array, $string);
                   4546:   }
                   4547: 
                   4548:   $string =~ s/^__ARRAY_REF__//;
                   4549: 
                   4550:   while($string !~ /^__END_ARRAY_REF__/) {
                   4551:       my $value='';
                   4552:       if($string =~ /^__HASH_REF__/) {
                   4553:           ($value, $string)=&str2hashref($string);
                   4554:           if(defined($value->{'error'})) {
                   4555:               $array[0] ='Array reference error';
                   4556:               return (\@array, $string);
                   4557:           }
                   4558:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4559:           ($value, $string)=&str2arrayref($string);
                   4560:           if($value->[0] eq 'Array reference error') {
                   4561:               $array[0] ='Array reference error';
                   4562:               return (\@array, $string);
                   4563:           }
                   4564:       } else {
                   4565: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4566:       }
                   4567:       $string =~ s/^&//;
                   4568: 
                   4569:       push(@array, $value);
1.191     harris41 4570:   }
1.265     albertel 4571: 
                   4572:   $string =~ s/^__END_ARRAY_REF__//;
                   4573: 
                   4574:   return (\@array, $string);
1.168     albertel 4575: }
                   4576: 
1.167     albertel 4577: # -------------------------------------------------------------------Temp Store
                   4578: 
1.168     albertel 4579: sub tmpreset {
                   4580:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4581:   if (!$symb) {
                   4582:     $symb=&symbread();
1.620     albertel 4583:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4584:   }
                   4585:   $symb=escape($symb);
                   4586: 
1.620     albertel 4587:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4588:   $namespace=~s/\//\_/g;
                   4589:   $namespace=~s/\W//g;
                   4590: 
1.620     albertel 4591:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4592:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4593:   if ($domain eq 'public' && $stuname eq 'public') {
                   4594:       $stuname=$ENV{'REMOTE_ADDR'};
                   4595:   }
1.1117    foxr     4596:   my $path=LONCAPA::tempdir();
1.168     albertel 4597:   my %hash;
                   4598:   if (tie(%hash,'GDBM_File',
                   4599: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4600: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4601:     foreach my $key (keys(%hash)) {
1.180     albertel 4602:       if ($key=~ /:$symb/) {
1.168     albertel 4603: 	delete($hash{$key});
                   4604:       }
                   4605:     }
                   4606:   }
                   4607: }
                   4608: 
1.167     albertel 4609: sub tmpstore {
1.168     albertel 4610:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4611: 
                   4612:   if (!$symb) {
                   4613:     $symb=&symbread();
1.620     albertel 4614:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4615:   }
                   4616:   $symb=escape($symb);
                   4617: 
                   4618:   if (!$namespace) {
                   4619:     # I don't think we would ever want to store this for a course.
                   4620:     # it seems this will only be used if we don't have a course.
1.620     albertel 4621:     #$namespace=$env{'request.course.id'};
1.168     albertel 4622:     #if (!$namespace) {
1.620     albertel 4623:       $namespace=$env{'request.state'};
1.168     albertel 4624:     #}
                   4625:   }
                   4626:   $namespace=~s/\//\_/g;
                   4627:   $namespace=~s/\W//g;
1.620     albertel 4628:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4629:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4630:   if ($domain eq 'public' && $stuname eq 'public') {
                   4631:       $stuname=$ENV{'REMOTE_ADDR'};
                   4632:   }
1.168     albertel 4633:   my $now=time;
                   4634:   my %hash;
1.1117    foxr     4635:   my $path=LONCAPA::tempdir();
1.168     albertel 4636:   if (tie(%hash,'GDBM_File',
                   4637: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4638: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4639:     $hash{"version:$symb"}++;
                   4640:     my $version=$hash{"version:$symb"};
                   4641:     my $allkeys=''; 
                   4642:     foreach my $key (keys(%$storehash)) {
                   4643:       $allkeys.=$key.':';
1.591     albertel 4644:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4645:     }
                   4646:     $hash{"$version:$symb:timestamp"}=$now;
                   4647:     $allkeys.='timestamp';
                   4648:     $hash{"$version:keys:$symb"}=$allkeys;
                   4649:     if (untie(%hash)) {
                   4650:       return 'ok';
                   4651:     } else {
                   4652:       return "error:$!";
                   4653:     }
                   4654:   } else {
                   4655:     return "error:$!";
                   4656:   }
                   4657: }
1.167     albertel 4658: 
1.168     albertel 4659: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4660: 
1.168     albertel 4661: sub tmprestore {
                   4662:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4663: 
1.168     albertel 4664:   if (!$symb) {
                   4665:     $symb=&symbread();
1.620     albertel 4666:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4667:   }
                   4668:   $symb=escape($symb);
                   4669: 
1.620     albertel 4670:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4671: 
1.620     albertel 4672:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4673:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4674:   if ($domain eq 'public' && $stuname eq 'public') {
                   4675:       $stuname=$ENV{'REMOTE_ADDR'};
                   4676:   }
1.168     albertel 4677:   my %returnhash;
                   4678:   $namespace=~s/\//\_/g;
                   4679:   $namespace=~s/\W//g;
                   4680:   my %hash;
1.1117    foxr     4681:   my $path=LONCAPA::tempdir();
1.168     albertel 4682:   if (tie(%hash,'GDBM_File',
                   4683: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4684: 	  &GDBM_READER(),0640)) {
1.168     albertel 4685:     my $version=$hash{"version:$symb"};
                   4686:     $returnhash{'version'}=$version;
                   4687:     my $scope;
                   4688:     for ($scope=1;$scope<=$version;$scope++) {
                   4689:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4690:       my @keys=split(/:/,$vkeys);
                   4691:       my $key;
                   4692:       $returnhash{"$scope:keys"}=$vkeys;
                   4693:       foreach $key (@keys) {
1.591     albertel 4694: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4695: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4696:       }
                   4697:     }
1.168     albertel 4698:     if (!(untie(%hash))) {
                   4699:       return "error:$!";
                   4700:     }
                   4701:   } else {
                   4702:     return "error:$!";
                   4703:   }
                   4704:   return %returnhash;
1.167     albertel 4705: }
                   4706: 
1.9       www      4707: # ----------------------------------------------------------------------- Store
                   4708: 
                   4709: sub store {
1.124     www      4710:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4711:     my $home='';
                   4712: 
1.168     albertel 4713:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4714: 
1.213     www      4715:     $symb=&symbclean($symb);
1.122     albertel 4716:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4717: 
1.620     albertel 4718:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4719:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4720: 
                   4721:     &devalidate($symb,$stuname,$domain);
1.109     www      4722: 
                   4723:     $symb=escape($symb);
1.187     www      4724:     if (!$namespace) { 
1.620     albertel 4725:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4726:           return ''; 
                   4727:        } 
                   4728:     }
1.620     albertel 4729:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4730: 
                   4731:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4732:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4733: 
1.12      www      4734:     my $namevalue='';
1.800     albertel 4735:     foreach my $key (keys(%$storehash)) {
                   4736:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4737:     }
1.12      www      4738:     $namevalue=~s/\&$//;
1.187     www      4739:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4740:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4741: }
                   4742: 
1.47      www      4743: # -------------------------------------------------------------- Critical Store
                   4744: 
                   4745: sub cstore {
1.124     www      4746:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4747:     my $home='';
                   4748: 
1.168     albertel 4749:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4750: 
1.213     www      4751:     $symb=&symbclean($symb);
1.122     albertel 4752:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4753: 
1.620     albertel 4754:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4755:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4756: 
                   4757:     &devalidate($symb,$stuname,$domain);
1.109     www      4758: 
                   4759:     $symb=escape($symb);
1.187     www      4760:     if (!$namespace) { 
1.620     albertel 4761:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4762:           return ''; 
                   4763:        } 
                   4764:     }
1.620     albertel 4765:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4766: 
                   4767:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4768:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4769: 
1.47      www      4770:     my $namevalue='';
1.800     albertel 4771:     foreach my $key (keys(%$storehash)) {
                   4772:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4773:     }
1.47      www      4774:     $namevalue=~s/\&$//;
1.187     www      4775:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4776:     return critical
                   4777:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4778: }
                   4779: 
1.9       www      4780: # --------------------------------------------------------------------- Restore
                   4781: 
                   4782: sub restore {
1.124     www      4783:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4784:     my $home='';
                   4785: 
1.168     albertel 4786:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4787: 
1.122     albertel 4788:     if (!$symb) {
                   4789:       unless ($symb=escape(&symbread())) { return ''; }
                   4790:     } else {
1.213     www      4791:       $symb=&escape(&symbclean($symb));
1.122     albertel 4792:     }
1.188     www      4793:     if (!$namespace) { 
1.620     albertel 4794:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4795:           return ''; 
                   4796:        } 
                   4797:     }
1.620     albertel 4798:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4799:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4800:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4801:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4802: 
1.12      www      4803:     my %returnhash=();
1.800     albertel 4804:     foreach my $line (split(/\&/,$answer)) {
                   4805: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4806:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4807:     }
1.75      www      4808:     my $version;
                   4809:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4810:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4811:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4812:        }
1.75      www      4813:     }
1.13      www      4814:     return %returnhash;
1.34      www      4815: }
                   4816: 
                   4817: # ---------------------------------------------------------- Course Description
1.1118    foxr     4818: #
                   4819: #  
1.34      www      4820: 
                   4821: sub coursedescription {
1.731     albertel 4822:     my ($courseid,$args)=@_;
1.34      www      4823:     $courseid=~s/^\///;
1.49      www      4824:     $courseid=~s/\_/\//g;
1.34      www      4825:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4826:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4827:     my $normalid=$cdomain.'_'.$cnum;
                   4828:     # need to always cache even if we get errors otherwise we keep 
                   4829:     # trying and trying and trying to get the course description.
                   4830:     my %envhash=();
                   4831:     my %returnhash=();
1.731     albertel 4832:     
                   4833:     my $expiretime=600;
                   4834:     if ($env{'request.course.id'} eq $normalid) {
                   4835: 	$expiretime=120;
                   4836:     }
                   4837: 
                   4838:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4839:     if (!$args->{'freshen_cache'}
                   4840: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4841: 	foreach my $key (keys(%env)) {
                   4842: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4843: 	    my ($setting) = $1;
                   4844: 	    $returnhash{$setting} = $env{$key};
                   4845: 	}
                   4846: 	return %returnhash;
                   4847:     }
                   4848: 
1.1118    foxr     4849:     # get the data again
                   4850: 
1.731     albertel 4851:     if (!$args->{'one_time'}) {
                   4852: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4853:     }
1.811     albertel 4854: 
1.34      www      4855:     if ($chome ne 'no_host') {
1.302     albertel 4856:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4857:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4858: 	   my $username = $env{'user.name'}; # Defult username
                   4859: 	   if(defined $args->{'user'}) {
                   4860: 	       $username = $args->{'user'};
                   4861: 	   }
1.129     albertel 4862:            $returnhash{'home'}= $chome;
                   4863: 	   $returnhash{'domain'} = $cdomain;
                   4864: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4865:            if (!defined($returnhash{'type'})) {
                   4866:                $returnhash{'type'} = 'Course';
                   4867:            }
1.130     albertel 4868:            while (my ($name,$value) = each %returnhash) {
1.53      www      4869:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4870:            }
1.270     www      4871:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4872:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4873: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4874:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4875:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4876:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4877:        }
                   4878:     }
1.731     albertel 4879:     if (!$args->{'one_time'}) {
1.949     raeburn  4880: 	&appenv(\%envhash);
1.731     albertel 4881:     }
1.302     albertel 4882:     return %returnhash;
1.461     www      4883: }
                   4884: 
1.1080    raeburn  4885: sub update_released_required {
                   4886:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4887:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4888:         $cid = $env{'request.course.id'};
                   4889:         $cdom = $env{'course.'.$cid.'.domain'};
                   4890:         $cnum = $env{'course.'.$cid.'.num'};
                   4891:         $chome = $env{'course.'.$cid.'.home'};
                   4892:     }
                   4893:     if ($needsrelease) {
                   4894:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4895:         my $needsupdate;
                   4896:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4897:             $needsupdate = 1;
                   4898:         } else {
                   4899:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4900:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4901:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4902:                 $needsupdate = 1;
                   4903:             }
                   4904:         }
                   4905:         if ($needsupdate) {
                   4906:             my %needshash = (
                   4907:                              'internal.releaserequired' => $needsrelease,
                   4908:                             );
                   4909:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4910:             if ($putresult eq 'ok') {
                   4911:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4912:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4913:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4914:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4915:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4916:                 }
                   4917:             }
                   4918:         }
                   4919:     }
                   4920:     return;
                   4921: }
                   4922: 
1.461     www      4923: # -------------------------------------------------See if a user is privileged
                   4924: 
                   4925: sub privileged {
1.1172.2.23! raeburn  4926:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 4927:     my $now = time;
1.1172.2.23! raeburn  4928:     my $roles;
        !          4929:     if (ref($possroles) eq 'ARRAY') {
        !          4930:         $roles = $possroles;
        !          4931:     } else {
        !          4932:         $roles = ['dc','su'];
        !          4933:     }
        !          4934:     if (ref($possdomains) eq 'ARRAY') {
        !          4935:         my %privileged = &privileged_by_domain($possdomains,$roles);
        !          4936:         foreach my $dom (@{$possdomains}) {
        !          4937:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
        !          4938:                 (ref($privileged{$dom}) eq 'HASH')) {
        !          4939:                 foreach my $role (@{$roles}) {
        !          4940:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
        !          4941:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
        !          4942:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
        !          4943:                             return 1 unless (($end && $end < $now) ||
        !          4944:                                              ($start && $start > $now));
        !          4945:                         }
        !          4946:                     }
        !          4947:                 }
        !          4948:             }
        !          4949:         }
        !          4950:     } else {
        !          4951:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
        !          4952:         my $now = time;
1.1170    droeschl 4953: 
1.1172.2.23! raeburn  4954:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170    droeschl 4955:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23! raeburn  4956:             if (grep(/^\Q$trole\E$/,@{$roles})) {
        !          4957:                 return 1 unless ($tend && $tend < $now)
        !          4958:                         or ($tstart && $tstart > $now);
1.1170    droeschl 4959:             }
1.1172.2.23! raeburn  4960:         }
        !          4961:     }
1.461     www      4962:     return 0;
1.9       www      4963: }
1.1       albertel 4964: 
1.1172.2.23! raeburn  4965: sub privileged_by_domain {
        !          4966:     my ($domains,$roles) = @_;
        !          4967:     my %privileged = ();
        !          4968:     my $cachetime = 60*60*24;
        !          4969:     my $now = time;
        !          4970:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
        !          4971:         return %privileged;
        !          4972:     }
        !          4973:     foreach my $dom (@{$domains}) {
        !          4974:         next if (ref($privileged{$dom}) eq 'HASH');
        !          4975:         my $needroles;
        !          4976:         foreach my $role (@{$roles}) {
        !          4977:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
        !          4978:             if (defined($cached)) {
        !          4979:                 if (ref($result) eq 'HASH') {
        !          4980:                     $privileged{$dom}{$role} = $result;
        !          4981:                 }
        !          4982:             } else {
        !          4983:                 $needroles = 1;
        !          4984:             }
        !          4985:         }
        !          4986:         if ($needroles) {
        !          4987:             my %dompersonnel = &get_domain_roles($dom,$roles);
        !          4988:             $privileged{$dom} = {};
        !          4989:             foreach my $server (keys(%dompersonnel)) {
        !          4990:                 if (ref($dompersonnel{$server}) eq 'HASH') {
        !          4991:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
        !          4992:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
        !          4993:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
        !          4994:                         next if ($end && $end < $now);
        !          4995:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
        !          4996:                             $dompersonnel{$server}{$item};
        !          4997:                     }
        !          4998:                 }
        !          4999:             }
        !          5000:             if (ref($privileged{$dom}) eq 'HASH') {
        !          5001:                 foreach my $role (@{$roles}) {
        !          5002:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
        !          5003:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
        !          5004:                     } else {
        !          5005:                         my %hash = ();
        !          5006:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
        !          5007:                     }
        !          5008:                 }
        !          5009:             }
        !          5010:         }
        !          5011:     }
        !          5012:     return %privileged;
        !          5013: }
        !          5014: 
1.103     harris41 5015: # -------------------------------------------------------- Get user privileges
1.11      www      5016: 
                   5017: sub rolesinit {
1.1169    droeschl 5018:     my ($domain, $username) = @_;
                   5019:     my %userroles = ('user.login.time' => time);
                   5020:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5021: 
                   5022:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5023:     # also, blocking can be triggered by an activating timer
                   5024:     # it's saved in the user's %env.
                   5025:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5026:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5027:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5028:         %timerintchk, %timerintenv);
                   5029: 
1.1162    raeburn  5030:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5031:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5032:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5033:     }
1.1169    droeschl 5034: 
1.1162    raeburn  5035:     foreach my $key (keys(%timerinterval)) {
                   5036:         my ($cid,$rest) = split(/\0/,$key);
                   5037:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5038:     }
1.1169    droeschl 5039: 
1.11      www      5040:     my %allroles=();
1.1162    raeburn  5041:     my %allgroups=();
1.11      www      5042: 
1.1169    droeschl 5043:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   5044:         my $role = $rolesdump{$area};
                   5045:         $area =~ s/\_\w\w$//;
                   5046: 
                   5047:         my ($trole, $tend, $tstart, $group_privs);
                   5048: 
                   5049:         if ($role =~ /^cr/) {
                   5050:         # Custom role, defined by a user 
                   5051:         # e.g., user.role.cr/msu/smith/mynewrole
                   5052:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5053:                 $trole = $1;
                   5054:                 ($tend, $tstart) = split('_', $2);
                   5055:             } else {
                   5056:                 $trole = $role;
                   5057:             }
                   5058:         } elsif ($role =~ m|^gr/|) {
                   5059:         # Role of member in a group, defined within a course/community
                   5060:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5061:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5062:             next if $tstart eq '-1';
                   5063:             ($trole, $group_privs) = split(/\//, $trole);
                   5064:             $group_privs = &unescape($group_privs);
                   5065:         } else {
                   5066:         # Just a normal role, defined in roles.tab
                   5067:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5068:         }
                   5069: 
                   5070:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5071:                  $username);
                   5072:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5073: 
                   5074:         # role expired or not available yet?
                   5075:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5076:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5077: 
                   5078:         next if $area eq '' or $trole eq '';
                   5079: 
                   5080:         my $spec = "$trole.$area";
                   5081:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5082: 
                   5083:         if ($trole =~ /^cr\//) {
                   5084:         # Custom role, defined by a user
                   5085:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5086:         } elsif ($trole eq 'gr') {
                   5087:         # Role of a member in a group, defined within a course/community
                   5088:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5089:             next;
                   5090:         } else {
                   5091:         # Normal role, defined in roles.tab
                   5092:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5093:         }
                   5094: 
                   5095:         my $cid = $tdomain.'_'.$trest;
                   5096:         unless ($firstaccchk{$cid}) {
                   5097:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5098:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5099:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5100:                         $coursetimerstarts{$cid}{$item}; 
                   5101:                 }
                   5102:             }
                   5103:             $firstaccchk{$cid} = 1;
                   5104:         }
                   5105:         unless ($timerintchk{$cid}) {
                   5106:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5107:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5108:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5109:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5110:                 }
1.12      www      5111:             }
1.1169    droeschl 5112:             $timerintchk{$cid} = 1;
1.191     harris41 5113:         }
1.11      www      5114:     }
1.1169    droeschl 5115: 
                   5116:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5117:         \%allroles, \%allgroups);
                   5118:     $env{'user.adv'} = $userroles{'user.adv'};
                   5119: 
1.1162    raeburn  5120:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5121: }
                   5122: 
1.567     raeburn  5123: sub set_arearole {
1.1172.2.19  raeburn  5124:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5125:     unless ($nolog) {
1.567     raeburn  5126: # log the associated role with the area
1.1172.2.19  raeburn  5127:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5128:     }
1.743     albertel 5129:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5130: }
                   5131: 
                   5132: sub custom_roleprivs {
                   5133:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5134:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   5135:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 5136:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5137:         my ($rdummy,$roledef)=
                   5138:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5139:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5140:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5141:             if (defined($syspriv)) {
1.1043    raeburn  5142:                 if ($trest =~ /^$match_community$/) {
                   5143:                     $syspriv =~ s/bre\&S//; 
                   5144:                 }
1.567     raeburn  5145:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5146:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5147:             }
                   5148:             if ($tdomain ne '') {
                   5149:                 if (defined($dompriv)) {
                   5150:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5151:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5152:                 }
                   5153:                 if (($trest ne '') && (defined($coursepriv))) {
                   5154:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5155:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5156:                 }
                   5157:             }
                   5158:         }
                   5159:     }
                   5160: }
                   5161: 
1.678     raeburn  5162: sub group_roleprivs {
                   5163:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5164:     my $access = 1;
                   5165:     my $now = time;
                   5166:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5167:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5168:     if ($access) {
1.811     albertel 5169:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5170:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5171:     }
                   5172: }
1.567     raeburn  5173: 
                   5174: sub standard_roleprivs {
                   5175:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5176:     if (defined($pr{$trole.':s'})) {
                   5177:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5178:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5179:     }
                   5180:     if ($tdomain ne '') {
                   5181:         if (defined($pr{$trole.':d'})) {
                   5182:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5183:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5184:         }
                   5185:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5186:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5187:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5188:         }
                   5189:     }
                   5190: }
                   5191: 
                   5192: sub set_userprivs {
1.1064    raeburn  5193:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5194:     my $author=0;
                   5195:     my $adv=0;
1.678     raeburn  5196:     my %grouproles = ();
                   5197:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5198:         my @groupkeys; 
1.1000    raeburn  5199:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5200:             push(@groupkeys,$role);
                   5201:         }
                   5202:         if (ref($groups_roles) eq 'HASH') {
                   5203:             foreach my $key (keys(%{$groups_roles})) {
                   5204:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5205:                     push(@groupkeys,$key);
                   5206:                 }
                   5207:             }
                   5208:         }
                   5209:         if (@groupkeys > 0) {
                   5210:             foreach my $role (@groupkeys) {
                   5211:                 my ($trole,$area,$sec,$extendedarea);
                   5212:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5213:                     $trole = $1;
                   5214:                     $area = $2;
                   5215:                     $sec = $3;
                   5216:                     $extendedarea = $area.$sec;
                   5217:                     if (exists($$allgroups{$area})) {
                   5218:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5219:                             my $spec = $trole.'.'.$extendedarea;
                   5220:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5221:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5222:                         }
1.678     raeburn  5223:                     }
                   5224:                 }
                   5225:             }
                   5226:         }
                   5227:     }
1.800     albertel 5228:     foreach my $group (keys(%grouproles)) {
                   5229:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5230:     }
1.800     albertel 5231:     foreach my $role (keys(%{$allroles})) {
                   5232:         my %thesepriv;
1.941     raeburn  5233:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5234:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5235:             if ($item ne '') {
                   5236:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5237:                 if ($restrictions eq '') {
                   5238:                     $thesepriv{$privilege}='F';
                   5239:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5240:                     $thesepriv{$privilege}.=$restrictions;
                   5241:                 }
                   5242:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5243:             }
                   5244:         }
                   5245:         my $thesestr='';
1.1104    raeburn  5246:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5247: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5248: 	}
                   5249:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5250:     }
                   5251:     return ($author,$adv);
                   5252: }
                   5253: 
1.994     raeburn  5254: sub role_status {
1.1104    raeburn  5255:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5256:     my @pwhere = ();
                   5257:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   5258:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   5259:         unless (!defined($$role) || $$role eq '') {
                   5260:             $$where=join('.',@pwhere);
                   5261:             $$trolecode=$$role.'.'.$$where;
                   5262:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5263:             $$tstatus='is';
1.1104    raeburn  5264:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5265:                 $$tstatus='future';
1.1034    raeburn  5266:                 if ($$tstart<$now) {
                   5267:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5268:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5269:                             my (%allroles,%allgroups,$group_privs,
                   5270:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5271:                             my %userroles = (
                   5272:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5273:                             );
1.1064    raeburn  5274:                             @rolecodes = ('cm'); 
1.1002    raeburn  5275:                             my $spec=$$role.'.'.$$where;
                   5276:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5277:                             if ($$role =~ /^cr\//) {
                   5278:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5279:                                 push(@rolecodes,'cr');
1.1002    raeburn  5280:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5281:                                 push(@rolecodes,$$role);
1.1002    raeburn  5282:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5283:                                                     $env{'user.name'});
1.1064    raeburn  5284:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5285:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5286:                                 $group_privs = &unescape($group_privs);
                   5287:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5288:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
1.1104    raeburn  5289:                                 &get_groups_roles($tdomain,$trest,
                   5290:                                                   \%course_roles,\@rolecodes,
                   5291:                                                   \%groups_roles);
1.1002    raeburn  5292:                             } else {
1.1064    raeburn  5293:                                 push(@rolecodes,$$role);
1.1002    raeburn  5294:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5295:                             }
1.1064    raeburn  5296:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5297:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5298:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5299:                         }
                   5300:                     }
1.1034    raeburn  5301:                     $$tstatus = 'is';
1.1002    raeburn  5302:                 }
1.994     raeburn  5303:             }
                   5304:             if ($$tend) {
1.1104    raeburn  5305:                 if ($$tend<$update) {
1.994     raeburn  5306:                     $$tstatus='expired';
                   5307:                 } elsif ($$tend<$now) {
                   5308:                     $$tstatus='will_not';
                   5309:                 }
                   5310:             }
                   5311:         }
                   5312:     }
                   5313: }
                   5314: 
1.1104    raeburn  5315: sub get_groups_roles {
                   5316:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5317:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5318:                   (ref($rolecodes) eq 'ARRAY') && 
                   5319:                   (ref($groups_roles) eq 'HASH')); 
                   5320:     if (keys(%{$cdom_courseroles}) > 0) {
                   5321:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5322:         if ($cdom ne '' && $cnum ne '') {
                   5323:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5324:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5325:                     my $crsrole = $1;
                   5326:                     my $crssec = $2;
                   5327:                     if ($crsrole =~ /^cr/) {
                   5328:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5329:                             push(@{$rolecodes},'cr');
                   5330:                         }
                   5331:                     } else {
                   5332:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5333:                             push(@{$rolecodes},$crsrole);
                   5334:                         }
                   5335:                     }
                   5336:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5337:                     if ($crssec ne '') {
                   5338:                         $rolekey .= "/$crssec";
                   5339:                     }
                   5340:                     $rolekey .= './';
                   5341:                     $groups_roles->{$rolekey} = $rolecodes;
                   5342:                 }
                   5343:             }
                   5344:         }
                   5345:     }
                   5346:     return;
                   5347: }
                   5348: 
                   5349: sub delete_env_groupprivs {
                   5350:     my ($where,$courseroles,$possroles) = @_;
                   5351:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5352:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5353:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5354:         %{$courseroles->{$udom}} =
                   5355:             &get_my_roles('','','userroles',['active'],
                   5356:                           $possroles,[$udom],1);
                   5357:     }
                   5358:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5359:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5360:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5361:             my $area = '/'.$cdom.'/'.$cnum;
                   5362:             my $privkey = "user.priv.$crsrole.$area";
                   5363:             if ($crssec ne '') {
                   5364:                 $privkey .= '/'.$crssec;
                   5365:             }
                   5366:             $privkey .= ".$area/$group";
                   5367:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5368:         }
                   5369:     }
                   5370:     return;
                   5371: }
                   5372: 
1.994     raeburn  5373: sub check_adhoc_privs {
1.1104    raeburn  5374:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5375:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5376:     my $setprivs;
1.994     raeburn  5377:     if ($env{$cckey}) {
                   5378:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5379:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5380:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5381:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5382:             $setprivs = 1;
1.994     raeburn  5383:         }
                   5384:     } else {
1.1088    raeburn  5385:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5386:         $setprivs = 1;
1.994     raeburn  5387:     }
1.1172.2.9  raeburn  5388:     return $setprivs;
1.994     raeburn  5389: }
                   5390: 
                   5391: sub set_adhoc_privileges {
                   5392: # role can be cc or ca
1.1088    raeburn  5393:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5394:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5395:     my $spec = $role.'.'.$area;
                   5396:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5397:                                   $env{'user.name'},1);
1.994     raeburn  5398:     my %ccrole = ();
                   5399:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5400:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5401:     &appenv(\%userroles,[$role,'cm']);
                   5402:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5403:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5404:         &appenv( {'request.role'        => $spec,
                   5405:                   'request.role.domain' => $dcdom,
                   5406:                   'request.course.sec'  => ''
                   5407:                  }
                   5408:                );
                   5409:         my $tadv=0;
                   5410:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5411:         &appenv({'request.role.adv'    => $tadv});
                   5412:     }
1.994     raeburn  5413: }
                   5414: 
1.12      www      5415: # --------------------------------------------------------------- get interface
                   5416: 
                   5417: sub get {
1.131     albertel 5418:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5419:    my $items='';
1.800     albertel 5420:    foreach my $item (@$storearr) {
                   5421:        $items.=&escape($item).'&';
1.191     harris41 5422:    }
1.12      www      5423:    $items=~s/\&$//;
1.620     albertel 5424:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5425:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5426:    my $uhome=&homeserver($uname,$udomain);
                   5427: 
1.133     albertel 5428:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5429:    my @pairs=split(/\&/,$rep);
1.273     albertel 5430:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5431:      return @pairs;
                   5432:    }
1.15      www      5433:    my %returnhash=();
1.42      www      5434:    my $i=0;
1.800     albertel 5435:    foreach my $item (@$storearr) {
                   5436:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5437:       $i++;
1.191     harris41 5438:    }
1.15      www      5439:    return %returnhash;
1.27      www      5440: }
                   5441: 
                   5442: # --------------------------------------------------------------- del interface
                   5443: 
                   5444: sub del {
1.133     albertel 5445:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5446:    my $items='';
1.800     albertel 5447:    foreach my $item (@$storearr) {
                   5448:        $items.=&escape($item).'&';
1.191     harris41 5449:    }
1.984     neumanie 5450: 
1.27      www      5451:    $items=~s/\&$//;
1.620     albertel 5452:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5453:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5454:    my $uhome=&homeserver($uname,$udomain);
                   5455:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5456: }
                   5457: 
                   5458: # -------------------------------------------------------------- dump interface
                   5459: 
1.1172.2.22  raeburn  5460: sub unserialize {
                   5461:     my ($rep, $escapedkeys) = @_;
                   5462: 
                   5463:     return {} if $rep =~ /^error/;
                   5464: 
                   5465:     my %returnhash=();
                   5466:     foreach my $item (split(/\&/,$rep)) {
                   5467:         my ($key, $value) = split(/=/, $item, 2);
                   5468:         $key = unescape($key) unless $escapedkeys;
                   5469:         next if $key =~ /^error: 2 /;
                   5470:         $returnhash{$key} = &thaw_unescape($value);
                   5471:     }
                   5472:     return \%returnhash;
                   5473: }
                   5474: 
                   5475: # see Lond::dump_with_regexp
                   5476: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5477: sub dump {
1.1172.2.22  raeburn  5478:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5479:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5480:     if (!$uname) { $uname=$env{'user.name'}; }
                   5481:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5482: 
1.1172.2.22  raeburn  5483:     my $reply;
                   5484:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   5485:         # user is hosted on this machine
                   5486:         $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
                   5487:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
                   5488:         return %{&unserialize($reply, $escapedkeys)};
                   5489:     }
1.755     albertel 5490:     if ($regexp) {
                   5491: 	$regexp=&escape($regexp);
                   5492:     } else {
                   5493: 	$regexp='.';
                   5494:     }
1.1166    raeburn  5495:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5496:     my @pairs=split(/\&/,$rep);
                   5497:     my %returnhash=();
1.1098    foxr     5498:     if (!($rep =~ /^error/ )) {
                   5499: 	foreach my $item (@pairs) {
                   5500: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  5501:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5502: 	    next if ($key =~ /^error: 2 /);
                   5503: 	    $returnhash{$key}=&thaw_unescape($value);
                   5504: 	}
1.755     albertel 5505:     }
                   5506:     return %returnhash;
1.407     www      5507: }
                   5508: 
1.1098    foxr     5509: 
1.717     albertel 5510: # --------------------------------------------------------- dumpstore interface
                   5511: 
                   5512: sub dumpstore {
                   5513:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  5514:    # same as dump but keys must be escaped. They may contain colon separated
                   5515:    # lists of values that may themself contain colons (e.g. symbs).
                   5516:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5517: }
                   5518: 
1.407     www      5519: # -------------------------------------------------------------- keys interface
                   5520: 
                   5521: sub getkeys {
                   5522:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5523:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5524:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5525:    my $uhome=&homeserver($uname,$udomain);
                   5526:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5527:    my @keyarray=();
1.800     albertel 5528:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5529:       next if ($key =~ /^error: 2 /);
1.800     albertel 5530:       push(@keyarray,&unescape($key));
1.407     www      5531:    }
                   5532:    return @keyarray;
1.318     matthew  5533: }
                   5534: 
1.319     matthew  5535: # --------------------------------------------------------------- currentdump
                   5536: sub currentdump {
1.328     matthew  5537:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5538:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5539:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5540:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5541:    my $uhome = &homeserver($sname,$sdom);
                   5542:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5543:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5544:    #
1.318     matthew  5545:    my %returnhash=();
1.319     matthew  5546:    #
                   5547:    if ($rep eq "unknown_cmd") { 
                   5548:        # an old lond will not know currentdump
                   5549:        # Do a dump and make it look like a currentdump
1.822     albertel 5550:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5551:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5552:        my %hash = @tmp;
                   5553:        @tmp=();
1.424     matthew  5554:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5555:    } else {
                   5556:        my @pairs=split(/\&/,$rep);
1.800     albertel 5557:        foreach my $pair (@pairs) {
                   5558:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5559:            my ($symb,$param) = split(/:/,$key);
                   5560:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5561:                                                         &thaw_unescape($value);
1.319     matthew  5562:        }
1.191     harris41 5563:    }
1.12      www      5564:    return %returnhash;
1.424     matthew  5565: }
                   5566: 
                   5567: sub convert_dump_to_currentdump{
                   5568:     my %hash = %{shift()};
                   5569:     my %returnhash;
                   5570:     # Code ripped from lond, essentially.  The only difference
                   5571:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5572:     # we might run in to problems with parameter names =~ /^v\./
                   5573:     while (my ($key,$value) = each(%hash)) {
                   5574:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5575: 	$symb  = &unescape($symb);
                   5576: 	$param = &unescape($param);
1.424     matthew  5577:         next if ($v eq 'version' || $symb eq 'keys');
                   5578:         next if (exists($returnhash{$symb}) &&
                   5579:                  exists($returnhash{$symb}->{$param}) &&
                   5580:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5581:         $returnhash{$symb}->{$param}=$value;
                   5582:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5583:     }
                   5584:     #
                   5585:     # Remove all of the keys in the hashes which keep track of
                   5586:     # the version of the parameter.
                   5587:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5588:         # use a foreach because we are going to delete from the hash.
                   5589:         foreach my $key (keys(%$param_hash)) {
                   5590:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5591:         }
                   5592:     }
                   5593:     return \%returnhash;
1.12      www      5594: }
                   5595: 
1.627     albertel 5596: # ------------------------------------------------------ critical inc interface
                   5597: 
                   5598: sub cinc {
                   5599:     return &inc(@_,'critical');
                   5600: }
                   5601: 
1.449     matthew  5602: # --------------------------------------------------------------- inc interface
                   5603: 
                   5604: sub inc {
1.627     albertel 5605:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5606:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5607:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5608:     my $uhome=&homeserver($uname,$udomain);
                   5609:     my $items='';
                   5610:     if (! ref($store)) {
                   5611:         # got a single value, so use that instead
                   5612:         $items = &escape($store).'=&';
                   5613:     } elsif (ref($store) eq 'SCALAR') {
                   5614:         $items = &escape($$store).'=&';        
                   5615:     } elsif (ref($store) eq 'ARRAY') {
                   5616:         $items = join('=&',map {&escape($_);} @{$store});
                   5617:     } elsif (ref($store) eq 'HASH') {
                   5618:         while (my($key,$value) = each(%{$store})) {
                   5619:             $items.= &escape($key).'='.&escape($value).'&';
                   5620:         }
                   5621:     }
                   5622:     $items=~s/\&$//;
1.627     albertel 5623:     if ($critical) {
                   5624: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5625:     } else {
                   5626: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5627:     }
1.449     matthew  5628: }
                   5629: 
1.12      www      5630: # --------------------------------------------------------------- put interface
                   5631: 
                   5632: sub put {
1.134     albertel 5633:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5634:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5635:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5636:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5637:    my $items='';
1.800     albertel 5638:    foreach my $item (keys(%$storehash)) {
                   5639:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5640:    }
1.12      www      5641:    $items=~s/\&$//;
1.134     albertel 5642:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5643: }
                   5644: 
1.631     albertel 5645: # ------------------------------------------------------------ newput interface
                   5646: 
                   5647: sub newput {
                   5648:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5649:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5650:    if (!$uname) { $uname=$env{'user.name'}; }
                   5651:    my $uhome=&homeserver($uname,$udomain);
                   5652:    my $items='';
                   5653:    foreach my $key (keys(%$storehash)) {
                   5654:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5655:    }
                   5656:    $items=~s/\&$//;
                   5657:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5658: }
                   5659: 
                   5660: # ---------------------------------------------------------  putstore interface
                   5661: 
1.524     raeburn  5662: sub putstore {
1.715     albertel 5663:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5664:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5665:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5666:    my $uhome=&homeserver($uname,$udomain);
                   5667:    my $items='';
1.715     albertel 5668:    foreach my $key (keys(%$storehash)) {
                   5669:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5670:    }
1.715     albertel 5671:    $items=~s/\&$//;
1.716     albertel 5672:    my $esc_symb=&escape($symb);
                   5673:    my $esc_v=&escape($version);
1.715     albertel 5674:    my $reply =
1.716     albertel 5675:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5676: 	      $uhome);
                   5677:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5678:        # gfall back to way things use to be done
1.715     albertel 5679:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5680: 			    $uname);
1.524     raeburn  5681:    }
1.715     albertel 5682:    return $reply;
                   5683: }
                   5684: 
                   5685: sub old_putstore {
1.716     albertel 5686:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5687:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5688:     if (!$uname) { $uname=$env{'user.name'}; }
                   5689:     my $uhome=&homeserver($uname,$udomain);
                   5690:     my %newstorehash;
1.800     albertel 5691:     foreach my $item (keys(%$storehash)) {
                   5692: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5693: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5694:     }
                   5695:     my $items='';
                   5696:     my %allitems = ();
1.800     albertel 5697:     foreach my $item (keys(%newstorehash)) {
                   5698: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5699: 	    my $key = $1.':keys:'.$2;
                   5700: 	    $allitems{$key} .= $3.':';
                   5701: 	}
1.800     albertel 5702: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5703:     }
1.800     albertel 5704:     foreach my $item (keys(%allitems)) {
                   5705: 	$allitems{$item} =~ s/\:$//;
                   5706: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5707:     }
                   5708:     $items=~s/\&$//;
                   5709:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5710: }
                   5711: 
1.47      www      5712: # ------------------------------------------------------ critical put interface
                   5713: 
                   5714: sub cput {
1.134     albertel 5715:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5716:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5717:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5718:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5719:    my $items='';
1.800     albertel 5720:    foreach my $item (keys(%$storehash)) {
                   5721:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5722:    }
1.47      www      5723:    $items=~s/\&$//;
1.134     albertel 5724:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5725: }
                   5726: 
                   5727: # -------------------------------------------------------------- eget interface
                   5728: 
                   5729: sub eget {
1.133     albertel 5730:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5731:    my $items='';
1.800     albertel 5732:    foreach my $item (@$storearr) {
                   5733:        $items.=&escape($item).'&';
1.191     harris41 5734:    }
1.12      www      5735:    $items=~s/\&$//;
1.620     albertel 5736:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5737:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5738:    my $uhome=&homeserver($uname,$udomain);
                   5739:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5740:    my @pairs=split(/\&/,$rep);
                   5741:    my %returnhash=();
1.42      www      5742:    my $i=0;
1.800     albertel 5743:    foreach my $item (@$storearr) {
                   5744:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5745:       $i++;
1.191     harris41 5746:    }
1.12      www      5747:    return %returnhash;
                   5748: }
                   5749: 
1.667     albertel 5750: # ------------------------------------------------------------ tmpput interface
                   5751: sub tmpput {
1.802     raeburn  5752:     my ($storehash,$server,$context)=@_;
1.667     albertel 5753:     my $items='';
1.800     albertel 5754:     foreach my $item (keys(%$storehash)) {
                   5755: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5756:     }
                   5757:     $items=~s/\&$//;
1.802     raeburn  5758:     if (defined($context)) {
                   5759:         $items .= ':'.&escape($context);
                   5760:     }
1.667     albertel 5761:     return &reply("tmpput:$items",$server);
                   5762: }
                   5763: 
                   5764: # ------------------------------------------------------------ tmpget interface
                   5765: sub tmpget {
1.688     albertel 5766:     my ($token,$server)=@_;
                   5767:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5768:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5769:     my %returnhash;
                   5770:     foreach my $item (split(/\&/,$rep)) {
                   5771: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5772:         next if ($key =~ /^error: 2 /);
1.667     albertel 5773: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5774:     }
                   5775:     return %returnhash;
                   5776: }
                   5777: 
1.1113    raeburn  5778: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5779: sub tmpdel {
                   5780:     my ($token,$server)=@_;
                   5781:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5782:     return &reply("tmpdel:$token",$server);
                   5783: }
                   5784: 
1.1172.2.13  raeburn  5785: # ------------------------------------------------------------ get_timebased_id
                   5786: 
                   5787: sub get_timebased_id {
                   5788:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   5789:         $maxtries) = @_;
                   5790:     my ($newid,$error,$dellock);
                   5791:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   5792:         return ('','ok','invalid call to get suffix');
                   5793:     }
                   5794: 
                   5795: # set defaults for any optional args for which values were not supplied
                   5796:     if ($who eq '') {
                   5797:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   5798:     }
                   5799:     if (!$locktries) {
                   5800:         $locktries = 3;
                   5801:     }
                   5802:     if (!$maxtries) {
                   5803:         $maxtries = 10;
                   5804:     }
                   5805: 
                   5806:     if (($cdom eq '') || ($cnum eq '')) {
                   5807:         if ($env{'request.course.id'}) {
                   5808:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5809:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5810:         }
                   5811:         if (($cdom eq '') || ($cnum eq '')) {
                   5812:             return ('','ok','call to get suffix not in course context');
                   5813:         }
                   5814:     }
                   5815: 
                   5816: # construct locking item
                   5817:     my $lockhash = {
                   5818:                       $prefix."\0".'locked_'.$keyid => $who,
                   5819:                    };
                   5820:     my $tries = 0;
                   5821: 
                   5822: # attempt to get lock on nohist_$namespace file
                   5823:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5824:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   5825:         $tries ++;
                   5826:         sleep 1;
                   5827:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   5828:     }
                   5829: 
                   5830: # attempt to get unique identifier, based on current timestamp
                   5831:     if ($gotlock eq 'ok') {
                   5832:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   5833:         my $id = time;
                   5834:         $newid = $id;
                   5835:         my $idtries = 0;
                   5836:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   5837:             if ($idtype eq 'concat') {
                   5838:                 $newid = $id.$idtries;
                   5839:             } else {
                   5840:                 $newid ++;
                   5841:             }
                   5842:             $idtries ++;
                   5843:         }
                   5844:         if (!exists($inuse{$prefix."\0".$newid})) {
                   5845:             my %new_item =  (
                   5846:                               $prefix."\0".$newid => $who,
                   5847:                             );
                   5848:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   5849:                                                  $cdom,$cnum);
                   5850:             if ($putresult ne 'ok') {
                   5851:                 undef($newid);
                   5852:                 $error = 'error saving new item: '.$putresult;
                   5853:             }
                   5854:         } else {
                   5855:              $error = ('error: no unique suffix available for the new item ');
                   5856:         }
                   5857: #  remove lock
                   5858:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   5859:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   5860:     } else {
                   5861:         $error = "error: could not obtain lockfile\n";
                   5862:         $dellock = 'ok';
                   5863:     }
                   5864:     return ($newid,$dellock,$error);
                   5865: }
                   5866: 
1.765     albertel 5867: # -------------------------------------------------- portfolio access checking
                   5868: 
                   5869: sub portfolio_access {
1.766     albertel 5870:     my ($requrl) = @_;
1.765     albertel 5871:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5872:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5873:     if ($result) {
                   5874:         my %setters;
                   5875:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5876:             my ($startblock,$endblock) =
                   5877:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5878:             if ($startblock && $endblock) {
                   5879:                 return 'B';
                   5880:             }
                   5881:         } else {
                   5882:             my ($startblock,$endblock) =
                   5883:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5884:             if ($startblock && $endblock) {
                   5885:                 return 'B';
                   5886:             }
                   5887:         }
                   5888:     }
1.765     albertel 5889:     if ($result eq 'ok') {
1.766     albertel 5890:        return 'F';
1.765     albertel 5891:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5892:        return 'A';
1.765     albertel 5893:     }
1.766     albertel 5894:     return '';
1.765     albertel 5895: }
                   5896: 
                   5897: sub get_portfolio_access {
1.767     albertel 5898:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5899: 
                   5900:     if (!ref($access_hash)) {
                   5901: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5902: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5903: 						   $file_name);
                   5904: 	$access_hash = $access_controls{$file_name};
                   5905:     }
                   5906: 
1.765     albertel 5907:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5908:     my $now = time;
                   5909:     if (ref($access_hash) eq 'HASH') {
                   5910:         foreach my $key (keys(%{$access_hash})) {
                   5911:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5912:             if ($start > $now) {
                   5913:                 next;
                   5914:             }
                   5915:             if ($end && $end<$now) {
                   5916:                 next;
                   5917:             }
                   5918:             if ($scope eq 'public') {
                   5919:                 $public = $key;
                   5920:                 last;
                   5921:             } elsif ($scope eq 'guest') {
                   5922:                 $guest = $key;
                   5923:             } elsif ($scope eq 'domains') {
                   5924:                 push(@domains,$key);
                   5925:             } elsif ($scope eq 'users') {
                   5926:                 push(@users,$key);
                   5927:             } elsif ($scope eq 'course') {
                   5928:                 push(@courses,$key);
                   5929:             } elsif ($scope eq 'group') {
                   5930:                 push(@groups,$key);
                   5931:             }
                   5932:         }
                   5933:         if ($public) {
                   5934:             return 'ok';
                   5935:         }
                   5936:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5937:             if ($guest) {
                   5938:                 return $guest;
                   5939:             }
                   5940:         } else {
                   5941:             if (@domains > 0) {
                   5942:                 foreach my $domkey (@domains) {
                   5943:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5944:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5945:                             return 'ok';
                   5946:                         }
                   5947:                     }
                   5948:                 }
                   5949:             }
                   5950:             if (@users > 0) {
                   5951:                 foreach my $userkey (@users) {
1.865     raeburn  5952:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5953:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5954:                             if (ref($item) eq 'HASH') {
                   5955:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5956:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5957:                                     return 'ok';
                   5958:                                 }
                   5959:                             }
                   5960:                         }
                   5961:                     } 
1.765     albertel 5962:                 }
                   5963:             }
                   5964:             my %roleshash;
                   5965:             my @courses_and_groups = @courses;
                   5966:             push(@courses_and_groups,@groups); 
                   5967:             if (@courses_and_groups > 0) {
                   5968:                 my (%allgroups,%allroles); 
                   5969:                 my ($start,$end,$role,$sec,$group);
                   5970:                 foreach my $envkey (%env) {
1.1060    raeburn  5971:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5972:                         my $cid = $2.'_'.$3; 
                   5973:                         if ($1 eq 'gr') {
                   5974:                             $group = $4;
                   5975:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5976:                         } else {
                   5977:                             if ($4 eq '') {
                   5978:                                 $sec = 'none';
                   5979:                             } else {
                   5980:                                 $sec = $4;
                   5981:                             }
                   5982:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5983:                         }
1.811     albertel 5984:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5985:                         my $cid = $2.'_'.$3;
                   5986:                         if ($4 eq '') {
                   5987:                             $sec = 'none';
                   5988:                         } else {
                   5989:                             $sec = $4;
                   5990:                         }
                   5991:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5992:                     }
                   5993:                 }
                   5994:                 if (keys(%allroles) == 0) {
                   5995:                     return;
                   5996:                 }
                   5997:                 foreach my $key (@courses_and_groups) {
                   5998:                     my %content = %{$$access_hash{$key}};
                   5999:                     my $cnum = $content{'number'};
                   6000:                     my $cdom = $content{'domain'};
                   6001:                     my $cid = $cdom.'_'.$cnum;
                   6002:                     if (!exists($allroles{$cid})) {
                   6003:                         next;
                   6004:                     }    
                   6005:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6006:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6007:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6008:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6009:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6010:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6011:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6012:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6013:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6014:                                         if (grep/^all$/,@sections) {
                   6015:                                             return 'ok';
                   6016:                                         } else {
                   6017:                                             if (grep/^$sec$/,@sections) {
                   6018:                                                 return 'ok';
                   6019:                                             }
                   6020:                                         }
                   6021:                                     }
                   6022:                                 }
                   6023:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6024:                                     if (grep/^none$/,@groups) {
                   6025:                                         return 'ok';
                   6026:                                     }
                   6027:                                 } else {
                   6028:                                     if (grep/^all$/,@groups) {
                   6029:                                         return 'ok';
                   6030:                                     } 
                   6031:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6032:                                         if (grep/^$group$/,@groups) {
                   6033:                                             return 'ok';
                   6034:                                         }
                   6035:                                     }
                   6036:                                 } 
                   6037:                             }
                   6038:                         }
                   6039:                     }
                   6040:                 }
                   6041:             }
                   6042:             if ($guest) {
                   6043:                 return $guest;
                   6044:             }
                   6045:         }
                   6046:     }
                   6047:     return;
                   6048: }
                   6049: 
                   6050: sub course_group_datechecker {
                   6051:     my ($dates,$now,$status) = @_;
                   6052:     my ($start,$end) = split(/\./,$dates);
                   6053:     if (!$start && !$end) {
                   6054:         return 'ok';
                   6055:     }
                   6056:     if (grep/^active$/,@{$status}) {
                   6057:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6058:             return 'ok';
                   6059:         }
                   6060:     }
                   6061:     if (grep/^previous$/,@{$status}) {
                   6062:         if ($end > $now ) {
                   6063:             return 'ok';
                   6064:         }
                   6065:     }
                   6066:     if (grep/^future$/,@{$status}) {
                   6067:         if ($start > $now) {
                   6068:             return 'ok';
                   6069:         }
                   6070:     }
                   6071:     return; 
                   6072: }
                   6073: 
                   6074: sub parse_portfolio_url {
                   6075:     my ($url) = @_;
                   6076: 
                   6077:     my ($type,$udom,$unum,$group,$file_name);
                   6078:     
1.823     albertel 6079:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6080: 	$type = 1;
                   6081:         $udom = $1;
                   6082:         $unum = $2;
                   6083:         $file_name = $3;
1.823     albertel 6084:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6085: 	$type = 2;
                   6086:         $udom = $1;
                   6087:         $unum = $2;
                   6088:         $group = $3;
                   6089:         $file_name = $3.'/'.$4;
                   6090:     }
                   6091:     if (wantarray) {
                   6092: 	return ($type,$udom,$unum,$file_name,$group);
                   6093:     }
                   6094:     return $type;
                   6095: }
                   6096: 
                   6097: sub is_portfolio_url {
                   6098:     my ($url) = @_;
                   6099:     return scalar(&parse_portfolio_url($url));
                   6100: }
                   6101: 
1.798     raeburn  6102: sub is_portfolio_file {
                   6103:     my ($file) = @_;
1.820     raeburn  6104:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6105:         return 1;
                   6106:     }
                   6107:     return;
                   6108: }
                   6109: 
1.976     raeburn  6110: sub usertools_access {
1.1084    raeburn  6111:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6112:     my ($access,%tools);
                   6113:     if ($context eq '') {
                   6114:         $context = 'tools';
                   6115:     }
                   6116:     if ($context eq 'requestcourses') {
                   6117:         %tools = (
                   6118:                       official   => 1,
                   6119:                       unofficial => 1,
1.1006    raeburn  6120:                       community  => 1,
1.985     raeburn  6121:                  );
1.1172.2.9  raeburn  6122:     } elsif ($context eq 'requestauthor') {
                   6123:         %tools = (
                   6124:                       requestauthor => 1,
                   6125:                  );
1.985     raeburn  6126:     } else {
                   6127:         %tools = (
                   6128:                       aboutme   => 1,
                   6129:                       blog      => 1,
1.1172.2.6  raeburn  6130:                       webdav    => 1,
1.985     raeburn  6131:                       portfolio => 1,
                   6132:                  );
                   6133:     }
1.976     raeburn  6134:     return if (!defined($tools{$tool}));
                   6135: 
                   6136:     if ((!defined($udom)) || (!defined($uname))) {
                   6137:         $udom = $env{'user.domain'};
                   6138:         $uname = $env{'user.name'};
                   6139:     }
                   6140: 
1.978     raeburn  6141:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6142:         if ($action ne 'reload') {
1.985     raeburn  6143:             if ($context eq 'requestcourses') {
                   6144:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6145:             } elsif ($context eq 'requestauthor') {
                   6146:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6147:             } else {
                   6148:                 return $env{'environment.availabletools.'.$tool};
                   6149:             }
                   6150:         }
1.976     raeburn  6151:     }
                   6152: 
1.1172.2.9  raeburn  6153:     my ($toolstatus,$inststatus,$envkey);
                   6154:     if ($context eq 'requestauthor') {
                   6155:         $envkey = $context;
                   6156:     } else {
                   6157:         $envkey = $context.'.'.$tool;
                   6158:     }
1.976     raeburn  6159: 
1.985     raeburn  6160:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6161:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6162:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6163:         $inststatus = $env{'environment.inststatus'};
                   6164:     } else {
1.1084    raeburn  6165:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6166:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6167:             $inststatus = $userenvref->{'inststatus'};
                   6168:         } else {
1.1172.2.9  raeburn  6169:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6170:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6171:             $inststatus = $userenv{'inststatus'};
                   6172:         }
1.976     raeburn  6173:     }
                   6174: 
                   6175:     if ($toolstatus ne '') {
                   6176:         if ($toolstatus) {
                   6177:             $access = 1;
                   6178:         } else {
                   6179:             $access = 0;
                   6180:         }
                   6181:         return $access;
                   6182:     }
                   6183: 
1.1084    raeburn  6184:     my ($is_adv,%domdef);
                   6185:     if (ref($is_advref) eq 'HASH') {
                   6186:         $is_adv = $is_advref->{'is_adv'};
                   6187:     } else {
                   6188:         $is_adv = &is_advanced_user($udom,$uname);
                   6189:     }
                   6190:     if (ref($domdefref) eq 'HASH') {
                   6191:         %domdef = %{$domdefref};
                   6192:     } else {
                   6193:         %domdef = &get_domain_defaults($udom);
                   6194:     }
1.976     raeburn  6195:     if (ref($domdef{$tool}) eq 'HASH') {
                   6196:         if ($is_adv) {
                   6197:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6198:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6199:                     $access = 1;
                   6200:                 } else {
                   6201:                     $access = 0;
                   6202:                 }
                   6203:                 return $access;
                   6204:             }
                   6205:         }
                   6206:         if ($inststatus ne '') {
                   6207:             my ($hasaccess,$hasnoaccess);
                   6208:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6209:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6210:                     if ($domdef{$tool}{$affiliation}) {
                   6211:                         $hasaccess = 1;
                   6212:                     } else {
                   6213:                         $hasnoaccess = 1;
                   6214:                     }
                   6215:                 }
                   6216:             }
                   6217:             if ($hasaccess || $hasnoaccess) {
                   6218:                 if ($hasaccess) {
                   6219:                     $access = 1;
                   6220:                 } elsif ($hasnoaccess) {
                   6221:                     $access = 0; 
                   6222:                 }
                   6223:                 return $access;
                   6224:             }
                   6225:         } else {
                   6226:             if ($domdef{$tool}{'default'} ne '') {
                   6227:                 if ($domdef{$tool}{'default'}) {
                   6228:                     $access = 1;
                   6229:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6230:                     $access = 0;
                   6231:                 }
                   6232:                 return $access;
                   6233:             }
                   6234:         }
                   6235:     } else {
1.1172.2.6  raeburn  6236:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6237:             $access = 1;
                   6238:         } else {
                   6239:             $access = 0;
                   6240:         }
1.976     raeburn  6241:         return $access;
                   6242:     }
                   6243: }
                   6244: 
1.1050    raeburn  6245: sub is_course_owner {
                   6246:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6247:     if (($udom eq '') || ($uname eq '')) {
                   6248:         $udom = $env{'user.domain'};
                   6249:         $uname = $env{'user.name'};
                   6250:     }
                   6251:     unless (($udom eq '') || ($uname eq '')) {
                   6252:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6253:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6254:                 return 1;
                   6255:             } else {
                   6256:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6257:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6258:                     return 1;
                   6259:                 }
                   6260:             }
                   6261:         }
                   6262:     }
                   6263:     return;
                   6264: }
                   6265: 
1.976     raeburn  6266: sub is_advanced_user {
                   6267:     my ($udom,$uname) = @_;
1.1085    raeburn  6268:     if ($udom ne '' && $uname ne '') {
                   6269:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6270:             if (wantarray) {
                   6271:                 return ($env{'user.adv'},$env{'user.author'});
                   6272:             } else {
                   6273:                 return $env{'user.adv'};
                   6274:             }
1.1085    raeburn  6275:         }
                   6276:     }
1.976     raeburn  6277:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6278:     my %allroles;
1.1128    raeburn  6279:     my ($is_adv,$is_author);
1.976     raeburn  6280:     foreach my $role (keys(%roleshash)) {
                   6281:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6282:         my $area = '/'.$tdomain.'/'.$trest;
                   6283:         if ($sec ne '') {
                   6284:             $area .= '/'.$sec;
                   6285:         }
                   6286:         if (($area ne '') && ($trole ne '')) {
                   6287:             my $spec=$trole.'.'.$area;
                   6288:             if ($trole =~ /^cr\//) {
                   6289:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6290:             } elsif ($trole ne 'gr') {
                   6291:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6292:             }
1.1128    raeburn  6293:             if ($trole eq 'au') {
                   6294:                 $is_author = 1;
                   6295:             }
1.976     raeburn  6296:         }
                   6297:     }
                   6298:     foreach my $role (keys(%allroles)) {
                   6299:         last if ($is_adv);
                   6300:         foreach my $item (split(/:/,$allroles{$role})) {
                   6301:             if ($item ne '') {
                   6302:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6303:                 if ($privilege eq 'adv') {
                   6304:                     $is_adv = 1;
                   6305:                     last;
                   6306:                 }
                   6307:             }
                   6308:         }
                   6309:     }
1.1128    raeburn  6310:     if (wantarray) {
                   6311:         return ($is_adv,$is_author);
                   6312:     }
1.976     raeburn  6313:     return $is_adv;
                   6314: }
1.798     raeburn  6315: 
1.1035    raeburn  6316: sub check_can_request {
1.1036    raeburn  6317:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6318:     my $canreq = 0;
                   6319:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6320:     my @options = ('approval','validate','autolimit');
                   6321:     my $optregex = join('|',@options);
                   6322:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6323:         foreach my $type (@{$types}) {
                   6324:             if (&usertools_access($env{'user.name'},
                   6325:                                   $env{'user.domain'},
                   6326:                                   $type,undef,'requestcourses')) {
                   6327:                 $canreq ++;
1.1036    raeburn  6328:                 if (ref($request_domains) eq 'HASH') {
                   6329:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6330:                 }
1.1035    raeburn  6331:                 if ($dom eq $env{'user.domain'}) {
                   6332:                     $can_request->{$type} = 1;
                   6333:                 }
                   6334:             }
                   6335:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6336:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6337:                 if (@curr > 0) {
1.1036    raeburn  6338:                     foreach my $item (@curr) {
                   6339:                         if (ref($request_domains) eq 'HASH') {
                   6340:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6341:                             if ($otherdom ne '') {
                   6342:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6343:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6344:                                         push(@{$request_domains->{$type}},$otherdom);
                   6345:                                     }
                   6346:                                 } else {
                   6347:                                     push(@{$request_domains->{$type}},$otherdom);
                   6348:                                 }
                   6349:                             }
                   6350:                         }
                   6351:                     }
                   6352:                     unless($dom eq $env{'user.domain'}) {
                   6353:                         $canreq ++;
1.1035    raeburn  6354:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6355:                             $can_request->{$type} = 1;
                   6356:                         }
                   6357:                     }
                   6358:                 }
                   6359:             }
                   6360:         }
                   6361:     }
                   6362:     return $canreq;
                   6363: }
                   6364: 
1.341     www      6365: # ---------------------------------------------- Custom access rule evaluation
                   6366: 
                   6367: sub customaccess {
                   6368:     my ($priv,$uri)=@_;
1.807     albertel 6369:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6370:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6371:     $udom = &LONCAPA::clean_domain($udom);
                   6372:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6373:     my $access=0;
1.800     albertel 6374:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6375: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6376: 	if ($type eq 'user') {
                   6377: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6378: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6379: 		if ($tdom) {
                   6380: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6381: 		}
1.896     albertel 6382: 		if ($tuname) {
                   6383: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6384: 		}
                   6385: 		$access=($effect eq 'allow');
                   6386: 		last;
                   6387: 	    }
                   6388: 	} else {
                   6389: 	    if ($role) {
                   6390: 		if ($role ne $urole) { next; }
                   6391: 	    }
                   6392: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6393: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6394: 		if ($tdom) {
                   6395: 		    if ($tdom ne $udom) { next; }
                   6396: 		}
                   6397: 		if ($tcrs) {
                   6398: 		    if ($tcrs ne $ucrs) { next; }
                   6399: 		}
                   6400: 		if ($tsec) {
                   6401: 		    if ($tsec ne $usec) { next; }
                   6402: 		}
                   6403: 		$access=($effect eq 'allow');
                   6404: 		last;
                   6405: 	    }
                   6406: 	    if ($realm eq '' && $role eq '') {
                   6407: 		$access=($effect eq 'allow');
                   6408: 	    }
1.402     bowersj2 6409: 	}
1.341     www      6410:     }
                   6411:     return $access;
                   6412: }
                   6413: 
1.103     harris41 6414: # ------------------------------------------------- Check for a user privilege
1.12      www      6415: 
                   6416: sub allowed {
1.810     raeburn  6417:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 6418:     my $ver_orguri=$uri;
1.439     www      6419:     $uri=&deversion($uri);
1.152     www      6420:     my $orguri=$uri;
1.52      www      6421:     $uri=&declutter($uri);
1.809     raeburn  6422: 
1.810     raeburn  6423:     if ($priv eq 'evb') {
                   6424: # Evade communication block restrictions for specified role in a course
                   6425:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6426:             return $1;
                   6427:         } else {
                   6428:             return;
                   6429:         }
                   6430:     }
                   6431: 
1.620     albertel 6432:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6433: # Free bre access to adm and meta resources
1.775     albertel 6434:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6435: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6436: 	&& ($priv eq 'bre')) {
1.14      www      6437: 	return 'F';
1.159     www      6438:     }
                   6439: 
1.545     banghart 6440: # Free bre access to user's own portfolio contents
1.714     raeburn  6441:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6442:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6443: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6444:         my %setters;
                   6445:         my ($startblock,$endblock) = 
                   6446:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6447:         if ($startblock && $endblock) {
                   6448:             return 'B';
                   6449:         } else {
                   6450:             return 'F';
                   6451:         }
1.545     banghart 6452:     }
                   6453: 
1.762     raeburn  6454: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6455:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6456:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6457:         if (exists($env{'request.course.id'})) {
                   6458:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6459:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6460:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6461:                 my $courseprivid=$env{'request.course.id'};
                   6462:                 $courseprivid=~s/\_/\//;
                   6463:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6464:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6465:                     return $1; 
1.762     raeburn  6466:                 } else {
                   6467:                     if ($env{'request.course.sec'}) {
                   6468:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6469:                     }
                   6470:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6471:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6472:                         return $2;
                   6473:                     }
1.714     raeburn  6474:                 }
                   6475:             }
                   6476:         }
                   6477:     }
                   6478: 
1.159     www      6479: # Free bre to public access
                   6480: 
                   6481:     if ($priv eq 'bre') {
1.238     www      6482:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6483: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6484:            return 'F'; 
                   6485:         }
1.238     www      6486:         if ($copyright eq 'priv') {
                   6487:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6488: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6489: 		return '';
                   6490:             }
                   6491:         }
                   6492:         if ($copyright eq 'domain') {
                   6493:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6494: 	    unless (($env{'user.domain'} eq $1) ||
                   6495:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6496: 		return '';
                   6497:             }
1.262     matthew  6498:         }
1.620     albertel 6499:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6500:             # Library role, so allow browsing of resources in this domain.
                   6501:             return 'F';
1.238     www      6502:         }
1.341     www      6503:         if ($copyright eq 'custom') {
                   6504: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6505:         }
1.14      www      6506:     }
1.264     matthew  6507:     # Domain coordinator is trying to create a course
1.620     albertel 6508:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6509:         # uri is the requested domain in this case.
                   6510:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6511:         # a role of dc for the domain in question.
1.620     albertel 6512:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6513:     }
1.29      www      6514: 
1.52      www      6515:     my $thisallowed='';
                   6516:     my $statecond=0;
                   6517:     my $courseprivid='';
                   6518: 
1.1039    raeburn  6519:     my $ownaccess;
1.1043    raeburn  6520:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6521:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6522:         if ($uri eq '') {
                   6523:             $ownaccess = 1;
                   6524:         } else {
                   6525:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6526:                 my $udom = $env{'user.domain'};
                   6527:                 my $uname = $env{'user.name'};
                   6528:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6529:                     $ownaccess = 1;
1.1040    raeburn  6530:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6531:                     unless ($uri =~ m{\.\./}) {
                   6532:                         $ownaccess = 1;
                   6533:                     }
                   6534:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6535:                     my $now = time;
                   6536:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6537:                         my $adom = $1;
                   6538:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6539:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6540:                                 my ($start,$end) = split('.',$env{$key});
                   6541:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6542:                                     $ownaccess = 1;
                   6543:                                     last;
                   6544:                                 }
                   6545:                             }
                   6546:                         }
                   6547:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6548:                         my $adom = $1;
                   6549:                         my $aname = $2;
1.1042    raeburn  6550:                         foreach my $role ('ca','aa') { 
                   6551:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6552:                                 my ($start,$end) =
                   6553:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6554:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6555:                                     $ownaccess = 1;
                   6556:                                     last;
                   6557:                                 }
1.1039    raeburn  6558:                             }
                   6559:                         }
                   6560:                     }
                   6561:                 }
                   6562:             }
                   6563:         }
                   6564:     }
                   6565: 
1.52      www      6566: # Course
                   6567: 
1.620     albertel 6568:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6569:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6570:             $thisallowed.=$1;
                   6571:         }
1.52      www      6572:     }
1.29      www      6573: 
1.52      www      6574: # Domain
                   6575: 
1.620     albertel 6576:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6577:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6578:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6579:             $thisallowed.=$1;
                   6580:         }
1.12      www      6581:     }
1.52      www      6582: 
1.1141    raeburn  6583: # User who is not author or co-author might still be able to edit
                   6584: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6585:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6586:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6587:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6588:             $thisallowed.=$1;
                   6589:         }
                   6590:     }
                   6591: 
1.52      www      6592: # Course: uri itself is a course
1.66      www      6593:     my $courseuri=$uri;
                   6594:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6595:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6596: 
1.620     albertel 6597:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6598:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6599:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6600:             $thisallowed.=$1;
                   6601:         }
1.12      www      6602:     }
1.29      www      6603: 
1.665     albertel 6604: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6605: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6606:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6607: 	$thisallowed='';
1.671     raeburn  6608:         my ($match)=&is_on_map($uri);
                   6609:         if ($match) {
                   6610:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6611:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6612:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6613:                 if (@blockers > 0) {
                   6614:                     $thisallowed = 'B';
                   6615:                 } else {
                   6616:                     $thisallowed.=$1;
                   6617:                 }
1.671     raeburn  6618:             }
                   6619:         } else {
1.705     albertel 6620:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6621:             if ($refuri) {
                   6622:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6623:                     $thisallowed='F';
1.671     raeburn  6624:                 } else {
                   6625:                     $refuri=&declutter($refuri);
                   6626:                     my ($match) = &is_on_map($refuri);
                   6627:                     if ($match) {
1.1162    raeburn  6628:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6629:                         if (@blockers > 0) {
                   6630:                             $thisallowed = 'B';
                   6631:                         } else {
                   6632:                             $thisallowed='F';
                   6633:                         }
1.671     raeburn  6634:                     }
1.669     raeburn  6635:                 }
1.671     raeburn  6636:             }
                   6637:         }
1.314     www      6638:     }
1.492     albertel 6639: 
1.766     albertel 6640:     if ($priv eq 'bre'
                   6641: 	&& $thisallowed ne 'F' 
                   6642: 	&& $thisallowed ne '2'
                   6643: 	&& &is_portfolio_url($uri)) {
                   6644: 	$thisallowed = &portfolio_access($uri);
                   6645:     }
                   6646:     
1.52      www      6647: # Full access at system, domain or course-wide level? Exit.
1.29      www      6648:     if ($thisallowed=~/F/) {
                   6649: 	return 'F';
                   6650:     }
                   6651: 
1.52      www      6652: # If this is generating or modifying users, exit with special codes
1.29      www      6653: 
1.643     www      6654:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6655: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6656: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6657: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6658: 	    unless ($auname) { return $thisallowed; }
                   6659: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6660: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6661: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6662: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6663: 	}
1.52      www      6664: 	return $thisallowed;
                   6665:     }
                   6666: #
1.103     harris41 6667: # Gathered so far: system, domain and course wide privileges
1.52      www      6668: #
                   6669: # Course: See if uri or referer is an individual resource that is part of 
                   6670: # the course
                   6671: 
1.620     albertel 6672:     if ($env{'request.course.id'}) {
1.232     www      6673: 
1.620     albertel 6674:        $courseprivid=$env{'request.course.id'};
                   6675:        if ($env{'request.course.sec'}) {
                   6676:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6677:        }
                   6678:        $courseprivid=~s/\_/\//;
                   6679:        my $checkreferer=1;
1.232     www      6680:        my ($match,$cond)=&is_on_map($uri);
                   6681:        if ($match) {
                   6682:            $statecond=$cond;
1.620     albertel 6683:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6684:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6685:                my $value = $1;
                   6686:                if ($priv eq 'bre') {
                   6687:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6688:                    if (@blockers > 0) {
                   6689:                        $thisallowed = 'B';
                   6690:                    } else {
                   6691:                        $thisallowed.=$value;
                   6692:                    }
                   6693:                } else {
                   6694:                    $thisallowed.=$value;
                   6695:                }
1.52      www      6696:                $checkreferer=0;
                   6697:            }
1.29      www      6698:        }
1.83      www      6699:        
1.148     www      6700:        if ($checkreferer) {
1.620     albertel 6701: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6702:             unless ($refuri) {
1.800     albertel 6703:                 foreach my $key (keys(%env)) {
                   6704: 		    if ($key=~/^httpref\..*\*/) {
                   6705: 			my $pattern=$key;
1.156     www      6706:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6707:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6708:                         $pattern=~s/\//\\\//g;
1.152     www      6709:                         if ($orguri=~/$pattern/) {
1.800     albertel 6710: 			    $refuri=$env{$key};
1.148     www      6711:                         }
                   6712:                     }
1.191     harris41 6713:                 }
1.148     www      6714:             }
1.232     www      6715: 
1.148     www      6716:          if ($refuri) { 
1.152     www      6717: 	  $refuri=&declutter($refuri);
1.232     www      6718:           my ($match,$cond)=&is_on_map($refuri);
                   6719:             if ($match) {
                   6720:               my $refstatecond=$cond;
1.620     albertel 6721:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6722:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6723:                   my $value = $1;
                   6724:                   if ($priv eq 'bre') {
                   6725:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6726:                       if (@blockers > 0) {
                   6727:                           $thisallowed = 'B';
                   6728:                       } else {
                   6729:                           $thisallowed.=$value;
                   6730:                       }
                   6731:                   } else {
                   6732:                       $thisallowed.=$value;
                   6733:                   }
1.53      www      6734:                   $uri=$refuri;
                   6735:                   $statecond=$refstatecond;
1.52      www      6736:               }
                   6737:           }
1.148     www      6738:         }
1.29      www      6739:        }
1.52      www      6740:    }
1.29      www      6741: 
1.52      www      6742: #
1.103     harris41 6743: # Gathered now: all privileges that could apply, and condition number
1.52      www      6744: # 
                   6745: #
                   6746: # Full or no access?
                   6747: #
1.29      www      6748: 
1.52      www      6749:     if ($thisallowed=~/F/) {
                   6750: 	return 'F';
                   6751:     }
1.29      www      6752: 
1.52      www      6753:     unless ($thisallowed) {
                   6754:         return '';
                   6755:     }
1.29      www      6756: 
1.52      www      6757: # Restrictions exist, deal with them
                   6758: #
                   6759: #   C:according to course preferences
                   6760: #   R:according to resource settings
                   6761: #   L:unless locked
                   6762: #   X:according to user session state
                   6763: #
                   6764: 
                   6765: # Possibly locked functionality, check all courses
1.54      www      6766: # Locks might take effect only after 10 minutes cache expiration for other
                   6767: # courses, and 2 minutes for current course
1.52      www      6768: 
                   6769:     my $envkey;
                   6770:     if ($thisallowed=~/L/) {
1.1000    raeburn  6771:         foreach $envkey (keys(%env)) {
1.54      www      6772:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6773:                my $courseid=$2;
                   6774:                my $roleid=$1.'.'.$2;
1.92      www      6775:                $courseid=~s/^\///;
1.54      www      6776:                my $expiretime=600;
1.620     albertel 6777:                if ($env{'request.role'} eq $roleid) {
1.54      www      6778: 		  $expiretime=120;
                   6779:                }
                   6780: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6781:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6782:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6783: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6784:                }
1.620     albertel 6785:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6786:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6787: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6788:                        &log($env{'user.domain'},$env{'user.name'},
                   6789:                             $env{'user.home'},
1.57      www      6790:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6791:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6792:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6793: 		       return '';
                   6794:                    }
                   6795:                }
1.620     albertel 6796:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6797:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6798: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6799:                        &log($env{'user.domain'},$env{'user.name'},
                   6800:                             $env{'user.home'},
1.57      www      6801:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6802:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6803:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6804: 		       return '';
                   6805:                    }
                   6806:                }
                   6807: 	   }
1.29      www      6808:        }
1.52      www      6809:     }
                   6810:    
                   6811: #
                   6812: # Rest of the restrictions depend on selected course
                   6813: #
                   6814: 
1.620     albertel 6815:     unless ($env{'request.course.id'}) {
1.766     albertel 6816: 	if ($thisallowed eq 'A') {
                   6817: 	    return 'A';
1.814     raeburn  6818:         } elsif ($thisallowed eq 'B') {
                   6819:             return 'B';
1.766     albertel 6820: 	} else {
                   6821: 	    return '1';
                   6822: 	}
1.52      www      6823:     }
1.29      www      6824: 
1.52      www      6825: #
                   6826: # Now user is definitely in a course
                   6827: #
1.53      www      6828: 
                   6829: 
                   6830: # Course preferences
                   6831: 
                   6832:    if ($thisallowed=~/C/) {
1.620     albertel 6833:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6834:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6835:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6836: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6837: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6838: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6839: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6840: 			$env{'request.course.id'});
                   6841: 	   }
1.237     www      6842:            return '';
                   6843:        }
                   6844: 
1.620     albertel 6845:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6846: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6847: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6848: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6849: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6850: 			$env{'request.course.id'});
                   6851: 	   }
1.54      www      6852:            return '';
                   6853:        }
1.53      www      6854:    }
                   6855: 
                   6856: # Resource preferences
                   6857: 
                   6858:    if ($thisallowed=~/R/) {
1.620     albertel 6859:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6860:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6861: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6862: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6863: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6864: 	   }
                   6865: 	   return '';
1.54      www      6866:        }
1.53      www      6867:    }
1.30      www      6868: 
1.246     www      6869: # Restricted by state or randomout?
1.30      www      6870: 
1.52      www      6871:    if ($thisallowed=~/X/) {
1.620     albertel 6872:       if ($env{'acc.randomout'}) {
1.579     albertel 6873: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6874:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6875:             return ''; 
                   6876:          }
1.247     www      6877:       }
                   6878:       if (&condval($statecond)) {
1.52      www      6879: 	 return '2';
                   6880:       } else {
                   6881:          return '';
                   6882:       }
                   6883:    }
1.30      www      6884: 
1.766     albertel 6885:     if ($thisallowed eq 'A') {
                   6886: 	return 'A';
1.814     raeburn  6887:     } elsif ($thisallowed eq 'B') {
                   6888:         return 'B';
1.766     albertel 6889:     }
1.52      www      6890:    return 'F';
1.232     www      6891: }
1.1162    raeburn  6892: 
1.1172.2.13  raeburn  6893: # ------------------------------------------- Check construction space access
                   6894: 
                   6895: sub constructaccess {
                   6896:     my ($url,$setpriv)=@_;
                   6897: 
                   6898: # We do not allow editing of previous versions of files
                   6899:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   6900: 
                   6901: # Get username and domain from URL
                   6902:     my ($ownername,$ownerdomain,$ownerhome);
                   6903: 
                   6904:     ($ownerdomain,$ownername) =
                   6905:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   6906: 
                   6907: # The URL does not really point to any authorspace, forget it
                   6908:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   6909: 
                   6910: # Now we need to see if the user has access to the authorspace of
                   6911: # $ownername at $ownerdomain
                   6912: 
                   6913:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   6914: # Real author for this?
                   6915:        $ownerhome = $env{'user.home'};
                   6916:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   6917:           return ($ownername,$ownerdomain,$ownerhome);
                   6918:        }
                   6919:     } else {
                   6920: # Co-author for this?
                   6921:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   6922:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   6923:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   6924:             return ($ownername,$ownerdomain,$ownerhome);
                   6925:         }
                   6926:     }
                   6927: 
                   6928: # We don't have any access right now. If we are not possibly going to do anything about this,
                   6929: # we might as well leave
                   6930:    unless ($setpriv) { return ''; }
                   6931: 
                   6932: # Backdoor access?
                   6933:     my $allowed=&allowed('eco',$ownerdomain);
                   6934: # Nope
                   6935:     unless ($allowed) { return ''; }
                   6936: # Looks like we may have access, but could be locked by the owner of the construction space
                   6937:     if ($allowed eq 'U') {
                   6938:         my %blocked=&get('environment',['domcoord.author'],
                   6939:                          $ownerdomain,$ownername);
                   6940: # Is blocked by owner
                   6941:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   6942:     }
                   6943:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   6944: # Grant temporary access
                   6945:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  6946:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  6947:         if (!$update) { $update = $then; }
                   6948:         my $refresh=$env{'user.refresh.time'};
                   6949:         if (!$refresh) { $refresh = $update; }
                   6950:         my $now = time;
                   6951:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   6952:                            $now,'ca','constructaccess');
                   6953:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   6954:         return($ownername,$ownerdomain,$ownerhome);
                   6955:     }
                   6956: # No business here
                   6957:     return '';
                   6958: }
                   6959: 
1.1162    raeburn  6960: sub get_comm_blocks {
                   6961:     my ($cdom,$cnum) = @_;
                   6962:     if ($cdom eq '' || $cnum eq '') {
                   6963:         return unless ($env{'request.course.id'});
                   6964:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6965:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6966:     }
                   6967:     my %commblocks;
                   6968:     my $hashid=$cdom.'_'.$cnum;
                   6969:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6970:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6971:         %commblocks = %{$blocksref};
                   6972:     } else {
                   6973:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6974:         my $cachetime = 600;
                   6975:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6976:     }
                   6977:     return %commblocks;
                   6978: }
                   6979: 
                   6980: sub has_comm_blocking {
                   6981:     my ($priv,$symb,$uri,$blocks) = @_;
                   6982:     return unless ($env{'request.course.id'});
                   6983:     return unless ($priv eq 'bre');
                   6984:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6985:     my %commblocks;
                   6986:     if (ref($blocks) eq 'HASH') {
                   6987:         %commblocks = %{$blocks};
                   6988:     } else {
                   6989:         %commblocks = &get_comm_blocks();
                   6990:     }
                   6991:     return unless (keys(%commblocks) > 0);
                   6992:     if (!$symb) { $symb=&symbread($uri,1); }
                   6993:     my ($map,$resid,undef)=&decode_symb($symb);
                   6994:     my %tocheck = (
                   6995:                     maps      => $map,
                   6996:                     resources => $symb,
                   6997:                   );
                   6998:     my @blockers;
                   6999:     my $now = time;
1.1163    raeburn  7000:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  7001:     foreach my $block (keys(%commblocks)) {
                   7002:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7003:             my ($start,$end) = ($1,$2);
                   7004:             if ($start <= $now && $end >= $now) {
                   7005:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7006:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7007:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7008:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   7009:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7010:                                     push(@blockers,$block);
                   7011:                                 }
                   7012:                             }
                   7013:                         }
                   7014:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7015:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   7016:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   7017:                                     push(@blockers,$block);
                   7018:                                 }
                   7019:                             }
                   7020:                         }
                   7021:                     }
                   7022:                 }
                   7023:             }
                   7024:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7025:             my $item = $1;
1.1163    raeburn  7026:             my @to_test;
1.1162    raeburn  7027:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7028:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7029:                     my $check_interval;
                   7030:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   7031:                         my @interval;
                   7032:                         my $type = 'map';
                   7033:                         if ($item eq 'course') {
                   7034:                             $type = 'course';
                   7035:                             @interval=&EXT("resource.0.interval");
                   7036:                         } else {
                   7037:                             if ($item =~ /___\d+___/) {
                   7038:                                 $type = 'resource';
                   7039:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  7040:                                 if (ref($navmap)) {                        
                   7041:                                     my $res = $navmap->getBySymb($item); 
                   7042:                                     push(@to_test,$res);
                   7043:                                 }
1.1162    raeburn  7044:                             } else {
                   7045:                                 my $mapsymb = &symbread($item,1);
                   7046:                                 if ($mapsymb) {
                   7047:                                     if (ref($navmap)) {
                   7048:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  7049:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   7050:                                         foreach my $res (@to_test) {
1.1162    raeburn  7051:                                             my $symb = $res->symb();
                   7052:                                             next if ($symb eq $mapsymb);
                   7053:                                             if ($symb ne '') {
                   7054:                                                 @interval=&EXT("resource.0.interval",$symb);
                   7055:                                                 last;
                   7056:                                             }
                   7057:                                         }
                   7058:                                     }
                   7059:                                 }
                   7060:                             }
                   7061:                         }
                   7062:                         if ($interval[0] =~ /\d+/) {
                   7063:                             my $first_access;
                   7064:                             if ($type eq 'resource') {
                   7065:                                 $first_access=&get_first_access($interval[1],$item);
                   7066:                             } elsif ($type eq 'map') {
                   7067:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   7068:                             } else {
                   7069:                                 $first_access=&get_first_access($interval[1]);
                   7070:                             }
                   7071:                             if ($first_access) {
                   7072:                                 my $timesup = $first_access+$interval[0];
                   7073:                                 if ($timesup > $now) {
1.1163    raeburn  7074:                                     foreach my $res (@to_test) {
                   7075:                                         if ($res->is_problem()) {
                   7076:                                             if ($res->completable()) {
                   7077:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   7078:                                                     push(@blockers,$block);
                   7079:                                                 }
                   7080:                                                 last;
                   7081:                                             }
                   7082:                                         }
1.1162    raeburn  7083:                                     }
                   7084:                                 }
                   7085:                             }
                   7086:                         }
                   7087:                     }
                   7088:                 }
                   7089:             }
                   7090:         }
                   7091:     }
                   7092:     return @blockers;
                   7093: }
                   7094: 
                   7095: sub check_docs_block {
                   7096:     my ($docsblock,$tocheck) =@_;
                   7097:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   7098:         return;
                   7099:     }
                   7100:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   7101:         if ($tocheck->{'maps'}) {
                   7102:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   7103:                 return 1;
                   7104:             }
                   7105:         }
                   7106:     }
                   7107:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   7108:         if ($tocheck->{'resources'}) {
                   7109:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   7110:                 return 1;
                   7111:             }
                   7112:         }
                   7113:     }
                   7114:     return;
                   7115: }
                   7116: 
1.1133    foxr     7117: #
                   7118: #   Removes the versino from a URI and
                   7119: #   splits it in to its filename and path to the filename.
                   7120: #   Seems like File::Basename could have done this more clearly.
                   7121: #   Parameters:
                   7122: #      $uri   - input URI
                   7123: #   Returns:
                   7124: #     Two element list consisting of 
                   7125: #     $pathname  - the URI up to and excluding the trailing /
                   7126: #     $filename  - The part of the URI following the last /
                   7127: #  NOTE:
                   7128: #    Another realization of this is simply:
                   7129: #    use File::Basename;
                   7130: #    ...
                   7131: #    $uri = shift;
                   7132: #    $filename = basename($uri);
                   7133: #    $path     = dirname($uri);
                   7134: #    return ($filename, $path);
                   7135: #
                   7136: #     The implementation below is probably faster however.
                   7137: #
1.710     albertel 7138: sub split_uri_for_cond {
                   7139:     my $uri=&deversion(&declutter(shift));
                   7140:     my @uriparts=split(/\//,$uri);
                   7141:     my $filename=pop(@uriparts);
                   7142:     my $pathname=join('/',@uriparts);
                   7143:     return ($pathname,$filename);
                   7144: }
1.232     www      7145: # --------------------------------------------------- Is a resource on the map?
                   7146: 
                   7147: sub is_on_map {
1.710     albertel 7148:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7149:     #Trying to find the conditional for the file
1.620     albertel 7150:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7151: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7152:     if ($match) {
1.289     bowersj2 7153: 	return (1,$1);
                   7154:     } else {
1.434     www      7155: 	return (0,0);
1.289     bowersj2 7156:     }
1.12      www      7157: }
                   7158: 
1.427     www      7159: # --------------------------------------------------------- Get symb from alias
                   7160: 
                   7161: sub get_symb_from_alias {
                   7162:     my $symb=shift;
                   7163:     my ($map,$resid,$url)=&decode_symb($symb);
                   7164: # Already is a symb
                   7165:     if ($url) { return $symb; }
                   7166: # Must be an alias
                   7167:     my $aliassymb='';
                   7168:     my %bighash;
1.620     albertel 7169:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7170:                             &GDBM_READER(),0640)) {
                   7171:         my $rid=$bighash{'mapalias_'.$symb};
                   7172: 	if ($rid) {
                   7173: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7174: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7175: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7176: 	}
                   7177:         untie %bighash;
                   7178:     }
                   7179:     return $aliassymb;
                   7180: }
                   7181: 
1.12      www      7182: # ----------------------------------------------------------------- Define Role
                   7183: 
                   7184: sub definerole {
                   7185:   if (allowed('mcr','/')) {
                   7186:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7187:     foreach my $role (split(':',$sysrole)) {
                   7188: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7189:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7190:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7191: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7192:                return "refused:s:$crole&$cqual"; 
                   7193:             }
                   7194:         }
1.191     harris41 7195:     }
1.800     albertel 7196:     foreach my $role (split(':',$domrole)) {
                   7197: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7198:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7199:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7200: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7201:                return "refused:d:$crole&$cqual"; 
                   7202:             }
                   7203:         }
1.191     harris41 7204:     }
1.800     albertel 7205:     foreach my $role (split(':',$courole)) {
                   7206: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7207:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7208:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7209: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7210:                return "refused:c:$crole&$cqual"; 
                   7211:             }
                   7212:         }
1.191     harris41 7213:     }
1.620     albertel 7214:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7215:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7216: 	        "rolesdef_$rolename=".
                   7217:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7218:     return reply($command,$env{'user.home'});
1.12      www      7219:   } else {
                   7220:     return 'refused';
                   7221:   }
1.105     harris41 7222: }
                   7223: 
                   7224: # ---------------- Make a metadata query against the network of library servers
                   7225: 
                   7226: sub metadata_query {
1.244     matthew  7227:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 7228:     my %rhash;
1.845     albertel 7229:     my %libserv = &all_library();
1.244     matthew  7230:     my @server_list = (defined($server_array) ? @$server_array
                   7231:                                               : keys(%libserv) );
                   7232:     for my $server (@server_list) {
1.118     harris41 7233: 	unless ($custom or $customshow) {
                   7234: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   7235: 	    $rhash{$server}=$reply;
                   7236: 	}
                   7237: 	else {
                   7238: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   7239: 			     &escape($custom).':'.&escape($customshow),
                   7240: 			     $server);
                   7241: 	    $rhash{$server}=$reply;
                   7242: 	}
1.112     harris41 7243:     }
1.118     harris41 7244:     return \%rhash;
1.240     www      7245: }
                   7246: 
                   7247: # ----------------------------------------- Send log queries and wait for reply
                   7248: 
                   7249: sub log_query {
                   7250:     my ($uname,$udom,$query,%filters)=@_;
                   7251:     my $uhome=&homeserver($uname,$udom);
                   7252:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7253:     my $uhost=&hostname($uhome);
1.800     albertel 7254:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7255:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7256:                        $uhome);
1.479     albertel 7257:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7258:     return get_query_reply($queryid);
                   7259: }
                   7260: 
1.818     raeburn  7261: # -------------------------- Update MySQL table for portfolio file
                   7262: 
                   7263: sub update_portfolio_table {
1.821     raeburn  7264:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7265:     if ($group ne '') {
                   7266:         $file_name =~s /^\Q$group\E//;
                   7267:     }
1.818     raeburn  7268:     my $homeserver = &homeserver($uname,$udom);
                   7269:     my $queryid=
1.821     raeburn  7270:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7271:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7272:     my $reply = &get_query_reply($queryid);
                   7273:     return $reply;
                   7274: }
                   7275: 
1.899     raeburn  7276: # -------------------------- Update MySQL allusers table
                   7277: 
                   7278: sub update_allusers_table {
                   7279:     my ($uname,$udom,$names) = @_;
                   7280:     my $homeserver = &homeserver($uname,$udom);
                   7281:     my $queryid=
                   7282:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7283:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7284:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7285:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7286:                'generation='.&escape($names->{'generation'}).'%%'.
                   7287:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7288:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7289:     return;
1.899     raeburn  7290: }
                   7291: 
1.508     raeburn  7292: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7293: 
                   7294: sub fetch_enrollment_query {
1.511     raeburn  7295:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7296:     my $homeserver;
1.547     raeburn  7297:     my $maxtries = 1;
1.508     raeburn  7298:     if ($context eq 'automated') {
                   7299:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7300:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7301:     } else {
                   7302:         $homeserver = &homeserver($cnum,$dom);
                   7303:     }
1.838     albertel 7304:     my $host=&hostname($homeserver);
1.506     raeburn  7305:     my $cmd = '';
1.1000    raeburn  7306:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7307:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7308:     }
                   7309:     $cmd =~ s/%%$//;
                   7310:     $cmd = &escape($cmd);
                   7311:     my $query = 'fetchenrollment';
1.620     albertel 7312:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7313:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7314:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7315:         return 'error: '.$queryid;
                   7316:     }
1.506     raeburn  7317:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7318:     my $tries = 1;
                   7319:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7320:         $reply = &get_query_reply($queryid);
                   7321:         $tries ++;
                   7322:     }
1.526     raeburn  7323:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7324:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7325:     } else {
1.901     albertel 7326:         my @responses = split(/:/,$reply);
1.515     raeburn  7327:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7328:             foreach my $line (@responses) {
                   7329:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7330:                 $$replyref{$key} = $value;
                   7331:             }
                   7332:         } else {
1.1117    foxr     7333:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7334:             foreach my $line (@responses) {
                   7335:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7336:                 $$replyref{$key} = $value;
                   7337:                 if ($value > 0) {
1.800     albertel 7338:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7339:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7340:                         my $destname = $pathname.'/'.$filename;
                   7341:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7342:                         if ($xml_classlist =~ /^error/) {
                   7343:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7344:                         } else {
1.506     raeburn  7345:                             if ( open(FILE,">$destname") ) {
                   7346:                                 print FILE &unescape($xml_classlist);
                   7347:                                 close(FILE);
1.526     raeburn  7348:                             } else {
                   7349:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7350:                             }
                   7351:                         }
                   7352:                     }
                   7353:                 }
                   7354:             }
                   7355:         }
                   7356:         return 'ok';
                   7357:     }
                   7358:     return 'error';
                   7359: }
                   7360: 
1.242     www      7361: sub get_query_reply {
                   7362:     my $queryid=shift;
1.1117    foxr     7363:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7364:     my $reply='';
                   7365:     for (1..100) {
                   7366: 	sleep 2;
                   7367:         if (-e $replyfile.'.end') {
1.448     albertel 7368: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7369: 		$reply = join('',<$fh>);
                   7370: 		close($fh);
1.240     www      7371: 	   } else { return 'error: reply_file_error'; }
1.242     www      7372:            return &unescape($reply);
                   7373: 	}
1.240     www      7374:     }
1.242     www      7375:     return 'timeout:'.$queryid;
1.240     www      7376: }
                   7377: 
                   7378: sub courselog_query {
1.241     www      7379: #
                   7380: # possible filters:
                   7381: # url: url or symb
                   7382: # username
                   7383: # domain
                   7384: # action: view, submit, grade
                   7385: # start: timestamp
                   7386: # end: timestamp
                   7387: #
1.240     www      7388:     my (%filters)=@_;
1.620     albertel 7389:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7390:     if ($filters{'url'}) {
                   7391: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7392:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7393:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7394:     }
1.620     albertel 7395:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7396:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7397:     return &log_query($cname,$cdom,'courselog',%filters);
                   7398: }
                   7399: 
                   7400: sub userlog_query {
1.858     raeburn  7401: #
                   7402: # possible filters:
                   7403: # action: log check role
                   7404: # start: timestamp
                   7405: # end: timestamp
                   7406: #
1.240     www      7407:     my ($uname,$udom,%filters)=@_;
                   7408:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7409: }
                   7410: 
1.506     raeburn  7411: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7412: 
                   7413: sub auto_run {
1.508     raeburn  7414:     my ($cnum,$cdom) = @_;
1.876     raeburn  7415:     my $response = 0;
                   7416:     my $settings;
                   7417:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7418:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7419:         $settings = $domconfig{'autoenroll'};
                   7420:         if ($settings->{'run'} eq '1') {
                   7421:             $response = 1;
                   7422:         }
                   7423:     } else {
1.934     raeburn  7424:         my $homeserver;
                   7425:         if (&is_course($cdom,$cnum)) {
                   7426:             $homeserver = &homeserver($cnum,$cdom);
                   7427:         } else {
                   7428:             $homeserver = &domain($cdom,'primary');
                   7429:         }
                   7430:         if ($homeserver ne 'no_host') {
                   7431:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7432:         }
1.876     raeburn  7433:     }
1.506     raeburn  7434:     return $response;
                   7435: }
1.776     albertel 7436: 
1.506     raeburn  7437: sub auto_get_sections {
1.508     raeburn  7438:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7439:     my $homeserver;
                   7440:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7441:         $homeserver = &homeserver($cnum,$cdom);
                   7442:     }
                   7443:     if (!defined($homeserver)) { 
                   7444:         if ($cdom =~ /^$match_domain$/) {
                   7445:             $homeserver = &domain($cdom,'primary');
                   7446:         }
                   7447:     }
                   7448:     my @secs;
                   7449:     if (defined($homeserver)) {
                   7450:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7451:         unless ($response eq 'refused') {
                   7452:             @secs = split(/:/,$response);
                   7453:         }
1.506     raeburn  7454:     }
                   7455:     return @secs;
                   7456: }
1.776     albertel 7457: 
1.506     raeburn  7458: sub auto_new_course {
1.1099    raeburn  7459:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7460:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7461:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7462:     return $response;
                   7463: }
1.776     albertel 7464: 
1.506     raeburn  7465: sub auto_validate_courseID {
1.508     raeburn  7466:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7467:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7468:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7469:     return $response;
                   7470: }
1.776     albertel 7471: 
1.1007    raeburn  7472: sub auto_validate_instcode {
1.1020    raeburn  7473:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7474:     my ($homeserver,$response);
                   7475:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7476:         $homeserver = &homeserver($cnum,$cdom);
                   7477:     }
                   7478:     if (!defined($homeserver)) {
                   7479:         if ($cdom =~ /^$match_domain$/) {
                   7480:             $homeserver = &domain($cdom,'primary');
                   7481:         }
                   7482:     }
1.1065    raeburn  7483:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7484:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7485:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7486:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7487: }
                   7488: 
1.506     raeburn  7489: sub auto_create_password {
1.873     raeburn  7490:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7491:     my ($homeserver,$response);
1.506     raeburn  7492:     my $create_passwd = 0;
                   7493:     my $authchk = '';
1.873     raeburn  7494:     if ($udom =~ /^$match_domain$/) {
                   7495:         $homeserver = &domain($udom,'primary');
                   7496:     }
                   7497:     if ($homeserver eq '') {
                   7498:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7499:             $homeserver = &homeserver($cnum,$cdom);
                   7500:         }
                   7501:     }
                   7502:     if ($homeserver eq '') {
                   7503:         $authchk = 'nodomain';
1.506     raeburn  7504:     } else {
1.873     raeburn  7505:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7506:         if ($response eq 'refused') {
                   7507:             $authchk = 'refused';
                   7508:         } else {
1.901     albertel 7509:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7510:         }
1.506     raeburn  7511:     }
                   7512:     return ($authparam,$create_passwd,$authchk);
                   7513: }
                   7514: 
1.706     raeburn  7515: sub auto_photo_permission {
                   7516:     my ($cnum,$cdom,$students) = @_;
                   7517:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7518:     my ($outcome,$perm_reqd,$conditions) = 
                   7519: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7520:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7521: 	return (undef,undef);
                   7522:     }
1.706     raeburn  7523:     return ($outcome,$perm_reqd,$conditions);
                   7524: }
                   7525: 
                   7526: sub auto_checkphotos {
                   7527:     my ($uname,$udom,$pid) = @_;
                   7528:     my $homeserver = &homeserver($uname,$udom);
                   7529:     my ($result,$resulttype);
                   7530:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7531: 				   &escape($uname).':'.&escape($pid),
                   7532: 				   $homeserver));
1.709     albertel 7533:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7534: 	return (undef,undef);
                   7535:     }
1.706     raeburn  7536:     if ($outcome) {
                   7537:         ($result,$resulttype) = split(/:/,$outcome);
                   7538:     } 
                   7539:     return ($result,$resulttype);
                   7540: }
                   7541: 
                   7542: sub auto_photochoice {
                   7543:     my ($cnum,$cdom) = @_;
                   7544:     my $homeserver = &homeserver($cnum,$cdom);
                   7545:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7546: 						       &escape($cdom),
                   7547: 						       $homeserver)));
1.709     albertel 7548:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7549: 	return (undef,undef);
                   7550:     }
1.706     raeburn  7551:     return ($update,$comment);
                   7552: }
                   7553: 
                   7554: sub auto_photoupdate {
                   7555:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7556:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7557:     my $host=&hostname($homeserver);
1.706     raeburn  7558:     my $cmd = '';
                   7559:     my $maxtries = 1;
1.800     albertel 7560:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7561:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7562:     }
                   7563:     $cmd =~ s/%%$//;
                   7564:     $cmd = &escape($cmd);
                   7565:     my $query = 'institutionalphotos';
                   7566:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7567:     unless ($queryid=~/^\Q$host\E\_/) {
                   7568:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7569:         return 'error: '.$queryid;
                   7570:     }
                   7571:     my $reply = &get_query_reply($queryid);
                   7572:     my $tries = 1;
                   7573:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7574:         $reply = &get_query_reply($queryid);
                   7575:         $tries ++;
                   7576:     }
                   7577:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7578:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7579:     } else {
                   7580:         my @responses = split(/:/,$reply);
                   7581:         my $outcome = shift(@responses); 
                   7582:         foreach my $item (@responses) {
                   7583:             my ($key,$value) = split(/=/,$item);
                   7584:             $$photo{$key} = $value;
                   7585:         }
                   7586:         return $outcome;
                   7587:     }
                   7588:     return 'error';
                   7589: }
                   7590: 
1.521     raeburn  7591: sub auto_instcode_format {
1.793     albertel 7592:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7593: 	$cat_order) = @_;
1.521     raeburn  7594:     my $courses = '';
1.772     raeburn  7595:     my @homeservers;
1.521     raeburn  7596:     if ($caller eq 'global') {
1.841     albertel 7597: 	my %servers = &get_servers($codedom,'library');
                   7598: 	foreach my $tryserver (keys(%servers)) {
                   7599: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7600: 		push(@homeservers,$tryserver);
                   7601: 	    }
1.584     raeburn  7602:         }
1.1022    raeburn  7603:     } elsif ($caller eq 'requests') {
                   7604:         if ($codedom =~ /^$match_domain$/) {
                   7605:             my $chome = &domain($codedom,'primary');
                   7606:             unless ($chome eq 'no_host') {
                   7607:                 push(@homeservers,$chome);
                   7608:             }
                   7609:         }
1.521     raeburn  7610:     } else {
1.772     raeburn  7611:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7612:     }
1.793     albertel 7613:     foreach my $code (keys(%{$instcodes})) {
                   7614:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7615:     }
                   7616:     chop($courses);
1.772     raeburn  7617:     my $ok_response = 0;
                   7618:     my $response;
                   7619:     while (@homeservers > 0 && $ok_response == 0) {
                   7620:         my $server = shift(@homeservers); 
                   7621:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7622:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7623:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7624: 		split(/:/,$response);
1.772     raeburn  7625:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7626:             push(@{$codetitles},&str2array($codetitles_str));
                   7627:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7628:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7629:             $ok_response = 1;
                   7630:         }
                   7631:     }
                   7632:     if ($ok_response) {
1.521     raeburn  7633:         return 'ok';
1.772     raeburn  7634:     } else {
                   7635:         return $response;
1.521     raeburn  7636:     }
                   7637: }
                   7638: 
1.792     raeburn  7639: sub auto_instcode_defaults {
                   7640:     my ($domain,$returnhash,$code_order) = @_;
                   7641:     my @homeservers;
1.841     albertel 7642: 
                   7643:     my %servers = &get_servers($domain,'library');
                   7644:     foreach my $tryserver (keys(%servers)) {
                   7645: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7646: 	    push(@homeservers,$tryserver);
                   7647: 	}
1.792     raeburn  7648:     }
1.841     albertel 7649: 
1.792     raeburn  7650:     my $response;
1.841     albertel 7651:     foreach my $server (@homeservers) {
1.792     raeburn  7652:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7653:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7654: 	
                   7655: 	foreach my $pair (split(/\&/,$response)) {
                   7656: 	    my ($name,$value)=split(/\=/,$pair);
                   7657: 	    if ($name eq 'code_order') {
                   7658: 		@{$code_order} = split(/\&/,&unescape($value));
                   7659: 	    } else {
                   7660: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7661: 	    }
                   7662: 	}
                   7663: 	return 'ok';
1.792     raeburn  7664:     }
1.841     albertel 7665: 
                   7666:     return $response;
1.1003    raeburn  7667: }
                   7668: 
                   7669: sub auto_possible_instcodes {
1.1007    raeburn  7670:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7671:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7672:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7673:         return;
                   7674:     }
1.1003    raeburn  7675:     my (@homeservers,$uhome);
                   7676:     if (defined(&domain($domain,'primary'))) {
                   7677:         $uhome=&domain($domain,'primary');
                   7678:         push(@homeservers,&domain($domain,'primary'));
                   7679:     } else {
                   7680:         my %servers = &get_servers($domain,'library');
                   7681:         foreach my $tryserver (keys(%servers)) {
                   7682:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7683:                 push(@homeservers,$tryserver);
                   7684:             }
                   7685:         }
                   7686:     }
                   7687:     my $response;
                   7688:     foreach my $server (@homeservers) {
                   7689:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7690:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7691:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7692:             split(':',$response);
                   7693:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7694:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7695:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7696:             my ($name,$value)=split('=',$item);
                   7697:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7698:         }
                   7699:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7700:             my ($name,$value)=split('=',$item);
                   7701:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7702:         }
                   7703:         return 'ok';
                   7704:     }
                   7705:     return $response;
                   7706: }
1.792     raeburn  7707: 
1.1010    raeburn  7708: sub auto_courserequest_checks {
                   7709:     my ($dom) = @_;
1.1020    raeburn  7710:     my ($homeserver,%validations);
                   7711:     if ($dom =~ /^$match_domain$/) {
                   7712:         $homeserver = &domain($dom,'primary');
                   7713:     }
                   7714:     unless ($homeserver eq 'no_host') {
                   7715:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7716:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7717:             my @items = split(/&/,$response);
                   7718:             foreach my $item (@items) {
                   7719:                 my ($key,$value) = split('=',$item);
                   7720:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7721:             }
                   7722:         }
                   7723:     }
1.1010    raeburn  7724:     return %validations; 
                   7725: }
                   7726: 
1.1020    raeburn  7727: sub auto_courserequest_validation {
                   7728:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7729:     my ($homeserver,$response);
                   7730:     if ($dom =~ /^$match_domain$/) {
                   7731:         $homeserver = &domain($dom,'primary');
                   7732:     }
                   7733:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7734:           
1.1020    raeburn  7735:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7736:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7737:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7738:                                     $homeserver));
                   7739:     }
                   7740:     return $response;
                   7741: }
                   7742: 
1.777     albertel 7743: sub auto_validate_class_sec {
1.918     raeburn  7744:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7745:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7746:     my $ownerlist;
                   7747:     if (ref($owners) eq 'ARRAY') {
                   7748:         $ownerlist = join(',',@{$owners});
                   7749:     } else {
                   7750:         $ownerlist = $owners;
                   7751:     }
1.773     raeburn  7752:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7753:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7754:     return $response;
                   7755: }
                   7756: 
1.679     raeburn  7757: # ------------------------------------------------------- Course Group routines
                   7758: 
                   7759: sub get_coursegroups {
1.809     raeburn  7760:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7761:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7762: }
                   7763: 
1.679     raeburn  7764: sub modify_coursegroup {
                   7765:     my ($cdom,$cnum,$groupsettings) = @_;
                   7766:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7767: }
                   7768: 
1.809     raeburn  7769: sub toggle_coursegroup_status {
                   7770:     my ($cdom,$cnum,$group,$action) = @_;
                   7771:     my ($from_namespace,$to_namespace);
                   7772:     if ($action eq 'delete') {
                   7773:         $from_namespace = 'coursegroups';
                   7774:         $to_namespace = 'deleted_groups';
                   7775:     } else {
                   7776:         $from_namespace = 'deleted_groups';
                   7777:         $to_namespace = 'coursegroups';
                   7778:     }
                   7779:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7780:     if (my $tmp = &error(%curr_group)) {
                   7781:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7782:         return ('read error',$tmp);
                   7783:     } else {
                   7784:         my %savedsettings = %curr_group; 
1.809     raeburn  7785:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7786:         my $deloutcome;
                   7787:         if ($result eq 'ok') {
1.809     raeburn  7788:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7789:         } else {
                   7790:             return ('write error',$result);
                   7791:         }
                   7792:         if ($deloutcome eq 'ok') {
                   7793:             return 'ok';
                   7794:         } else {
                   7795:             return ('delete error',$deloutcome);
                   7796:         }
                   7797:     }
                   7798: }
                   7799: 
1.679     raeburn  7800: sub modify_group_roles {
1.957     raeburn  7801:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7802:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7803:     my $role = 'gr/'.&escape($userprivs);
                   7804:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7805:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7806:     if ($result eq 'ok') {
                   7807:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7808:     }
1.679     raeburn  7809:     return $result;
                   7810: }
                   7811: 
                   7812: sub modify_coursegroup_membership {
                   7813:     my ($cdom,$cnum,$membership) = @_;
                   7814:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7815:     return $result;
                   7816: }
                   7817: 
1.682     raeburn  7818: sub get_active_groups {
                   7819:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7820:     my $now = time;
                   7821:     my %groups = ();
                   7822:     foreach my $key (keys(%env)) {
1.811     albertel 7823:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7824:             my ($start,$end) = split(/\./,$env{$key});
                   7825:             if (($end!=0) && ($end<$now)) { next; }
                   7826:             if (($start!=0) && ($start>$now)) { next; }
                   7827:             if ($1 eq $cdom && $2 eq $cnum) {
                   7828:                 $groups{$3} = $env{$key} ;
                   7829:             }
                   7830:         }
                   7831:     }
                   7832:     return %groups;
                   7833: }
                   7834: 
1.683     raeburn  7835: sub get_group_membership {
                   7836:     my ($cdom,$cnum,$group) = @_;
                   7837:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7838: }
                   7839: 
                   7840: sub get_users_groups {
                   7841:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7842:     my @usersgroups;
1.683     raeburn  7843:     my $cachetime=1800;
                   7844: 
                   7845:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7846:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7847:     if (defined($cached)) {
1.734     albertel 7848:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7849:     } else {  
                   7850:         $grouplist = '';
1.816     raeburn  7851:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7852:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7853:         my $access_end = $env{'course.'.$courseid.
                   7854:                               '.default_enrollment_end_date'};
                   7855:         my $now = time;
                   7856:         foreach my $key (keys(%roleshash)) {
                   7857:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7858:                 my $group = $1;
                   7859:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7860:                     my $start = $2;
                   7861:                     my $end = $1;
                   7862:                     if ($start == -1) { next; } # deleted from group
                   7863:                     if (($start!=0) && ($start>$now)) { next; }
                   7864:                     if (($end!=0) && ($end<$now)) {
                   7865:                         if ($access_end && $access_end < $now) {
                   7866:                             if ($access_end - $end < 86400) {
                   7867:                                 push(@usersgroups,$group);
1.733     raeburn  7868:                             }
                   7869:                         }
1.817     raeburn  7870:                         next;
1.733     raeburn  7871:                     }
1.817     raeburn  7872:                     push(@usersgroups,$group);
1.683     raeburn  7873:                 }
                   7874:             }
                   7875:         }
1.817     raeburn  7876:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7877:         $grouplist = join(':',@usersgroups);
                   7878:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7879:     }
1.733     raeburn  7880:     return @usersgroups;
1.683     raeburn  7881: }
                   7882: 
                   7883: sub devalidate_getgroups_cache {
                   7884:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7885:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7886: 
1.683     raeburn  7887:     my $hashid="$udom:$uname:$courseid";
                   7888:     &devalidate_cache_new('getgroups',$hashid);
                   7889: }
                   7890: 
1.12      www      7891: # ------------------------------------------------------------------ Plain Text
                   7892: 
                   7893: sub plaintext {
1.988     raeburn  7894:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7895:     if ($short =~ m{^cr/}) {
1.758     albertel 7896: 	return (split('/',$short))[-1];
                   7897:     }
1.742     raeburn  7898:     if (!defined($cid)) {
                   7899:         $cid = $env{'request.course.id'};
                   7900:     }
                   7901:     my %rolenames = (
1.1008    raeburn  7902:                       Course    => 'std',
                   7903:                       Community => 'alt1',
1.742     raeburn  7904:                     );
1.1037    raeburn  7905:     if ($cid ne '') {
                   7906:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7907:             unless ($forcedefault) {
                   7908:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7909:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7910:                 return &Apache::lonlocal::mt($roletext);
                   7911:             }
                   7912:         }
                   7913:     }
                   7914:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7915:         (defined($rolenames{$type})) && 
                   7916:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7917:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7918:     } elsif ($cid ne '') {
                   7919:         my $crstype = $env{'course.'.$cid.'.type'};
                   7920:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7921:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7922:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7923:         }
1.742     raeburn  7924:     }
1.1037    raeburn  7925:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7926: }
                   7927: 
                   7928: # ----------------------------------------------------------------- Assign Role
                   7929: 
                   7930: sub assignrole {
1.957     raeburn  7931:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7932:         $context)=@_;
1.21      www      7933:     my $mrole;
                   7934:     if ($role =~ /^cr\//) {
1.393     www      7935:         my $cwosec=$url;
1.811     albertel 7936:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7937: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7938:            my $refused = 1;
                   7939:            if ($context eq 'requestcourses') {
                   7940:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7941:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7942:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7943:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7944:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7945:                            if ($crsenv{'internal.courseowner'} eq
                   7946:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7947:                                $refused = '';
                   7948:                            }
                   7949:                        }
                   7950:                    }
                   7951:                }
                   7952:            }
                   7953:            if ($refused) {
                   7954:                &logthis('Refused custom assignrole: '.
                   7955:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7956:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7957:                return 'refused';
                   7958:            }
1.104     www      7959:         }
1.21      www      7960:         $mrole='cr';
1.678     raeburn  7961:     } elsif ($role =~ /^gr\//) {
                   7962:         my $cwogrp=$url;
1.811     albertel 7963:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7964:         unless (&allowed('mdg',$cwogrp)) {
                   7965:             &logthis('Refused group assignrole: '.
                   7966:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7967:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7968:             return 'refused';
                   7969:         }
                   7970:         $mrole='gr';
1.21      www      7971:     } else {
1.82      www      7972:         my $cwosec=$url;
1.811     albertel 7973:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7974:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7975:             my $refused;
                   7976:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7977:                 if (!(&allowed('c'.$role,$url))) {
                   7978:                     $refused = 1;
                   7979:                 }
                   7980:             } else {
                   7981:                 $refused = 1;
                   7982:             }
1.947     raeburn  7983:             if ($refused) {
1.1045    raeburn  7984:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7985:                 if (!$selfenroll && $context eq 'course') {
                   7986:                     my %crsenv;
                   7987:                     if ($role eq 'cc' || $role eq 'co') {
                   7988:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7989:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7990:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7991:                                 if ($crsenv{'internal.courseowner'} eq 
                   7992:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7993:                                     $refused = '';
                   7994:                                 }
                   7995:                             }
                   7996:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7997:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7998:                                 if ($crsenv{'internal.courseowner'} eq 
                   7999:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8000:                                     $refused = '';
                   8001:                                 }
                   8002:                             }
                   8003:                         }
                   8004:                     }
                   8005:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8006:                     $refused = '';
1.1017    raeburn  8007:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8008:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8009:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8010:                         my $wrongcc;
                   8011:                         if ($cnum =~ /^$match_community$/) {
                   8012:                             $wrongcc = 1 if ($role eq 'cc');
                   8013:                         } else {
                   8014:                             $wrongcc = 1 if ($role eq 'co');
                   8015:                         }
                   8016:                         unless ($wrongcc) {
                   8017:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8018:                             if ($crsenv{'internal.courseowner'} eq 
                   8019:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8020:                                 $refused = '';
                   8021:                             }
1.1017    raeburn  8022:                         }
                   8023:                     }
1.1172.2.9  raeburn  8024:                 } elsif ($context eq 'requestauthor') {
                   8025:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8026:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8027:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8028:                             $refused = '';
                   8029:                         } else {
                   8030:                             my %domdefaults = &get_domain_defaults($udom);
                   8031:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8032:                                 my $checkbystatus;
                   8033:                                 if ($env{'user.adv'}) {
                   8034:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8035:                                     if ($disposition eq 'automatic') {
                   8036:                                         $refused = '';
                   8037:                                     } elsif ($disposition eq '') {
                   8038:                                         $checkbystatus = 1;
                   8039:                                     }
                   8040:                                 } else {
                   8041:                                     $checkbystatus = 1;
                   8042:                                 }
                   8043:                                 if ($checkbystatus) {
                   8044:                                     if ($env{'environment.inststatus'}) {
                   8045:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8046:                                         foreach my $type (@inststatuses) {
                   8047:                                             if (($type ne '') &&
                   8048:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8049:                                                 $refused = '';
                   8050:                                             }
                   8051:                                         }
                   8052:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8053:                                         $refused = '';
                   8054:                                     }
                   8055:                                 }
                   8056:                             }
                   8057:                         }
                   8058:                     }
1.1017    raeburn  8059:                 }
                   8060:                 if ($refused) {
1.947     raeburn  8061:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8062:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8063: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8064:                     return 'refused';
                   8065:                 }
1.932     raeburn  8066:             }
1.1131    raeburn  8067:         } elsif ($role eq 'au') {
                   8068:             if ($url ne '/'.$udom.'/') {
                   8069:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8070:                          ' to assign author role for '.$uname.':'.$udom.
                   8071:                          ' in domain: '.$url.' refused (wrong domain).');
                   8072:                 return 'refused';
                   8073:             }
1.104     www      8074:         }
1.21      www      8075:         $mrole=$role;
                   8076:     }
1.620     albertel 8077:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8078:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8079:     if ($end) { $command.='_'.$end; }
1.21      www      8080:     if ($start) {
                   8081: 	if ($end) { 
1.81      www      8082:            $command.='_'.$start; 
1.21      www      8083:         } else {
1.81      www      8084:            $command.='_0_'.$start;
1.21      www      8085:         }
                   8086:     }
1.739     raeburn  8087:     my $origstart = $start;
                   8088:     my $origend = $end;
1.957     raeburn  8089:     my $delflag;
1.357     www      8090: # actually delete
                   8091:     if ($deleteflag) {
1.373     www      8092: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8093: # modify command to delete the role
1.620     albertel 8094:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8095:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8096: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8097: # set start and finish to negative values for userrolelog
                   8098:            $start=-1;
                   8099:            $end=-1;
1.957     raeburn  8100:            $delflag = 1;
1.357     www      8101:         }
                   8102:     }
                   8103: # send command
1.349     www      8104:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8105: # log new user role if status is ok
1.349     www      8106:     if ($answer eq 'ok') {
1.663     raeburn  8107: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8108:         if (($role eq 'cc') || ($role eq 'in') ||
                   8109:             ($role eq 'ep') || ($role eq 'ad') ||
                   8110:             ($role eq 'ta') || ($role eq 'st') ||
                   8111:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8112:             ($role eq 'co')) {
1.1172.2.13  raeburn  8113: # for course roles, perform group memberships changes triggered by role change.
                   8114:             unless ($role =~ /^gr/) {
                   8115:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8116:                                                  $origstart,$selfenroll,$context);
                   8117:             }
1.1172.2.9  raeburn  8118:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8119:                            $selfenroll,$context);
                   8120:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8121:                  ($role eq 'au') || ($role eq 'dc')) {
                   8122:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8123:                            $context);
                   8124:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8125:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8126:                              $context);
                   8127:         }
1.1053    raeburn  8128:         if ($role eq 'cc') {
                   8129:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8130:         }
1.349     www      8131:     }
                   8132:     return $answer;
1.169     harris41 8133: }
                   8134: 
1.1053    raeburn  8135: sub autoupdate_coowners {
                   8136:     my ($url,$end,$start,$uname,$udom) = @_;
                   8137:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8138:     if (($cdom ne '') && ($cnum ne '')) {
                   8139:         my $now = time;
                   8140:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8141:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8142:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8143:             my $instcode = $coursehash{'internal.coursecode'};
                   8144:             if ($instcode ne '') {
1.1056    raeburn  8145:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8146:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8147:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8148:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8149:                         if ($result eq 'valid') {
                   8150:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8151:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8152:                                     push(@newcoowners,$coowner);
                   8153:                                 }
                   8154:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8155:                                     push(@newcoowners,$uname.':'.$udom);
                   8156:                                 }
                   8157:                                 @newcoowners = sort(@newcoowners);
                   8158:                             } else {
                   8159:                                 push(@newcoowners,$uname.':'.$udom);
                   8160:                             }
                   8161:                         } else {
                   8162:                             if ($coursehash{'internal.co-owners'}) {
                   8163:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8164:                                     unless ($coowner eq $uname.':'.$udom) {
                   8165:                                         push(@newcoowners,$coowner);
                   8166:                                     }
                   8167:                                 }
                   8168:                                 unless (@newcoowners > 0) {
                   8169:                                     $delcoowners = 1;
                   8170:                                     $coowners = '';
                   8171:                                 }
                   8172:                             }
                   8173:                         }
                   8174:                         if (@newcoowners || $delcoowners) {
                   8175:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8176:                                             $delcoowners,@newcoowners);
                   8177:                         }
                   8178:                     }
                   8179:                 }
                   8180:             }
                   8181:         }
                   8182:     }
                   8183: }
                   8184: 
                   8185: sub store_coowners {
                   8186:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8187:     my $cid = $cdom.'_'.$cnum;
                   8188:     my ($coowners,$delresult,$putresult);
                   8189:     if (@newcoowners) {
                   8190:         $coowners = join(',',@newcoowners);
                   8191:         my %coownershash = (
                   8192:                             'internal.co-owners' => $coowners,
                   8193:                            );
                   8194:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8195:         if ($putresult eq 'ok') {
                   8196:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8197:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8198:             }
                   8199:         }
                   8200:     }
                   8201:     if ($delcoowners) {
                   8202:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8203:         if ($delresult eq 'ok') {
                   8204:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8205:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8206:             }
                   8207:         }
                   8208:     }
                   8209:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8210:         my %crsinfo =
                   8211:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8212:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8213:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8214:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8215:         }
                   8216:     }
                   8217: }
                   8218: 
1.169     harris41 8219: # -------------------------------------------------- Modify user authentication
1.197     www      8220: # Overrides without validation
                   8221: 
1.169     harris41 8222: sub modifyuserauth {
                   8223:     my ($udom,$uname,$umode,$upass)=@_;
                   8224:     my $uhome=&homeserver($uname,$udom);
1.197     www      8225:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8226:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8227:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8228:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8229:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8230: 		     &escape($upass),$uhome);
1.620     albertel 8231:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8232:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8233:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8234:     &log($udom,,$uname,$uhome,
1.620     albertel 8235:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8236:                                      $env{'user.name'}.', '.$umode.
1.197     www      8237:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8238:     unless ($reply eq 'ok') {
1.197     www      8239:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8240: 	return 'error: '.$reply;
                   8241:     }   
1.170     harris41 8242:     return 'ok';
1.80      www      8243: }
                   8244: 
1.81      www      8245: # --------------------------------------------------------------- Modify a user
1.80      www      8246: 
1.81      www      8247: sub modifyuser {
1.206     matthew  8248:     my ($udom,    $uname, $uid,
                   8249:         $umode,   $upass, $first,
                   8250:         $middle,  $last,  $gene,
1.1058    raeburn  8251:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8252:     $udom= &LONCAPA::clean_domain($udom);
                   8253:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8254:     my $showcandelete = 'none';
                   8255:     if (ref($candelete) eq 'ARRAY') {
                   8256:         if (@{$candelete} > 0) {
                   8257:             $showcandelete = join(', ',@{$candelete});
                   8258:         }
                   8259:     }
1.81      www      8260:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8261:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8262: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8263:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8264:                                      ' desiredhome not specified'). 
1.620     albertel 8265:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8266:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8267:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8268:     my $newuser;
                   8269:     if ($uhome eq 'no_host') {
                   8270:         $newuser = 1;
                   8271:     }
1.80      www      8272: # ----------------------------------------------------------------- Create User
1.406     albertel 8273:     if (($uhome eq 'no_host') && 
                   8274: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8275:         my $unhome='';
1.844     albertel 8276:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8277:             $unhome = $desiredhome;
1.620     albertel 8278: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8279: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8280:         } else { # load balancing routine for determining $unhome
1.81      www      8281:             my $loadm=10000000;
1.841     albertel 8282: 	    my %servers = &get_servers($udom,'library');
                   8283: 	    foreach my $tryserver (keys(%servers)) {
                   8284: 		my $answer=reply('load',$tryserver);
                   8285: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8286: 		    $loadm=$answer;
                   8287: 		    $unhome=$tryserver;
                   8288: 		}
1.80      www      8289: 	    }
                   8290:         }
                   8291:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8292: 	    return 'error: unable to find a home server for '.$uname.
                   8293:                    ' in domain '.$udom;
1.80      www      8294:         }
                   8295:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8296:                          &escape($upass),$unhome);
                   8297: 	unless ($reply eq 'ok') {
                   8298:             return 'error: '.$reply;
                   8299:         }   
1.230     stredwic 8300:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8301:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8302: 	    return 'error: unable verify users home machine.';
1.80      www      8303:         }
1.209     matthew  8304:     }   # End of creation of new user
1.80      www      8305: # ---------------------------------------------------------------------- Add ID
                   8306:     if ($uid) {
                   8307:        $uid=~tr/A-Z/a-z/;
                   8308:        my %uidhash=&idrget($udom,$uname);
1.196     www      8309:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8310:          && (!$forceid)) {
1.80      www      8311: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8312: 	      return 'error: user id "'.$uid.'" does not match '.
                   8313:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8314:           }
                   8315:        } else {
                   8316: 	  &idput($udom,($uname => $uid));
                   8317:        }
                   8318:     }
                   8319: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8320:     my @tmp=&get('environment',
1.899     raeburn  8321: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8322:                     'permanentemail','inststatus'],
1.134     albertel 8323: 		   $udom,$uname);
1.1075    raeburn  8324:     my (%names,%oldnames);
1.313     matthew  8325:     if ($tmp[0] =~ m/^error:.*/) { 
                   8326:         %names=(); 
                   8327:     } else {
                   8328:         %names = @tmp;
1.1075    raeburn  8329:         %oldnames = %names;
1.313     matthew  8330:     }
1.388     www      8331: #
1.1058    raeburn  8332: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8333: # of users did not contain them), do not overwrite existing values
                   8334: # unless field is in $candelete array ref.  
                   8335: #
                   8336: 
                   8337:     my @fields = ('firstname','middlename','lastname','generation',
                   8338:                   'permanentemail','id');
                   8339:     my %newvalues;
                   8340:     if (ref($candelete) eq 'ARRAY') {
                   8341:         foreach my $field (@fields) {
                   8342:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8343:                 if ($field eq 'firstname') {
                   8344:                     $names{$field} = $first;
                   8345:                 } elsif ($field eq 'middlename') {
                   8346:                     $names{$field} = $middle;
                   8347:                 } elsif ($field eq 'lastname') {
                   8348:                     $names{$field} = $last;
                   8349:                 } elsif ($field eq 'generation') { 
                   8350:                     $names{$field} = $gene;
                   8351:                 } elsif ($field eq 'permanentemail') {
                   8352:                     $names{$field} = $email;
                   8353:                 } elsif ($field eq 'id') {
                   8354:                     $names{$field}  = $uid;
                   8355:                 }
                   8356:             }
                   8357:         }
                   8358:     }
1.388     www      8359:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8360:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8361:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8362:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8363:     if ($email) {
                   8364:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8365:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8366:     }
1.899     raeburn  8367:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8368:     if (defined($inststatus)) {
                   8369:         $names{'inststatus'} = '';
                   8370:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8371:         if (ref($usertypes) eq 'HASH') {
                   8372:             my @okstatuses; 
                   8373:             foreach my $item (split(/:/,$inststatus)) {
                   8374:                 if (defined($usertypes->{$item})) {
                   8375:                     push(@okstatuses,$item);  
                   8376:                 }
                   8377:             }
                   8378:             if (@okstatuses) {
                   8379:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8380:             }
                   8381:         }
                   8382:     }
1.1075    raeburn  8383:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8384:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8385:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8386:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8387:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8388:     } else {
                   8389:         $logmsg .= ' during self creation';
                   8390:     }
1.1075    raeburn  8391:     my $changed;
                   8392:     if ($newuser) {
                   8393:         $changed = 1;
                   8394:     } else {
                   8395:         foreach my $field (@fields) {
                   8396:             if ($names{$field} ne $oldnames{$field}) {
                   8397:                 $changed = 1;
                   8398:                 last;
                   8399:             }
                   8400:         }
                   8401:     }
                   8402:     unless ($changed) {
                   8403:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8404:         &logthis($logmsg);
                   8405:         return 'ok';
                   8406:     }
                   8407:     my $reply = &put('environment', \%names, $udom,$uname);
                   8408:     if ($reply ne 'ok') { 
                   8409:         return 'error: '.$reply;
                   8410:     }
1.1087    raeburn  8411:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8412:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8413:     }
1.1075    raeburn  8414:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8415:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8416:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8417:     &logthis($logmsg);
1.134     albertel 8418:     return 'ok';
1.80      www      8419: }
                   8420: 
1.81      www      8421: # -------------------------------------------------------------- Modify student
1.80      www      8422: 
1.81      www      8423: sub modifystudent {
                   8424:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8425:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19  raeburn  8426:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8427:     if (!$cid) {
1.620     albertel 8428: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8429: 	    return 'not_in_class';
                   8430: 	}
1.80      www      8431:     }
                   8432: # --------------------------------------------------------------- Make the user
1.81      www      8433:     my $reply=&modifyuser
1.209     matthew  8434: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8435:          $desiredhome,$email,$inststatus);
1.80      www      8436:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8437:     # This will cause &modify_student_enrollment to get the uid from the
                   8438:     # students environment
                   8439:     $uid = undef if (!$forceid);
1.455     albertel 8440:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  8441: 					$gene,$usec,$end,$start,$type,$locktype,
                   8442:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8443:     return $reply;
                   8444: }
                   8445: 
                   8446: sub modify_student_enrollment {
1.1172.2.23! raeburn  8447:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
        !          8448:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8449:     my ($cdom,$cnum,$chome);
                   8450:     if (!$cid) {
1.620     albertel 8451: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8452: 	    return 'not_in_class';
                   8453: 	}
1.620     albertel 8454: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8455: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8456:     } else {
                   8457: 	($cdom,$cnum)=split(/_/,$cid);
                   8458:     }
1.620     albertel 8459:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8460:     if (!$chome) {
1.457     raeburn  8461: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8462:     }
1.455     albertel 8463:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8464:     # Make sure the user exists
1.81      www      8465:     my $uhome=&homeserver($uname,$udom);
                   8466:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8467: 	return 'error: no such user';
                   8468:     }
1.297     matthew  8469:     # Get student data if we were not given enough information
                   8470:     if (!defined($first)  || $first  eq '' || 
                   8471:         !defined($last)   || $last   eq '' || 
                   8472:         !defined($uid)    || $uid    eq '' || 
                   8473:         !defined($middle) || $middle eq '' || 
                   8474:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8475:         # They did not supply us with enough data to enroll the student, so
                   8476:         # we need to pick up more information.
1.297     matthew  8477:         my %tmp = &get('environment',
1.294     matthew  8478:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8479:                        ,$udom,$uname);
                   8480: 
1.800     albertel 8481:         #foreach my $key (keys(%tmp)) {
                   8482:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8483:         #}
1.294     matthew  8484:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8485:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8486:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8487:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8488:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8489:     }
1.556     albertel 8490:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8491:     my $user = "$uname:$udom";
                   8492:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8493:     my $reply=cput('classlist',
1.1148    raeburn  8494: 		   {$user => 
1.1172.2.19  raeburn  8495: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8496: 		   $cdom,$cnum);
1.1148    raeburn  8497:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8498:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8499:     } else { 
1.81      www      8500: 	return 'error: '.$reply;
                   8501:     }
1.297     matthew  8502:     # Add student role to user
1.83      www      8503:     my $uurl='/'.$cid;
1.81      www      8504:     $uurl=~s/\_/\//g;
                   8505:     if ($usec) {
                   8506: 	$uurl.='/'.$usec;
                   8507:     }
1.1148    raeburn  8508:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8509:                              $selfenroll,$context);
                   8510:     if ($result ne 'ok') {
                   8511:         if ($old_entry{$user} ne '') {
                   8512:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8513:         } else {
                   8514:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8515:         }
                   8516:     }
                   8517:     return $result; 
1.21      www      8518: }
                   8519: 
1.556     albertel 8520: sub format_name {
                   8521:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8522:     my $name;
                   8523:     if ($first ne 'lastname') {
                   8524: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8525:     } else {
                   8526: 	if ($lastname=~/\S/) {
                   8527: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8528: 	    $name=~s/\s+,/,/;
                   8529: 	} else {
                   8530: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8531: 	}
                   8532:     }
                   8533:     $name=~s/^\s+//;
                   8534:     $name=~s/\s+$//;
                   8535:     $name=~s/\s+/ /g;
                   8536:     return $name;
                   8537: }
                   8538: 
1.84      www      8539: # ------------------------------------------------- Write to course preferences
                   8540: 
                   8541: sub writecoursepref {
                   8542:     my ($courseid,%prefs)=@_;
                   8543:     $courseid=~s/^\///;
                   8544:     $courseid=~s/\_/\//g;
                   8545:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8546:     my $chome=homeserver($cnum,$cdomain);
                   8547:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8548: 	return 'error: no such course';
                   8549:     }
                   8550:     my $cstring='';
1.800     albertel 8551:     foreach my $pref (keys(%prefs)) {
                   8552: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8553:     }
1.84      www      8554:     $cstring=~s/\&$//;
                   8555:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8556: }
                   8557: 
                   8558: # ---------------------------------------------------------- Make/modify course
                   8559: 
                   8560: sub createcourse {
1.741     raeburn  8561:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8562:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8563:     $url=&declutter($url);
                   8564:     my $cid='';
1.1028    raeburn  8565:     if ($context eq 'requestcourses') {
                   8566:         my $can_create = 0;
                   8567:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8568:         if ($udom eq $ownerdom) {
                   8569:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8570:                                   $context)) {
                   8571:                 $can_create = 1;
                   8572:             }
                   8573:         } else {
                   8574:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8575:                                            $category);
                   8576:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8577:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8578:                 if (@curr > 0) {
                   8579:                     my @options = qw(approval validate autolimit);
                   8580:                     my $optregex = join('|',@options);
                   8581:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8582:                         $can_create = 1;
                   8583:                     }
                   8584:                 }
                   8585:             }
                   8586:         }
                   8587:         if ($can_create) {
                   8588:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8589:                 unless (&allowed('ccc',$udom)) {
                   8590:                     return 'refused'; 
                   8591:                 }
1.1017    raeburn  8592:             }
                   8593:         } else {
                   8594:             return 'refused';
                   8595:         }
1.1028    raeburn  8596:     } elsif (!&allowed('ccc',$udom)) {
                   8597:         return 'refused';
1.84      www      8598:     }
1.1011    raeburn  8599: # --------------------------------------------------------------- Get Unique ID
                   8600:     my $uname;
                   8601:     if ($cnum =~ /^$match_courseid$/) {
                   8602:         my $chome=&homeserver($cnum,$udom,'true');
                   8603:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8604:             $uname = $cnum;
                   8605:         } else {
1.1038    raeburn  8606:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8607:         }
                   8608:     } else {
1.1038    raeburn  8609:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8610:     }
                   8611:     return $uname if ($uname =~ /^error/);
                   8612: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8613:     if (!defined($course_server)) {
                   8614:         if (defined(&domain($udom,'primary'))) {
                   8615:             $course_server = &domain($udom,'primary');
                   8616:         } else {
                   8617:             $course_server = $env{'user.home'}; 
                   8618:         }
                   8619:     }
                   8620:     my %host_servers =
                   8621:         &Apache::lonnet::get_servers($udom,'library');
                   8622:     unless ($host_servers{$course_server}) {
                   8623:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8624:     }
1.84      www      8625: # ------------------------------------------------------------- Make the course
                   8626:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8627:                       $course_server);
1.84      www      8628:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8629:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8630:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8631: 	return 'error: no such course';
                   8632:     }
1.271     www      8633: # ----------------------------------------------------------------- Course made
1.516     raeburn  8634: # log existence
1.1029    raeburn  8635:     my $now = time;
1.918     raeburn  8636:     my $newcourse = {
                   8637:                     $udom.'_'.$uname => {
1.921     raeburn  8638:                                      description => $description,
                   8639:                                      inst_code   => $inst_code,
                   8640:                                      owner       => $course_owner,
                   8641:                                      type        => $crstype,
1.1029    raeburn  8642:                                      creator     => $env{'user.name'}.':'.
                   8643:                                                     $env{'user.domain'},
                   8644:                                      created     => $now,
                   8645:                                      context     => $context,
1.918     raeburn  8646:                                                 },
                   8647:                     };
1.921     raeburn  8648:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8649: # set toplevel url
1.271     www      8650:     my $topurl=$url;
                   8651:     unless ($nonstandard) {
                   8652: # ------------------------------------------ For standard courses, make top url
                   8653:         my $mapurl=&clutter($url);
1.278     www      8654:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8655:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8656: <map>
                   8657: <resource id="1" type="start"></resource>
                   8658: <resource id="2" src="$mapurl"></resource>
                   8659: <resource id="3" type="finish"></resource>
                   8660: <link index="1" from="1" to="2"></link>
                   8661: <link index="2" from="2" to="3"></link>
                   8662: </map>
                   8663: ENDINITMAP
                   8664:         $topurl=&declutter(
1.638     albertel 8665:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8666:                           );
                   8667:     }
                   8668: # ----------------------------------------------------------- Write preferences
1.84      www      8669:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8670:                      ('description'              => $description,
                   8671:                       'url'                      => $topurl,
                   8672:                       'internal.creator'         => $env{'user.name'}.':'.
                   8673:                                                     $env{'user.domain'},
                   8674:                       'internal.created'         => $now,
                   8675:                       'internal.creationcontext' => $context)
                   8676:                     );
1.84      www      8677:     return '/'.$udom.'/'.$uname;
                   8678: }
                   8679: 
1.1011    raeburn  8680: # ------------------------------------------------------------------- Create ID
                   8681: sub generate_coursenum {
1.1038    raeburn  8682:     my ($udom,$crstype) = @_;
1.1011    raeburn  8683:     my $domdesc = &domain($udom);
                   8684:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8685:     my $first;
                   8686:     if ($crstype eq 'Community') {
                   8687:         $first = '0';
                   8688:     } else {
                   8689:         $first = int(1+rand(9)); 
                   8690:     } 
                   8691:     my $uname=$first.
1.1011    raeburn  8692:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8693:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8694:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8695: # ----------------------------------------------- Make sure that does not exist
                   8696:     my $uhome=&homeserver($uname,$udom,'true');
                   8697:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8698:         if ($crstype eq 'Community') {
                   8699:             $first = '0';
                   8700:         } else {
                   8701:             $first = int(1+rand(9));
                   8702:         }
                   8703:         $uname=$first.
1.1011    raeburn  8704:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8705:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8706:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8707:         $uhome=&homeserver($uname,$udom,'true');
                   8708:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8709:             return 'error: unable to generate unique course-ID';
                   8710:         }
                   8711:     }
                   8712:     return $uname;
                   8713: }
                   8714: 
1.813     albertel 8715: sub is_course {
1.1167    droeschl 8716:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8717:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8718: 
                   8719:     return unless $cdom and $cnum;
                   8720: 
                   8721:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8722:         '.');
                   8723: 
1.1172.2.23! raeburn  8724:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 8725:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8726: }
                   8727: 
1.1015    raeburn  8728: sub store_userdata {
                   8729:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8730:     my $result;
1.1016    raeburn  8731:     if ($datakey ne '') {
1.1013    raeburn  8732:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8733:             if ($udom eq '' || $uname eq '') {
                   8734:                 $udom = $env{'user.domain'};
                   8735:                 $uname = $env{'user.name'};
                   8736:             }
                   8737:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8738:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8739:                 $result = 'error: no_host';
                   8740:             } else {
                   8741:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8742:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8743: 
                   8744:                 my $namevalue='';
                   8745:                 foreach my $key (keys(%{$storehash})) {
                   8746:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8747:                 }
                   8748:                 $namevalue=~s/\&$//;
1.1105    raeburn  8749:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8750:                                   $namevalue,$uhome);
1.1013    raeburn  8751:             }
                   8752:         } else {
                   8753:             $result = 'error: data to store was not a hash reference'; 
                   8754:         }
                   8755:     } else {
                   8756:         $result= 'error: invalid requestkey'; 
                   8757:     }
                   8758:     return $result;
                   8759: }
                   8760: 
1.21      www      8761: # ---------------------------------------------------------- Assign Custom Role
                   8762: 
                   8763: sub assigncustomrole {
1.957     raeburn  8764:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8765:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8766:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8767: }
                   8768: 
                   8769: # ----------------------------------------------------------------- Revoke Role
                   8770: 
                   8771: sub revokerole {
1.957     raeburn  8772:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8773:     my $now=time;
1.965     raeburn  8774:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8775: }
                   8776: 
                   8777: # ---------------------------------------------------------- Revoke Custom Role
                   8778: 
                   8779: sub revokecustomrole {
1.957     raeburn  8780:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8781:     my $now=time;
1.357     www      8782:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8783:            $deleteflag,$selfenroll,$context);
1.17      www      8784: }
                   8785: 
1.533     banghart 8786: # ------------------------------------------------------------ Disk usage
1.535     albertel 8787: sub diskusage {
1.955     raeburn  8788:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8789:     $directorypath =~ s/\/$//;
                   8790:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8791:                        .&escape($getpropath).':'.&escape($uname).':'
                   8792:                        .&escape($udom),homeserver($uname,$udom));
                   8793:     if ($listing eq 'unknown_cmd') {
                   8794:         if ($getpropath) {
                   8795:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8796:         }
                   8797:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8798:     }
1.514     albertel 8799:     return $listing;
1.512     banghart 8800: }
                   8801: 
1.566     banghart 8802: sub is_locked {
1.1096    raeburn  8803:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8804:     my @check;
                   8805:     my $is_locked;
1.1093    raeburn  8806:     push (@check,$file_name);
1.613     albertel 8807:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8808: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8809:     my ($tmp)=keys(%locked);
                   8810:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8811:     
1.566     banghart 8812:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8813:         $is_locked = 'false';
                   8814:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8815:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8816:                $is_locked = 'true';
1.1096    raeburn  8817:                if (ref($which) eq 'ARRAY') {
                   8818:                    push(@{$which},$entry);
                   8819:                } else {
                   8820:                    last;
                   8821:                }
1.745     raeburn  8822:            }
                   8823:        }
1.566     banghart 8824:     } else {
                   8825:         $is_locked = 'false';
                   8826:     }
1.1093    raeburn  8827:     return $is_locked;
1.566     banghart 8828: }
                   8829: 
1.759     albertel 8830: sub declutter_portfile {
                   8831:     my ($file) = @_;
1.833     albertel 8832:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8833:     return $file;
                   8834: }
                   8835: 
1.559     banghart 8836: # ------------------------------------------------------------- Mark as Read Only
                   8837: 
                   8838: sub mark_as_readonly {
                   8839:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8840:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8841:     my ($tmp)=keys(%current_permissions);
                   8842:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8843:     foreach my $file (@{$files}) {
1.759     albertel 8844: 	$file = &declutter_portfile($file);
1.561     banghart 8845:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8846:     }
1.613     albertel 8847:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8848:     return;
                   8849: }
                   8850: 
1.572     banghart 8851: # ------------------------------------------------------------Save Selected Files
                   8852: 
                   8853: sub save_selected_files {
                   8854:     my ($user, $path, @files) = @_;
                   8855:     my $filename = $user."savedfiles";
1.573     banghart 8856:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8857:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8858:     foreach my $file (@files) {
1.620     albertel 8859:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8860:     }
                   8861:     foreach my $file (@other_files) {
1.574     banghart 8862:         print (OUT $file."\n");
1.572     banghart 8863:     }
1.574     banghart 8864:     close (OUT);
1.572     banghart 8865:     return 'ok';
                   8866: }
                   8867: 
1.574     banghart 8868: sub clear_selected_files {
                   8869:     my ($user) = @_;
                   8870:     my $filename = $user."savedfiles";
1.1117    foxr     8871:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8872:     print (OUT undef);
                   8873:     close (OUT);
                   8874:     return ("ok");    
                   8875: }
                   8876: 
1.572     banghart 8877: sub files_in_path {
                   8878:     my ($user, $path) = @_;
                   8879:     my $filename = $user."savedfiles";
                   8880:     my %return_files;
1.1117    foxr     8881:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8882:     while (my $line_in = <IN>) {
1.574     banghart 8883:         chomp ($line_in);
                   8884:         my @paths_and_file = split (m!/!, $line_in);
                   8885:         my $file_part = pop (@paths_and_file);
                   8886:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8887:         $path_part.='/';
                   8888:         my $path_and_file = $path_part.$file_part;
                   8889:         if ($path_part eq $path) {
                   8890:             $return_files{$file_part}= 'selected';
                   8891:         }
                   8892:     }
1.574     banghart 8893:     close (IN);
                   8894:     return (\%return_files);
1.572     banghart 8895: }
                   8896: 
                   8897: # called in portfolio select mode, to show files selected NOT in current directory
                   8898: sub files_not_in_path {
                   8899:     my ($user, $path) = @_;
                   8900:     my $filename = $user."savedfiles";
                   8901:     my @return_files;
                   8902:     my $path_part;
1.1117    foxr     8903:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8904:     while (my $line = <IN>) {
1.572     banghart 8905:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8906:         my @paths_and_file = split(m|/|, $line);
                   8907:         my $file_part = pop(@paths_and_file);
                   8908:         chomp($file_part);
                   8909:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8910:         $path_part .= '/';
                   8911:         my $path_and_file = $path_part.$file_part;
                   8912:         if ($path_part ne $path) {
1.800     albertel 8913:             push(@return_files, ($path_and_file));
1.572     banghart 8914:         }
                   8915:     }
1.800     albertel 8916:     close(OUT);
1.574     banghart 8917:     return (@return_files);
1.572     banghart 8918: }
                   8919: 
1.745     raeburn  8920: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8921: 
1.745     raeburn  8922: sub get_portfile_permissions {
                   8923:     my ($domain,$user) = @_;
1.613     albertel 8924:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8925:     my ($tmp)=keys(%current_permissions);
                   8926:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8927:     return \%current_permissions;
                   8928: }
                   8929: 
                   8930: #---------------------------------------------Get portfolio file access controls
                   8931: 
1.749     raeburn  8932: sub get_access_controls {
1.745     raeburn  8933:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8934:     my %access;
                   8935:     my $real_file = $file;
                   8936:     $file =~ s/\.meta$//;
1.745     raeburn  8937:     if (defined($file)) {
1.749     raeburn  8938:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8939:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8940:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8941:             }
                   8942:         }
1.745     raeburn  8943:     } else {
1.749     raeburn  8944:         foreach my $key (keys(%{$current_permissions})) {
                   8945:             if ($key =~ /\0accesscontrol$/) {
                   8946:                 if (defined($group)) {
                   8947:                     if ($key !~ m-^\Q$group\E/-) {
                   8948:                         next;
                   8949:                     }
                   8950:                 }
                   8951:                 my ($fullpath) = split(/\0/,$key);
                   8952:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8953:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8954:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8955:                     }
                   8956:                 }
                   8957:             }
                   8958:         }
                   8959:     }
                   8960:     return %access;
                   8961: }
                   8962: 
                   8963: sub modify_access_controls {
                   8964:     my ($file_name,$changes,$domain,$user)=@_;
                   8965:     my ($outcome,$deloutcome);
                   8966:     my %store_permissions;
                   8967:     my %new_values;
                   8968:     my %new_control;
                   8969:     my %translation;
                   8970:     my @deletions = ();
                   8971:     my $now = time;
                   8972:     if (exists($$changes{'activate'})) {
                   8973:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8974:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8975:             my $numnew = scalar(@newitems);
                   8976:             for (my $i=0; $i<$numnew; $i++) {
                   8977:                 my $newkey = $newitems[$i];
                   8978:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8979:                 if ($newkey =~ /^\d+:/) { 
                   8980:                     $newkey =~ s/^(\d+)/$newid/;
                   8981:                     $translation{$1} = $newid;
                   8982:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8983:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8984:                     $translation{$1} = $newid;
                   8985:                 }
1.749     raeburn  8986:                 $new_values{$file_name."\0".$newkey} = 
                   8987:                                           $$changes{'activate'}{$newitems[$i]};
                   8988:                 $new_control{$newkey} = $now;
                   8989:             }
                   8990:         }
                   8991:     }
                   8992:     my %todelete;
                   8993:     my %changed_items;
                   8994:     foreach my $action ('delete','update') {
                   8995:         if (exists($$changes{$action})) {
                   8996:             if (ref($$changes{$action}) eq 'HASH') {
                   8997:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8998:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8999:                     if ($action eq 'delete') { 
                   9000:                         $todelete{$itemnum} = 1;
                   9001:                     } else {
                   9002:                         $changed_items{$itemnum} = $key;
                   9003:                     }
                   9004:                 }
1.745     raeburn  9005:             }
                   9006:         }
1.749     raeburn  9007:     }
                   9008:     # get lock on access controls for file.
                   9009:     my $lockhash = {
                   9010:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9011:                                                        ':'.$env{'user.domain'},
                   9012:                    }; 
                   9013:     my $tries = 0;
                   9014:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9015:    
                   9016:     while (($gotlock ne 'ok') && $tries <3) {
                   9017:         $tries ++;
                   9018:         sleep 1;
                   9019:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9020:     }
                   9021:     if ($gotlock eq 'ok') {
                   9022:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9023:         my ($tmp)=keys(%curr_permissions);
                   9024:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9025:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9026:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9027:             if (ref($curr_controls) eq 'HASH') {
                   9028:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9029:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9030:                     if (defined($todelete{$itemnum})) {
                   9031:                         push(@deletions,$file_name."\0".$control_item);
                   9032:                     } else {
                   9033:                         if (defined($changed_items{$itemnum})) {
                   9034:                             $new_control{$changed_items{$itemnum}} = $now;
                   9035:                             push(@deletions,$file_name."\0".$control_item);
                   9036:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9037:                         } else {
                   9038:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9039:                         }
                   9040:                     }
1.745     raeburn  9041:                 }
                   9042:             }
                   9043:         }
1.970     raeburn  9044:         my ($group);
                   9045:         if (&is_course($domain,$user)) {
                   9046:             ($group,my $file) = split(/\//,$file_name,2);
                   9047:         }
1.749     raeburn  9048:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9049:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9050:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9051:         #  remove lock
                   9052:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9053:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9054:         my $sqlresult =
1.970     raeburn  9055:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9056:                                     $group);
1.749     raeburn  9057:     } else {
                   9058:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9059:     }
1.749     raeburn  9060:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9061: }
                   9062: 
1.827     raeburn  9063: sub make_public_indefinitely {
                   9064:     my ($requrl) = @_;
                   9065:     my $now = time;
                   9066:     my $action = 'activate';
                   9067:     my $aclnum = 0;
                   9068:     if (&is_portfolio_url($requrl)) {
                   9069:         my (undef,$udom,$unum,$file_name,$group) =
                   9070:             &parse_portfolio_url($requrl);
                   9071:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9072:         my %access_controls = &get_access_controls($current_perms,
                   9073:                                                    $group,$file_name);
                   9074:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9075:             my ($num,$scope,$end,$start) = 
                   9076:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9077:             if ($scope eq 'public') {
                   9078:                 if ($start <= $now && $end == 0) {
                   9079:                     $action = 'none';
                   9080:                 } else {
                   9081:                     $action = 'update';
                   9082:                     $aclnum = $num;
                   9083:                 }
                   9084:                 last;
                   9085:             }
                   9086:         }
                   9087:         if ($action eq 'none') {
                   9088:              return 'ok';
                   9089:         } else {
                   9090:             my %changes;
                   9091:             my $newend = 0;
                   9092:             my $newstart = $now;
                   9093:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9094:             $changes{$action}{$newkey} = {
                   9095:                 type => 'public',
                   9096:                 time => {
                   9097:                     start => $newstart,
                   9098:                     end   => $newend,
                   9099:                 },
                   9100:             };
                   9101:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9102:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9103:             return $outcome;
                   9104:         }
                   9105:     } else {
                   9106:         return 'invalid';
                   9107:     }
                   9108: }
                   9109: 
1.745     raeburn  9110: #------------------------------------------------------Get Marked as Read Only
                   9111: 
                   9112: sub get_marked_as_readonly {
                   9113:     my ($domain,$user,$what,$group) = @_;
                   9114:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9115:     my @readonly_files;
1.629     banghart 9116:     my $cmp1=$what;
                   9117:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9118:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9119:         if (defined($group)) {
                   9120:             if ($file_name !~ m-^\Q$group\E/-) {
                   9121:                 next;
                   9122:             }
                   9123:         }
1.561     banghart 9124:         if (ref($value) eq "ARRAY"){
                   9125:             foreach my $stored_what (@{$value}) {
1.629     banghart 9126:                 my $cmp2=$stored_what;
1.759     albertel 9127:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9128:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9129:                 }
1.629     banghart 9130:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9131:                     push(@readonly_files, $file_name);
1.745     raeburn  9132:                     last;
1.563     banghart 9133:                 } elsif (!defined($what)) {
                   9134:                     push(@readonly_files, $file_name);
1.745     raeburn  9135:                     last;
1.561     banghart 9136:                 }
                   9137:             }
1.745     raeburn  9138:         }
1.561     banghart 9139:     }
                   9140:     return @readonly_files;
                   9141: }
1.577     banghart 9142: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9143: 
1.577     banghart 9144: sub get_marked_as_readonly_hash {
1.745     raeburn  9145:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9146:     my %readonly_files;
1.745     raeburn  9147:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9148:         if (defined($group)) {
                   9149:             if ($file_name !~ m-^\Q$group\E/-) {
                   9150:                 next;
                   9151:             }
                   9152:         }
1.577     banghart 9153:         if (ref($value) eq "ARRAY"){
                   9154:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9155:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9156:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9157:                         if ($lock_descriptor eq 'graded') {
                   9158:                             $readonly_files{$file_name} = 'graded';
                   9159:                         } elsif ($lock_descriptor eq 'handback') {
                   9160:                             $readonly_files{$file_name} = 'handback';
                   9161:                         } else {
                   9162:                             if (!exists($readonly_files{$file_name})) {
                   9163:                                 $readonly_files{$file_name} = 'locked';
                   9164:                             }
                   9165:                         }
1.745     raeburn  9166:                     }
1.750     banghart 9167:                 } 
1.577     banghart 9168:             }
                   9169:         } 
                   9170:     }
                   9171:     return %readonly_files;
                   9172: }
1.559     banghart 9173: # ------------------------------------------------------------ Unmark as Read Only
                   9174: 
                   9175: sub unmark_as_readonly {
1.629     banghart 9176:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9177:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9178:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9179:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9180:     my $symb_crs = $what;
                   9181:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9182:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9183:     my ($tmp)=keys(%current_permissions);
                   9184:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9185:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9186:     foreach my $file (@readonly_files) {
1.759     albertel 9187: 	my $clean_file = &declutter_portfile($file);
                   9188: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9189: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9190:         my @new_locks;
                   9191:         my @del_keys;
                   9192:         if (ref($current_locks) eq "ARRAY"){
                   9193:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9194:                 my $compare=$locker;
1.749     raeburn  9195:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9196:                     $compare=join('',@{$locker});
1.746     raeburn  9197:                     if ($compare ne $symb_crs) {
                   9198:                         push(@new_locks, $locker);
                   9199:                     }
1.563     banghart 9200:                 }
                   9201:             }
1.650     albertel 9202:             if (scalar(@new_locks) > 0) {
1.563     banghart 9203:                 $current_permissions{$file} = \@new_locks;
                   9204:             } else {
                   9205:                 push(@del_keys, $file);
1.613     albertel 9206:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9207:                 delete($current_permissions{$file});
1.563     banghart 9208:             }
                   9209:         }
1.561     banghart 9210:     }
1.613     albertel 9211:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9212:     return;
                   9213: }
1.512     banghart 9214: 
1.17      www      9215: # ------------------------------------------------------------ Directory lister
                   9216: 
                   9217: sub dirlist {
1.955     raeburn  9218:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9219:     $uri=~s/^\///;
                   9220:     $uri=~s/\/$//;
1.253     stredwic 9221:     my ($udom, $uname);
1.955     raeburn  9222:     if ($getuserdir) {
1.253     stredwic 9223:         $udom = $userdomain;
                   9224:         $uname = $username;
1.955     raeburn  9225:     } else {
                   9226:         (undef,$udom,$uname)=split(/\//,$uri);
                   9227:         if(defined($userdomain)) {
                   9228:             $udom = $userdomain;
                   9229:         }
                   9230:         if(defined($username)) {
                   9231:             $uname = $username;
                   9232:         }
1.253     stredwic 9233:     }
1.955     raeburn  9234:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9235: 
1.955     raeburn  9236:     $dirRoot = $perlvar{'lonDocRoot'};
                   9237:     if (defined($getpropath)) {
                   9238:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9239:         $dirRoot =~ s/\/$//;
1.955     raeburn  9240:     } elsif (defined($getuserdir)) {
                   9241:         my $subdir=$uname.'__';
                   9242:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9243:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9244:                    ."/$udom/$subdir/$uname";
                   9245:     } elsif (defined($alternateRoot)) {
                   9246:         $dirRoot = $alternateRoot;
1.751     banghart 9247:     }
1.253     stredwic 9248: 
                   9249:     if($udom) {
                   9250:         if($uname) {
1.1135    raeburn  9251:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9252:             if ($uhome eq 'no_host') {
                   9253:                 return ([],'no_host');
                   9254:             }
1.955     raeburn  9255:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9256:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9257:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9258:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9259:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9260:             } else {
                   9261:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9262:             }
1.605     matthew  9263:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9264:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9265:                 @listing_results = split(/:/,$listing);
                   9266:             } else {
                   9267:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9268:             }
1.1135    raeburn  9269:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9270:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9271:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9272:                 return ([],$listing);
                   9273:             } else {
                   9274:                 return (\@listing_results);
1.1135    raeburn  9275:             }
1.955     raeburn  9276:         } elsif(!$alternateRoot) {
1.1136    raeburn  9277:             my (%allusers,%listerror);
1.841     albertel 9278: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9279:  	    foreach my $tryserver (keys(%servers)) {
                   9280:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9281:                                   &escape($udom),$tryserver);
                   9282:                 if ($listing eq 'unknown_cmd') {
                   9283: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9284: 				      $udom, $tryserver);
                   9285:                 } else {
                   9286:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9287:                 }
1.841     albertel 9288: 		if ($listing eq 'unknown_cmd') {
                   9289: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9290: 				      $udom, $tryserver);
                   9291: 		    @listing_results = split(/:/,$listing);
                   9292: 		} else {
                   9293: 		    @listing_results =
                   9294: 			map { &unescape($_); } split(/:/,$listing);
                   9295: 		}
1.1136    raeburn  9296:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9297:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9298:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9299:                     $listerror{$tryserver} = $listing;
                   9300:                 } else {
1.841     albertel 9301: 		    foreach my $line (@listing_results) {
                   9302: 			my ($entry) = split(/&/,$line,2);
                   9303: 			$allusers{$entry} = 1;
                   9304: 		    }
                   9305: 		}
1.253     stredwic 9306:             }
1.1136    raeburn  9307:             my @alluserslist=();
1.800     albertel 9308:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9309:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9310:             }
1.1136    raeburn  9311:             return (\@alluserslist);
1.253     stredwic 9312:         } else {
1.1136    raeburn  9313:             return ([],'missing username');
1.253     stredwic 9314:         }
1.955     raeburn  9315:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9316:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9317:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9318:         return (\@all_domains);
1.955     raeburn  9319:     } else {
1.1136    raeburn  9320:         return ([],'missing domain');
1.275     stredwic 9321:     }
                   9322: }
                   9323: 
                   9324: # --------------------------------------------- GetFileTimestamp
                   9325: # This function utilizes dirlist and returns the date stamp for
                   9326: # when it was last modified.  It will also return an error of -1
                   9327: # if an error occurs
                   9328: 
                   9329: sub GetFileTimestamp {
1.955     raeburn  9330:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9331:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9332:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9333:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9334:                                     undef,$getuserdir);
                   9335:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9336:         return -1;
                   9337:     }
                   9338:     if (ref($fileref) eq 'ARRAY') {
                   9339:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9340:         # @stats contains first the filename, then the stat output
                   9341:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9342:     } else {
                   9343:         return -1;
1.253     stredwic 9344:     }
1.26      www      9345: }
                   9346: 
1.712     albertel 9347: sub stat_file {
                   9348:     my ($uri) = @_;
1.787     albertel 9349:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9350: 
1.955     raeburn  9351:     my ($udom,$uname,$file);
1.712     albertel 9352:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9353: 	($udom,$uname,$file) =
1.811     albertel 9354: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9355: 	$file = 'userfiles/'.$file;
                   9356:     }
                   9357:     if ($uri =~ m-^/res/-) {
                   9358: 	($udom,$uname) = 
1.807     albertel 9359: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9360: 	$file = $uri;
                   9361:     }
                   9362: 
                   9363:     if (!$udom || !$uname || !$file) {
                   9364: 	# unable to handle the uri
                   9365: 	return ();
                   9366:     }
1.956     raeburn  9367:     my $getpropath;
                   9368:     if ($file =~ /^userfiles\//) {
                   9369:         $getpropath = 1;
                   9370:     }
1.1136    raeburn  9371:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9372:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9373:         return ();
                   9374:     } else {
                   9375:         if (ref($listref) eq 'ARRAY') {
                   9376:             my @stats = split('&',$listref->[0]);
                   9377: 	    shift(@stats); #filename is first
                   9378: 	    return @stats;
                   9379:         }
1.712     albertel 9380:     }
                   9381:     return ();
                   9382: }
                   9383: 
1.26      www      9384: # -------------------------------------------------------- Value of a Condition
                   9385: 
1.713     albertel 9386: # gets the value of a specific preevaluated condition
                   9387: #    stored in the string  $env{user.state.<cid>}
                   9388: # or looks up a condition reference in the bighash and if if hasn't
                   9389: # already been evaluated recurses into docondval to get the value of
                   9390: # the condition, then memoizing it to 
                   9391: #   $env{user.state.<cid>.<condition>}
1.40      www      9392: sub directcondval {
                   9393:     my $number=shift;
1.620     albertel 9394:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9395: 	&Apache::lonuserstate::evalstate();
                   9396:     }
1.713     albertel 9397:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9398: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9399:     } elsif ($number =~ /^_/) {
                   9400: 	my $sub_condition;
                   9401: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9402: 		&GDBM_READER(),0640)) {
                   9403: 	    $sub_condition=$bighash{'conditions'.$number};
                   9404: 	    untie(%bighash);
                   9405: 	}
                   9406: 	my $value = &docondval($sub_condition);
1.949     raeburn  9407: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9408: 	return $value;
                   9409:     }
1.620     albertel 9410:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9411:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9412:     } else {
                   9413:        return 2;
                   9414:     }
                   9415: }
                   9416: 
1.713     albertel 9417: # get the collection of conditions for this resource
1.26      www      9418: sub condval {
                   9419:     my $condidx=shift;
1.54      www      9420:     my $allpathcond='';
1.713     albertel 9421:     foreach my $cond (split(/\|/,$condidx)) {
                   9422: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9423: 	    $allpathcond.=
                   9424: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9425: 	}
1.191     harris41 9426:     }
1.54      www      9427:     $allpathcond=~s/\|$//;
1.713     albertel 9428:     return &docondval($allpathcond);
                   9429: }
                   9430: 
                   9431: #evaluates an expression of conditions
                   9432: sub docondval {
                   9433:     my ($allpathcond) = @_;
                   9434:     my $result=0;
                   9435:     if ($env{'request.course.id'}
                   9436: 	&& defined($allpathcond)) {
                   9437: 	my $operand='|';
                   9438: 	my @stack;
                   9439: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9440: 	    if ($chunk eq '(') {
                   9441: 		push @stack,($operand,$result);
                   9442: 	    } elsif ($chunk eq ')') {
                   9443: 		my $before=pop @stack;
                   9444: 		if (pop @stack eq '&') {
                   9445: 		    $result=$result>$before?$before:$result;
                   9446: 		} else {
                   9447: 		    $result=$result>$before?$result:$before;
                   9448: 		}
                   9449: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   9450: 		$operand=$chunk;
                   9451: 	    } else {
                   9452: 		my $new=directcondval($chunk);
                   9453: 		if ($operand eq '&') {
                   9454: 		    $result=$result>$new?$new:$result;
                   9455: 		} else {
                   9456: 		    $result=$result>$new?$result:$new;
                   9457: 		}
                   9458: 	    }
                   9459: 	}
1.26      www      9460:     }
                   9461:     return $result;
1.421     albertel 9462: }
                   9463: 
                   9464: # ---------------------------------------------------- Devalidate courseresdata
                   9465: 
                   9466: sub devalidatecourseresdata {
                   9467:     my ($coursenum,$coursedomain)=@_;
                   9468:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9469:     &devalidate_cache_new('courseres',$hashid);
1.28      www      9470: }
                   9471: 
1.763     www      9472: 
1.200     www      9473: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     9474: #
                   9475: #  Parameters:
                   9476: #      $coursenum    - Number of the course.
                   9477: #      $coursedomain - Domain at which the course was created.
                   9478: #  Returns:
                   9479: #     A hash of the course parameters along (I think) with timestamps
                   9480: #     and version info.
1.877     foxr     9481: 
1.624     albertel 9482: sub get_courseresdata {
                   9483:     my ($coursenum,$coursedomain)=@_;
1.200     www      9484:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   9485:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 9486:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 9487:     my %dumpreply;
1.417     albertel 9488:     unless (defined($cached)) {
1.624     albertel 9489: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 9490: 	$result=\%dumpreply;
1.251     albertel 9491: 	my ($tmp) = keys(%dumpreply);
                   9492: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 9493: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 9494: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   9495: 	    return $tmp;
1.416     albertel 9496: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 9497: 	    $result=undef;
1.599     albertel 9498: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 9499: 	}
                   9500:     }
1.624     albertel 9501:     return $result;
                   9502: }
                   9503: 
1.633     albertel 9504: sub devalidateuserresdata {
                   9505:     my ($uname,$udom)=@_;
                   9506:     my $hashid="$udom:$uname";
                   9507:     &devalidate_cache_new('userres',$hashid);
                   9508: }
                   9509: 
1.624     albertel 9510: sub get_userresdata {
                   9511:     my ($uname,$udom)=@_;
                   9512:     #most student don\'t have any data set, check if there is some data
                   9513:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9514: 
                   9515:     my $hashid="$udom:$uname";
                   9516:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9517:     if (!defined($cached)) {
                   9518: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9519: 	$result=\%resourcedata;
                   9520: 	&do_cache_new('userres',$hashid,$result,600);
                   9521:     }
                   9522:     my ($tmp)=keys(%$result);
                   9523:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9524: 	return $result;
                   9525:     }
                   9526:     #error 2 occurs when the .db doesn't exist
                   9527:     if ($tmp!~/error: 2 /) {
1.672     albertel 9528: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9529: 		 " Trying to get resource data for ".
                   9530: 		 $uname." at ".$udom.": ".
                   9531: 		 $tmp."</font>");
                   9532:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9533: 	#&EXT_cache_set($udom,$uname);
                   9534: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9535: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9536:     }
                   9537:     return $tmp;
                   9538: }
1.879     foxr     9539: #----------------------------------------------- resdata - return resource data
                   9540: #  Purpose:
                   9541: #    Return resource data for either users or for a course.
                   9542: #  Parameters:
                   9543: #     $name      - Course/user name.
                   9544: #     $domain    - Name of the domain the user/course is registered on.
                   9545: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9546: #     @which     - Array of names of resources desired.
                   9547: #  Returns:
                   9548: #     The value of the first reasource in @which that is found in the
                   9549: #     resource hash.
                   9550: #  Exceptional Conditions:
                   9551: #     If the $type passed in is not valid (not the string 'course' or 
                   9552: #     'user', an undefined  reference is returned.
                   9553: #     If none of the resources are found, an undef is returned
1.624     albertel 9554: sub resdata {
                   9555:     my ($name,$domain,$type,@which)=@_;
                   9556:     my $result;
                   9557:     if ($type eq 'course') {
                   9558: 	$result=&get_courseresdata($name,$domain);
                   9559:     } elsif ($type eq 'user') {
                   9560: 	$result=&get_userresdata($name,$domain);
                   9561:     }
                   9562:     if (!ref($result)) { return $result; }    
1.251     albertel 9563:     foreach my $item (@which) {
1.927     albertel 9564: 	if (defined($result->{$item->[0]})) {
                   9565: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9566: 	}
1.250     albertel 9567:     }
1.291     albertel 9568:     return undef;
1.200     www      9569: }
                   9570: 
1.379     matthew  9571: #
                   9572: # EXT resource caching routines
                   9573: #
                   9574: 
                   9575: sub clear_EXT_cache_status {
1.383     albertel 9576:     &delenv('cache.EXT.');
1.379     matthew  9577: }
                   9578: 
                   9579: sub EXT_cache_status {
                   9580:     my ($target_domain,$target_user) = @_;
1.383     albertel 9581:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9582:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9583:         # We know already the user has no data
                   9584:         return 1;
                   9585:     } else {
                   9586:         return 0;
                   9587:     }
                   9588: }
                   9589: 
                   9590: sub EXT_cache_set {
                   9591:     my ($target_domain,$target_user) = @_;
1.383     albertel 9592:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9593:     #&appenv({$cachename => time});
1.379     matthew  9594: }
                   9595: 
1.28      www      9596: # --------------------------------------------------------- Value of a Variable
1.58      www      9597: sub EXT {
1.715     albertel 9598: 
1.395     albertel 9599:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9600:     unless ($varname) { return ''; }
1.218     albertel 9601:     #get real user name/domain, courseid and symb
                   9602:     my $courseid;
1.359     albertel 9603:     my $publicuser;
1.427     www      9604:     if ($symbparm) {
                   9605: 	$symbparm=&get_symb_from_alias($symbparm);
                   9606:     }
1.218     albertel 9607:     if (!($uname && $udom)) {
1.790     albertel 9608:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9609:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9610:     } else {
1.620     albertel 9611: 	$courseid=$env{'request.course.id'};
1.218     albertel 9612:     }
1.48      www      9613:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9614:     my $rest;
1.320     albertel 9615:     if (defined($therest[0])) {
1.48      www      9616:        $rest=join('.',@therest);
                   9617:     } else {
                   9618:        $rest='';
                   9619:     }
1.320     albertel 9620: 
1.57      www      9621:     my $qualifierrest=$qualifier;
                   9622:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9623:     my $spacequalifierrest=$space;
                   9624:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9625:     if ($realm eq 'user') {
1.48      www      9626: # --------------------------------------------------------------- user.resource
                   9627: 	if ($space eq 'resource') {
1.651     albertel 9628: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9629: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9630: 		 &&
1.744     albertel 9631: 		 ($symbparm eq &symbread()) ) {	
                   9632: 		# if we are in the middle of processing the resource the
                   9633: 		# get the value we are planning on committing
                   9634:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9635:                     return $Apache::lonhomework::results{$qualifierrest};
                   9636:                 } else {
                   9637:                     return $Apache::lonhomework::history{$qualifierrest};
                   9638:                 }
1.335     albertel 9639: 	    } else {
1.359     albertel 9640: 		my %restored;
1.620     albertel 9641: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9642: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9643: 		} else {
                   9644: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9645: 		}
1.335     albertel 9646: 		return $restored{$qualifierrest};
                   9647: 	    }
1.48      www      9648: # ----------------------------------------------------------------- user.access
                   9649:         } elsif ($space eq 'access') {
1.218     albertel 9650: 	    # FIXME - not supporting calls for a specific user
1.48      www      9651:             return &allowed($qualifier,$rest);
                   9652: # ------------------------------------------ user.preferences, user.environment
                   9653:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9654: 	    if (($uname eq $env{'user.name'}) &&
                   9655: 		($udom eq $env{'user.domain'})) {
                   9656: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9657: 	    } else {
1.359     albertel 9658: 		my %returnhash;
                   9659: 		if (!$publicuser) {
                   9660: 		    %returnhash=&userenvironment($udom,$uname,
                   9661: 						 $qualifierrest);
                   9662: 		}
1.218     albertel 9663: 		return $returnhash{$qualifierrest};
                   9664: 	    }
1.48      www      9665: # ----------------------------------------------------------------- user.course
                   9666:         } elsif ($space eq 'course') {
1.218     albertel 9667: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9668:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9669: # ------------------------------------------------------------------- user.role
                   9670:         } elsif ($space eq 'role') {
1.218     albertel 9671: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9672:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9673:             if ($qualifier eq 'value') {
                   9674: 		return $role;
                   9675:             } elsif ($qualifier eq 'extent') {
                   9676:                 return $where;
                   9677:             }
                   9678: # ----------------------------------------------------------------- user.domain
                   9679:         } elsif ($space eq 'domain') {
1.218     albertel 9680:             return $udom;
1.48      www      9681: # ------------------------------------------------------------------- user.name
                   9682:         } elsif ($space eq 'name') {
1.218     albertel 9683:             return $uname;
1.48      www      9684: # ---------------------------------------------------- Any other user namespace
1.29      www      9685:         } else {
1.359     albertel 9686: 	    my %reply;
                   9687: 	    if (!$publicuser) {
                   9688: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9689: 	    }
                   9690: 	    return $reply{$qualifierrest};
1.48      www      9691:         }
1.236     www      9692:     } elsif ($realm eq 'query') {
                   9693: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9694:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9695: 						[$spacequalifierrest]);
1.620     albertel 9696: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9697:    } elsif ($realm eq 'request') {
1.48      www      9698: # ------------------------------------------------------------- request.browser
                   9699:         if ($space eq 'browser') {
1.1145    bisitz   9700:             return $env{'browser.'.$qualifier};
1.57      www      9701: # ------------------------------------------------------------ request.filename
                   9702:         } else {
1.620     albertel 9703:             return $env{'request.'.$spacequalifierrest};
1.29      www      9704:         }
1.28      www      9705:     } elsif ($realm eq 'course') {
1.48      www      9706: # ---------------------------------------------------------- course.description
1.620     albertel 9707:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9708:     } elsif ($realm eq 'resource') {
1.165     www      9709: 
1.620     albertel 9710: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9711: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9712: 	}
1.693     albertel 9713: 
                   9714: 	if ($space eq 'title') {
                   9715: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9716: 	    return &gettitle($symbparm);
                   9717: 	}
                   9718: 	
                   9719: 	if ($space eq 'map') {
                   9720: 	    my ($map) = &decode_symb($symbparm);
                   9721: 	    return &symbread($map);
                   9722: 	}
1.905     albertel 9723: 	if ($space eq 'filename') {
                   9724: 	    if ($symbparm) {
                   9725: 		return &clutter((&decode_symb($symbparm))[2]);
                   9726: 	    }
                   9727: 	    return &hreflocation('',$env{'request.filename'});
                   9728: 	}
1.693     albertel 9729: 
                   9730: 	my ($section, $group, @groups);
1.593     albertel 9731: 	my ($courselevelm,$courselevel);
1.539     albertel 9732: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9733: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9734: 
1.218     albertel 9735: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9736: 
1.60      www      9737: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9738: 	    my $symbp=$symbparm;
1.735     albertel 9739: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9740: 
                   9741: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9742: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9743: 
1.620     albertel 9744: 	    if (($env{'user.name'} eq $uname) &&
                   9745: 		($env{'user.domain'} eq $udom)) {
                   9746: 		$section=$env{'request.course.sec'};
1.733     raeburn  9747:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9748:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9749: 	    } else {
1.539     albertel 9750: 		if (! defined($usection)) {
1.551     albertel 9751: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9752: 		} else {
                   9753: 		    $section = $usection;
                   9754: 		}
1.733     raeburn  9755:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9756: 	    }
                   9757: 
                   9758: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9759: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9760: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9761: 
1.593     albertel 9762: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9763: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9764: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9765: 
1.60      www      9766: # ----------------------------------------------------------- first, check user
1.624     albertel 9767: 
                   9768: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9769: 				       ([$courselevelr,'resource'],
                   9770: 					[$courselevelm,'map'     ],
                   9771: 					[$courselevel, 'course'  ]));
1.931     albertel 9772: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9773: 
1.594     albertel 9774: # ------------------------------------------------ second, check some of course
1.684     raeburn  9775:             my $coursereply;
1.691     raeburn  9776:             if (@groups > 0) {
                   9777:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9778:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9779:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9780:             }
1.96      www      9781: 
1.684     raeburn  9782: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9783: 				  $env{'course.'.$courseid.'.domain'},
                   9784: 				  'course',
                   9785: 				  ([$seclevelr,   'resource'],
                   9786: 				   [$seclevelm,   'map'     ],
                   9787: 				   [$seclevel,    'course'  ],
                   9788: 				   [$courselevelr,'resource']));
                   9789: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9790: 
1.60      www      9791: # ------------------------------------------------------ third, check map parms
1.218     albertel 9792: 	    my %parmhash=();
                   9793: 	    my $thisparm='';
                   9794: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9795: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9796: 		    &GDBM_READER(),0640)) {
1.218     albertel 9797: 		$thisparm=$parmhash{$symbparm};
                   9798: 		untie(%parmhash);
                   9799: 	    }
1.927     albertel 9800: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9801: 	}
1.594     albertel 9802: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9803: 
1.218     albertel 9804: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9805: 	my $filename;
                   9806: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9807: 	if ($symbparm) {
1.409     www      9808: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9809: 	} else {
1.620     albertel 9810: 	    $filename=$env{'request.filename'};
1.282     albertel 9811: 	}
                   9812: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9813: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9814: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9815: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9816: 
1.927     albertel 9817: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9818: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9819: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9820: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9821: 				     $env{'course.'.$courseid.'.domain'},
                   9822: 				     'course',
1.927     albertel 9823: 				     ([$courselevelm,'map'   ],
                   9824: 				      [$courselevel, 'course']));
                   9825: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9826: 	}
1.145     www      9827: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9828: 	unless ($space eq '0') {
1.336     albertel 9829: 	    my @parts=split(/_/,$space);
                   9830: 	    my $id=pop(@parts);
                   9831: 	    my $part=join('_',@parts);
                   9832: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9833: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9834: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9835: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9836: 	}
1.395     albertel 9837: 	if ($recurse) { return undef; }
                   9838: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9839: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9840: # ---------------------------------------------------- Any other user namespace
                   9841:     } elsif ($realm eq 'environment') {
                   9842: # ----------------------------------------------------------------- environment
1.620     albertel 9843: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9844: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9845: 	} else {
1.770     albertel 9846: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9847: 		return '';
                   9848: 	    }
1.219     albertel 9849: 	    my %returnhash=&userenvironment($udom,$uname,
                   9850: 					    $spacequalifierrest);
                   9851: 	    return $returnhash{$spacequalifierrest};
                   9852: 	}
1.28      www      9853:     } elsif ($realm eq 'system') {
1.48      www      9854: # ----------------------------------------------------------------- system.time
                   9855: 	if ($space eq 'time') {
                   9856: 	    return time;
                   9857:         }
1.696     albertel 9858:     } elsif ($realm eq 'server') {
                   9859: # ----------------------------------------------------------------- system.time
                   9860: 	if ($space eq 'name') {
                   9861: 	    return $ENV{'SERVER_NAME'};
                   9862:         }
1.28      www      9863:     }
1.48      www      9864:     return '';
1.61      www      9865: }
                   9866: 
1.927     albertel 9867: sub get_reply {
                   9868:     my ($reply_value) = @_;
1.940     raeburn  9869:     if (ref($reply_value) eq 'ARRAY') {
                   9870:         if (wantarray) {
                   9871: 	    return @$reply_value;
                   9872:         }
                   9873:         return $reply_value->[0];
                   9874:     } else {
                   9875:         return $reply_value;
1.927     albertel 9876:     }
                   9877: }
                   9878: 
1.691     raeburn  9879: sub check_group_parms {
                   9880:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9881:     my @groupitems = ();
                   9882:     my $resultitem;
1.927     albertel 9883:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9884:     foreach my $group (@{$groups}) {
                   9885:         foreach my $level (@levels) {
1.927     albertel 9886:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9887:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9888:         }
                   9889:     }
                   9890:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9891:                             $env{'course.'.$courseid.'.domain'},
                   9892:                                      'course',@groupitems);
                   9893:     return $coursereply;
                   9894: }
                   9895: 
                   9896: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9897:     my ($courseid,@groups) = @_;
                   9898:     @groups = sort(@groups);
1.691     raeburn  9899:     return @groups;
                   9900: }
                   9901: 
1.395     albertel 9902: sub packages_tab_default {
                   9903:     my ($uri,$varname)=@_;
                   9904:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9905: 
                   9906:     my (@extension,@specifics,$do_default);
                   9907:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9908: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9909: 	if ($pack_type eq 'default') {
                   9910: 	    $do_default=1;
                   9911: 	} elsif ($pack_type eq 'extension') {
                   9912: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9913: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9914: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9915: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9916: 	}
                   9917:     }
                   9918:     # first look for a package that matches the requested part id
                   9919:     foreach my $package (@specifics) {
                   9920: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9921: 	next if ($pack_part ne $part);
                   9922: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9923: 	    return $packagetab{"$pack_type&$name&default"};
                   9924: 	}
                   9925:     }
                   9926:     # look for any possible matching non extension_ package
                   9927:     foreach my $package (@specifics) {
                   9928: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9929: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9930: 	    return $packagetab{"$pack_type&$name&default"};
                   9931: 	}
1.585     albertel 9932: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9933: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9934: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9935: 	}
                   9936:     }
1.738     albertel 9937:     # look for any posible extension_ match
                   9938:     foreach my $package (@extension) {
                   9939: 	my ($package,$pack_type)=@{$package};
                   9940: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9941: 	    return $packagetab{"$pack_type&$name&default"};
                   9942: 	}
                   9943: 	if (defined($packagetab{$package."&$name&default"})) {
                   9944: 	    return $packagetab{$package."&$name&default"};
                   9945: 	}
                   9946:     }
                   9947:     # look for a global default setting
                   9948:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9949: 	return $packagetab{"default&$name&default"};
                   9950:     }
1.395     albertel 9951:     return undef;
                   9952: }
                   9953: 
1.334     albertel 9954: sub add_prefix_and_part {
                   9955:     my ($prefix,$part)=@_;
                   9956:     my $keyroot;
                   9957:     if (defined($prefix) && $prefix !~ /^__/) {
                   9958: 	# prefix that has a part already
                   9959: 	$keyroot=$prefix;
                   9960:     } elsif (defined($prefix)) {
                   9961: 	# prefix that is missing a part
                   9962: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9963:     } else {
                   9964: 	# no prefix at all
                   9965: 	if (defined($part)) { $keyroot='_'.$part; }
                   9966:     }
                   9967:     return $keyroot;
                   9968: }
                   9969: 
1.71      www      9970: # ---------------------------------------------------------------- Get metadata
                   9971: 
1.599     albertel 9972: my %metaentry;
1.1070    www      9973: my %importedpartids;
1.71      www      9974: sub metadata {
1.176     www      9975:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9976:     $uri=&declutter($uri);
1.288     albertel 9977:     # if it is a non metadata possible uri return quickly
1.529     albertel 9978:     if (($uri eq '') || 
                   9979: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  9980: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  9981:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9982: 	return undef;
                   9983:     }
1.1140    www      9984:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9985: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9986: 	return undef;
1.288     albertel 9987:     }
1.73      www      9988:     my $filename=$uri;
                   9989:     $uri=~s/\.meta$//;
1.172     www      9990: #
                   9991: # Is the metadata already cached?
1.177     www      9992: # Look at timestamp of caching
1.172     www      9993: # Everything is cached by the main uri, libraries are never directly cached
                   9994: #
1.428     albertel 9995:     if (!defined($liburi)) {
1.599     albertel 9996: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9997: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9998:     }
                   9999:     {
1.1069    www      10000: # Imported parts would go here
1.1070    www      10001:         my %importedids=();
                   10002:         my @origfileimportpartids=();
1.1069    www      10003:         my $importedparts=0;
1.172     www      10004: #
                   10005: # Is this a recursive call for a library?
                   10006: #
1.599     albertel 10007: #	if (! exists($metacache{$uri})) {
                   10008: #	    $metacache{$uri}={};
                   10009: #	}
1.924     albertel 10010: 	my $cachetime = 60*60;
1.171     www      10011:         if ($liburi) {
                   10012: 	    $liburi=&declutter($liburi);
                   10013:             $filename=$liburi;
1.401     bowersj2 10014:         } else {
1.599     albertel 10015: 	    &devalidate_cache_new('meta',$uri);
                   10016: 	    undef(%metaentry);
1.401     bowersj2 10017: 	}
1.140     www      10018:         my %metathesekeys=();
1.73      www      10019:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10020: 	my $metastring;
1.1140    www      10021: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10022: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10023: 	    $metastring = 
1.929     albertel 10024: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10025: 					  ('grade_target' => 'meta'));
                   10026: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10027: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10028:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10029: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10030: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10031: 	    $metastring=&getfile($file);
1.489     albertel 10032: 	}
1.208     albertel 10033:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10034:         my $token;
1.140     www      10035:         undef %metathesekeys;
1.71      www      10036:         while ($token=$parser->get_token) {
1.339     albertel 10037: 	    if ($token->[0] eq 'S') {
                   10038: 		if (defined($token->[2]->{'package'})) {
1.172     www      10039: #
                   10040: # This is a package - get package info
                   10041: #
1.339     albertel 10042: 		    my $package=$token->[2]->{'package'};
                   10043: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10044: 		    if (defined($token->[2]->{'id'})) { 
                   10045: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10046: 		    }
1.599     albertel 10047: 		    if ($metaentry{':packages'}) {
                   10048: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10049: 		    } else {
1.599     albertel 10050: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10051: 		    }
1.736     albertel 10052: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10053: 			my $part=$keyroot;
                   10054: 			$part=~s/^\_//;
1.736     albertel 10055: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10056: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10057: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10058: 			    # ignore package.tab specified default values
                   10059:                             # here &package_tab_default() will fetch those
                   10060: 			    if ($subp eq 'default') { next; }
1.736     albertel 10061: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10062: 			    my $unikey;
                   10063: 			    if ($pack =~ /_0$/) {
                   10064: 				$unikey='parameter_0_'.$name;
                   10065: 				$part=0;
                   10066: 			    } else {
                   10067: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10068: 			    }
1.339     albertel 10069: 			    if ($subp eq 'display') {
                   10070: 				$value.=' [Part: '.$part.']';
                   10071: 			    }
1.599     albertel 10072: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10073: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10074: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10075: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10076: 			    }
1.599     albertel 10077: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10078: 				$metaentry{':'.$unikey}=
                   10079: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10080: 			    }
1.339     albertel 10081: 			}
                   10082: 		    }
                   10083: 		} else {
1.172     www      10084: #
                   10085: # This is not a package - some other kind of start tag
1.339     albertel 10086: #
                   10087: 		    my $entry=$token->[1];
1.1068    www      10088: 		    my $unikey='';
1.175     www      10089: 
1.339     albertel 10090: 		    if ($entry eq 'import') {
1.175     www      10091: #
                   10092: # Importing a library here
1.339     albertel 10093: #
1.1067    www      10094:                         my $location=$parser->get_text('/import');
                   10095:                         my $dir=$filename;
                   10096:                         $dir=~s|[^/]*$||;
                   10097:                         $location=&filelocation($dir,$location);
1.1069    www      10098:                        
1.1068    www      10099:                         my $importmode=$token->[2]->{'importmode'};
                   10100:                         if ($importmode eq 'problem') {
1.1069    www      10101: # Import as problem/response
1.1068    www      10102:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10103:                         } elsif ($importmode eq 'part') {
                   10104: # Import as part(s)
1.1069    www      10105:                            $importedparts=1;
                   10106: # We need to get the original file and the imported file to get the part order correct
                   10107: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10108: # Load and inspect original file
1.1070    www      10109:                            if ($#origfileimportpartids<0) {
                   10110:                               undef(%importedpartids);
                   10111:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10112:                               my $origfile=&getfile($origfilelocation);
                   10113:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10114:                            }
                   10115: 
1.1069    www      10116: # Load and inspect imported file
                   10117:                            my $impfile=&getfile($location);
                   10118:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10119:                            if ($#impfilepartids>=0) {
                   10120: # This problem had parts
1.1070    www      10121:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10122:                            } else {
                   10123: # Importing by turning a single problem into a problem part
                   10124: # It gets the import-tags ID as part-ID
                   10125:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10126:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10127:                            }
1.1068    www      10128:                         } else {
                   10129: # Normal import
                   10130:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10131:                            if (defined($token->[2]->{'id'})) {
                   10132:                               $unikey.='_'.$token->[2]->{'id'};
                   10133:                            }
1.1067    www      10134:                         }
                   10135: 
1.339     albertel 10136: 			if ($depthcount<20) {
1.736     albertel 10137: 			    my $metadata = 
                   10138: 				&metadata($uri,'keys', $location,$unikey,
                   10139: 					  $depthcount+1);
                   10140: 			    foreach my $meta (split(',',$metadata)) {
                   10141: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10142: 				$metathesekeys{$meta}=1;
1.339     albertel 10143: 			    }
1.1068    www      10144: 			
                   10145:                         }
1.1067    www      10146: 		    } else {
                   10147: #
                   10148: # Not importing, some other kind of non-package, non-library start tag
                   10149: # 
                   10150:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10151:                         if (defined($token->[2]->{'id'})) {
                   10152:                             $unikey.='_'.$token->[2]->{'id'};
                   10153:                         }
1.339     albertel 10154: 			if (defined($token->[2]->{'name'})) { 
                   10155: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10156: 			}
                   10157: 			$metathesekeys{$unikey}=1;
1.736     albertel 10158: 			foreach my $param (@{$token->[3]}) {
                   10159: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10160: 				$token->[2]->{$param};
1.339     albertel 10161: 			}
                   10162: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10163: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10164: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10165: 		 # only ws inside the tag, and not in default, so use default
                   10166: 		 # as value
1.599     albertel 10167: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10168: 			} elsif ( $internaltext =~ /\S/ ) {
                   10169: 		  # something interesting inside the tag
                   10170: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10171: 			} else {
1.908     albertel 10172: 		  # no interesting values, don't set a default
1.339     albertel 10173: 			}
1.172     www      10174: # end of not-a-package not-a-library import
1.339     albertel 10175: 		    }
1.172     www      10176: # end of not-a-package start tag
1.339     albertel 10177: 		}
1.172     www      10178: # the next is the end of "start tag"
1.339     albertel 10179: 	    }
                   10180: 	}
1.483     albertel 10181: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10182: 	$extension = lc($extension);
                   10183: 	if ($extension eq 'htm') { $extension='html'; }
                   10184: 
1.737     albertel 10185: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10186: 	    #no specific packages #how's our extension
                   10187: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10188: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10189: 					 \%metathesekeys);
                   10190: 	}
1.883     albertel 10191: 
                   10192: 	if (!exists($metaentry{':packages'})
                   10193: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10194: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10195: 		#no specific packages well let's get default then
                   10196: 		if ($key!~/^default&/) { next; }
1.488     albertel 10197: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10198: 					     \%metathesekeys);
                   10199: 	    }
                   10200: 	}
1.338     www      10201: # are there custom rights to evaluate
1.599     albertel 10202: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10203: 
1.338     www      10204:     #
                   10205:     # Importing a rights file here
1.339     albertel 10206:     #
                   10207: 	    unless ($depthcount) {
1.599     albertel 10208: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10209: 		my $dir=$filename;
                   10210: 		$dir=~s|[^/]*$||;
                   10211: 		$location=&filelocation($dir,$location);
1.736     albertel 10212: 		my $rights_metadata =
                   10213: 		    &metadata($uri,'keys',$location,'_rights',
                   10214: 			      $depthcount+1);
                   10215: 		foreach my $rights (split(',',$rights_metadata)) {
                   10216: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10217: 		    $metathesekeys{$rights}=1;
1.339     albertel 10218: 		}
                   10219: 	    }
                   10220: 	}
1.737     albertel 10221: 	# uniqifiy package listing
                   10222: 	my %seen;
                   10223: 	my @uniq_packages =
                   10224: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10225: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10226: 
1.1070    www      10227:         if ($importedparts) {
                   10228: # We had imported parts and need to rebuild partorder
                   10229:            $metaentry{':partorder'}='';
                   10230:            $metathesekeys{'partorder'}=1;
                   10231:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10232:                if ($origfileimportpartids[$index] eq 'part') {
                   10233: # original part, part of the problem
                   10234:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10235:                } else {
                   10236: # we have imported parts at this position
                   10237:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10238:                }
                   10239:            }
                   10240:            $metaentry{':partorder'}=~s/^\,//;
                   10241:         }
                   10242: 
1.737     albertel 10243: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10244: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   10245: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 10246: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10247: # this is the end of "was not already recently cached
1.71      www      10248:     }
1.599     albertel 10249:     return $metaentry{':'.$what};
1.261     albertel 10250: }
                   10251: 
1.488     albertel 10252: sub metadata_create_package_def {
1.483     albertel 10253:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10254:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10255:     if ($subp eq 'default') { next; }
                   10256:     
1.599     albertel 10257:     if (defined($metaentry{':packages'})) {
                   10258: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10259:     } else {
1.599     albertel 10260: 	$metaentry{':packages'}=$package;
1.483     albertel 10261:     }
                   10262:     my $value=$packagetab{$key};
                   10263:     my $unikey;
                   10264:     $unikey='parameter_0_'.$name;
1.599     albertel 10265:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10266:     $$metathesekeys{$unikey}=1;
1.599     albertel 10267:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10268: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10269:     }
1.599     albertel 10270:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10271: 	$metaentry{':'.$unikey}=
                   10272: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10273:     }
                   10274: }
                   10275: 
1.261     albertel 10276: sub metadata_generate_part0 {
                   10277:     my ($metadata,$metacache,$uri) = @_;
                   10278:     my %allnames;
1.737     albertel 10279:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10280: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10281: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10282: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10283: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10284: 	    $allnames{$name}=$part;
                   10285: 	  }
                   10286: 	}
                   10287:     }
                   10288:     foreach my $name (keys(%allnames)) {
                   10289:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10290:       my $key=":parameter_0_$name";
1.261     albertel 10291:       $$metacache{"$key.part"}='0';
                   10292:       $$metacache{"$key.name"}=$name;
1.428     albertel 10293:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10294: 					   $allnames{$name}.'_'.$name.
                   10295: 					   '.type'};
1.428     albertel 10296:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10297: 			     '.display'};
1.644     www      10298:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10299:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10300:       $$metacache{"$key.display"}=$olddis;
                   10301:     }
1.71      www      10302: }
                   10303: 
1.764     albertel 10304: # ------------------------------------------------------ Devalidate title cache
                   10305: 
                   10306: sub devalidate_title_cache {
                   10307:     my ($url)=@_;
                   10308:     if (!$env{'request.course.id'}) { return; }
                   10309:     my $symb=&symbread($url);
                   10310:     if (!$symb) { return; }
                   10311:     my $key=$env{'request.course.id'}."\0".$symb;
                   10312:     &devalidate_cache_new('title',$key);
                   10313: }
                   10314: 
1.1014    droeschl 10315: # ------------------------------------------------- Get the title of a course
                   10316: 
                   10317: sub current_course_title {
                   10318:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10319: }
1.301     www      10320: # ------------------------------------------------- Get the title of a resource
                   10321: 
                   10322: sub gettitle {
                   10323:     my $urlsymb=shift;
                   10324:     my $symb=&symbread($urlsymb);
1.534     albertel 10325:     if ($symb) {
1.620     albertel 10326: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10327: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10328: 	if (defined($cached)) { 
                   10329: 	    return $result;
                   10330: 	}
1.534     albertel 10331: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10332: 	my $title='';
1.907     albertel 10333: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10334: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10335: 	} else {
                   10336: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10337: 		    &GDBM_READER(),0640)) {
                   10338: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10339: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10340: 		untie(%bighash);
                   10341: 	    }
1.534     albertel 10342: 	}
                   10343: 	$title=~s/\&colon\;/\:/gs;
                   10344: 	if ($title) {
1.1159    www      10345: # Remember both $symb and $title for dynamic metadata
                   10346:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10347:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10348: # Cache this title and then return it
1.599     albertel 10349: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10350: 	}
                   10351: 	$urlsymb=$url;
                   10352:     }
                   10353:     my $title=&metadata($urlsymb,'title');
                   10354:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10355:     return $title;
1.301     www      10356: }
1.613     albertel 10357: 
1.1172.2.13  raeburn  10358: sub getdocspath {
                   10359:     my ($symb) = @_;
                   10360:     my $path;
                   10361:     if ($symb) {
                   10362:         my ($mapurl,$id,$resurl) = &decode_symb($symb);
                   10363:         if ($resurl=~/\.(sequence|page)$/) {
                   10364:             $mapurl=$resurl;
                   10365:         } elsif ($resurl eq 'adm/navmaps') {
                   10366:             $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   10367:         }
                   10368:         my $mapresobj;
                   10369:         my $navmap = Apache::lonnavmaps::navmap->new();
                   10370:         if (ref($navmap)) {
                   10371:             $mapresobj = $navmap->getResourceByUrl($mapurl);
                   10372:         }
                   10373:         $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   10374:         my $type=$2;
                   10375:         if (ref($mapresobj)) {
                   10376:             my $pcslist = $mapresobj->map_hierarchy();
                   10377:             if ($pcslist ne '') {
                   10378:                 foreach my $pc (split(/,/,$pcslist)) {
                   10379:                     next if ($pc <= 1);
                   10380:                     my $res = $navmap->getByMapPc($pc);
                   10381:                     if (ref($res)) {
                   10382:                         my $thisurl = $res->src();
                   10383:                         $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   10384:                         my $thistitle = $res->title();
                   10385:                         $path .= '&'.
                   10386:                                  &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
                   10387:                                  &Apache::lonhtmlcommon::entity_encode($thistitle).
                   10388:                                  ':'.$res->randompick().
                   10389:                                  ':'.$res->randomout().
                   10390:                                  ':'.$res->encrypted().
                   10391:                                  ':'.$res->randomorder().
                   10392:                                  ':'.$res->is_page();
                   10393:                     }
                   10394:                 }
                   10395:             }
                   10396:             $path =~ s/^\&//;
                   10397:             my $maptitle = $mapresobj->title();
                   10398:             if ($mapurl eq 'default') {
                   10399:                 $maptitle = 'Main Course Documents';
                   10400:             }
                   10401:             $path .= ($path ne '')? '&' : ''.
                   10402:                     &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   10403:                     &Apache::lonhtmlcommon::entity_encode($maptitle).
                   10404:                     ':'.$mapresobj->randompick().
                   10405:                     ':'.$mapresobj->randomout().
                   10406:                     ':'.$mapresobj->encrypted().
                   10407:                     ':'.$mapresobj->randomorder().
                   10408:                     ':'.$mapresobj->is_page();
                   10409:         } else {
                   10410:             my $maptitle = &gettitle($mapurl);
                   10411:             my $ispage;
                   10412:             if ($mapurl =~ /\.page$/) {
                   10413:                 $ispage = 1;
                   10414:             }
                   10415:             if ($mapurl eq 'default') {
                   10416:                 $maptitle = 'Main Course Documents';
                   10417:             }
                   10418:             $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   10419:                     &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
                   10420:         }
                   10421:         unless ($mapurl eq 'default') {
                   10422:             $path = 'default&'.
                   10423:                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
                   10424:                     ':::::&'.$path;
                   10425:         }
                   10426:     }
                   10427:     return $path;
                   10428: }
                   10429: 
1.614     albertel 10430: sub get_slot {
                   10431:     my ($which,$cnum,$cdom)=@_;
                   10432:     if (!$cnum || !$cdom) {
1.790     albertel 10433: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10434: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10435: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10436:     }
1.703     albertel 10437:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10438:     my %slotinfo;
                   10439:     if (exists($remembered{$key})) {
                   10440: 	$slotinfo{$which} = $remembered{$key};
                   10441:     } else {
                   10442: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10443: 	&Apache::lonhomework::showhash(%slotinfo);
                   10444: 	my ($tmp)=keys(%slotinfo);
                   10445: 	if ($tmp=~/^error:/) { return (); }
                   10446: 	$remembered{$key} = $slotinfo{$which};
                   10447:     }
1.616     albertel 10448:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10449: 	return %{$slotinfo{$which}};
                   10450:     }
                   10451:     return $slotinfo{$which};
1.614     albertel 10452: }
1.1150    raeburn  10453: 
                   10454: sub get_reservable_slots {
                   10455:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10456:     my $now = time;
                   10457:     my $reservable_info;
                   10458:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10459:     if (exists($remembered{$key})) {
                   10460:         $reservable_info = $remembered{$key};
                   10461:     } else {
                   10462:         my %resv;
                   10463:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10464:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10465:         $reservable_info = \%resv;
                   10466:         $remembered{$key} = $reservable_info;
                   10467:     }
                   10468:     return $reservable_info;
                   10469: }
                   10470: 
                   10471: sub get_course_slots {
                   10472:     my ($cnum,$cdom) = @_;
                   10473:     my $hashid=$cnum.':'.$cdom;
                   10474:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   10475:     if (defined($cached)) {
                   10476:         if (ref($result) eq 'HASH') {
                   10477:             return %{$result};
                   10478:         }
                   10479:     } else {
                   10480:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   10481:         my ($tmp) = keys(%slots);
                   10482:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23! raeburn  10483:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  10484:             return %slots;
                   10485:         }
                   10486:     }
                   10487:     return;
                   10488: }
                   10489: 
                   10490: sub devalidate_slots_cache {
                   10491:     my ($cnum,$cdom)=@_;
                   10492:     my $hashid=$cnum.':'.$cdom;
                   10493:     &devalidate_cache_new('allslots',$hashid);
                   10494: }
                   10495: 
1.1172.2.8  raeburn  10496: sub get_coursechange {
                   10497:     my ($cdom,$cnum) = @_;
                   10498:     if ($cdom eq '' || $cnum eq '') {
                   10499:         return unless ($env{'request.course.id'});
                   10500:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10501:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10502:     }
                   10503:     my $hashid=$cdom.'_'.$cnum;
                   10504:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   10505:     if ((defined($cached)) && ($change ne '')) {
                   10506:         return $change;
                   10507:     } else {
                   10508:         my %crshash;
                   10509:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   10510:         if ($crshash{'internal.contentchange'} eq '') {
                   10511:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   10512:             if ($change eq '') {
                   10513:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   10514:                 $change = $crshash{'internal.created'};
                   10515:             }
                   10516:         } else {
                   10517:             $change = $crshash{'internal.contentchange'};
                   10518:         }
                   10519:         my $cachetime = 600;
                   10520:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   10521:     }
                   10522:     return $change;
                   10523: }
                   10524: 
                   10525: sub devalidate_coursechange_cache {
                   10526:     my ($cnum,$cdom)=@_;
                   10527:     my $hashid=$cnum.':'.$cdom;
                   10528:     &devalidate_cache_new('crschange',$hashid);
                   10529: }
                   10530: 
1.31      www      10531: # ------------------------------------------------- Update symbolic store links
                   10532: 
                   10533: sub symblist {
                   10534:     my ($mapname,%newhash)=@_;
1.438     www      10535:     $mapname=&deversion(&declutter($mapname));
1.31      www      10536:     my %hash;
1.620     albertel 10537:     if (($env{'request.course.fn'}) && (%newhash)) {
                   10538:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10539:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  10540: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 10541: 		next if ($url eq 'last_known'
                   10542: 			 && $env{'form.no_update_last_known'});
                   10543: 		$hash{declutter($url)}=&encode_symb($mapname,
                   10544: 						    $newhash{$url}->[1],
                   10545: 						    $newhash{$url}->[0]);
1.191     harris41 10546:             }
1.31      www      10547:             if (untie(%hash)) {
                   10548: 		return 'ok';
                   10549:             }
                   10550:         }
                   10551:     }
                   10552:     return 'error';
1.212     www      10553: }
                   10554: 
                   10555: # --------------------------------------------------------------- Verify a symb
                   10556: 
                   10557: sub symbverify {
1.1172.2.11  raeburn  10558:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      10559:     my $thisfn=$thisurl;
1.439     www      10560:     $thisfn=&declutter($thisfn);
1.215     www      10561: # direct jump to resource in page or to a sequence - will construct own symbs
                   10562:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   10563: # check URL part
1.409     www      10564:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      10565: 
1.431     www      10566:     unless ($url eq $thisfn) { return 0; }
1.213     www      10567: 
1.216     www      10568:     $symb=&symbclean($symb);
1.510     www      10569:     $thisurl=&deversion($thisurl);
1.439     www      10570:     $thisfn=&deversion($thisfn);
1.213     www      10571: 
                   10572:     my %bighash;
                   10573:     my $okay=0;
1.431     www      10574: 
1.620     albertel 10575:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10576:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  10577:         my $noclutter;
1.1032    raeburn  10578:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   10579:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  10580:             if ($map =~ m{^uploaded/.+\.page$}) {
                   10581:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   10582:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   10583:                 $noclutter = 1;
                   10584:             }
                   10585:         }
                   10586:         my $ids;
                   10587:         if ($noclutter) {
                   10588:             $ids=$bighash{'ids_'.$thisurl};
                   10589:         } else {
                   10590:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  10591:         }
1.1102    raeburn  10592:         unless ($ids) {
1.1172.2.13  raeburn  10593:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  10594:             $ids=$bighash{$idkey};
1.216     www      10595:         }
                   10596:         if ($ids) {
                   10597: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  10598:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10599:                 $symb =~ s/\?.+$//;
                   10600:             }
1.800     albertel 10601: 	    foreach my $id (split(/\,/,$ids)) {
                   10602: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      10603:                if (
                   10604:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  10605:    eq $symb) {
1.1172.2.11  raeburn  10606:                    if (ref($encstate)) {
                   10607:                        $$encstate = $bighash{'encrypted_'.$id};
                   10608:                    }
1.1172.2.13  raeburn  10609:                    if (($env{'request.role.adv'}) ||
                   10610:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  10611:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  10612:                        $okay=1;
                   10613:                        last;
                   10614:                    }
                   10615:                }
                   10616:            }
1.216     www      10617:         }
1.213     www      10618: 	untie(%bighash);
                   10619:     }
                   10620:     return $okay;
1.31      www      10621: }
                   10622: 
1.210     www      10623: # --------------------------------------------------------------- Clean-up symb
                   10624: 
                   10625: sub symbclean {
                   10626:     my $symb=shift;
1.568     albertel 10627:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10628: # remove version from map
                   10629:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10630: 
1.210     www      10631: # remove version from URL
                   10632:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10633: 
1.507     www      10634: # remove wrapper
                   10635: 
1.510     www      10636:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10637:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10638:     return $symb;
1.409     www      10639: }
                   10640: 
                   10641: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10642: 
                   10643: sub encode_symb {
                   10644:     my ($map,$resid,$url)=@_;
                   10645:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10646: }
1.409     www      10647: 
                   10648: sub decode_symb {
1.568     albertel 10649:     my $symb=shift;
                   10650:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10651:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10652:     return (&fixversion($map),$resid,&fixversion($url));
                   10653: }
                   10654: 
                   10655: sub fixversion {
                   10656:     my $fn=shift;
1.609     banghart 10657:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10658:     my %bighash;
                   10659:     my $uri=&clutter($fn);
1.620     albertel 10660:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10661: # is this cached?
1.599     albertel 10662:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10663:     if (defined($cached)) { return $result; }
                   10664: # unfortunately not cached, or expired
1.620     albertel 10665:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10666: 	    &GDBM_READER(),0640)) {
                   10667:  	if ($bighash{'version_'.$uri}) {
                   10668:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10669:  	    unless (($version eq 'mostrecent') || 
                   10670: 		    ($version==&getversion($uri))) {
1.440     www      10671:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10672:  	    }
                   10673:  	}
                   10674:  	untie %bighash;
1.413     www      10675:     }
1.599     albertel 10676:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10677: }
                   10678: 
                   10679: sub deversion {
                   10680:     my $url=shift;
                   10681:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10682:     return $url;
1.210     www      10683: }
                   10684: 
1.31      www      10685: # ------------------------------------------------------ Return symb list entry
                   10686: 
                   10687: sub symbread {
1.249     www      10688:     my ($thisfn,$donotrecurse)=@_;
1.1172.2.13  raeburn  10689:     my $cache_str;
                   10690:     if ($thisfn ne '') {
                   10691:         $cache_str='request.symbread.cached.'.$thisfn;
                   10692:         if ($env{$cache_str} ne '') {
1.1172.2.8  raeburn  10693:             return $env{$cache_str};
                   10694:         }
1.1172.2.13  raeburn  10695:    } else {
1.242     www      10696: # no filename provided? try from environment
1.620     albertel 10697:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  10698:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   10699:         }
                   10700:         $thisfn=$env{'request.filename'};
1.44      www      10701:     }
1.569     albertel 10702:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10703: # is that filename actually a symb? Verify, clean, and return
                   10704:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10705: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10706: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10707: 	}
1.242     www      10708:     }
1.44      www      10709:     $thisfn=declutter($thisfn);
1.31      www      10710:     my %hash;
1.37      www      10711:     my %bighash;
                   10712:     my $syval='';
1.620     albertel 10713:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10714:         my $targetfn = $thisfn;
1.609     banghart 10715:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10716:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10717:         }
1.687     albertel 10718: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10719: 	    $targetfn=$1;
                   10720: 	}
1.620     albertel 10721:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10722:                       &GDBM_READER(),0640)) {
1.481     raeburn  10723: 	    $syval=$hash{$targetfn};
1.37      www      10724:             untie(%hash);
                   10725:         }
                   10726: # ---------------------------------------------------------- There was an entry
                   10727:         if ($syval) {
1.601     albertel 10728: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10729: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10730: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10731: 		    #return $env{$cache_str}='';
1.601     albertel 10732: 		#}    
                   10733: 		#$syval.=$1;
                   10734: 	    #}
1.37      www      10735:         } else {
                   10736: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10737:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10738:                             &GDBM_READER(),0640)) {
1.37      www      10739: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10740:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10741:               unless ($ids) { 
                   10742:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10743:               }
                   10744:               unless ($ids) {
                   10745: # alias?
                   10746: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10747:               }
1.37      www      10748:               if ($ids) {
                   10749: # ------------------------------------------------------------------- Has ID(s)
                   10750:                  my @possibilities=split(/\,/,$ids);
1.39      www      10751:                  if ($#possibilities==0) {
                   10752: # ----------------------------------------------- There is only one possibility
1.37      www      10753: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10754: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10755: 						    $resid,$thisfn);
1.249     www      10756:                  } elsif (!$donotrecurse) {
1.39      www      10757: # ------------------------------------------ There is more than one possibility
                   10758:                      my $realpossible=0;
1.800     albertel 10759:                      foreach my $id (@possibilities) {
                   10760: 			 my $file=$bighash{'src_'.$id};
1.39      www      10761:                          if (&allowed('bre',$file)) {
1.800     albertel 10762:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10763:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10764: 				$realpossible++;
1.626     albertel 10765:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10766: 						    $resid,$thisfn);
1.39      www      10767:                             }
                   10768: 			 }
1.191     harris41 10769:                      }
1.39      www      10770: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10771:                  } else {
                   10772:                      $syval='';
1.37      www      10773:                  }
                   10774: 	      }
                   10775:               untie(%bighash)
1.481     raeburn  10776:            }
1.31      www      10777:         }
1.62      www      10778:         if ($syval) {
1.620     albertel 10779: 	    return $env{$cache_str}=$syval;
1.62      www      10780:         }
1.31      www      10781:     }
1.949     raeburn  10782:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10783:     return $env{$cache_str}='';
1.31      www      10784: }
                   10785: 
                   10786: # ---------------------------------------------------------- Return random seed
                   10787: 
1.32      www      10788: sub numval {
                   10789:     my $txt=shift;
                   10790:     $txt=~tr/A-J/0-9/;
                   10791:     $txt=~tr/a-j/0-9/;
                   10792:     $txt=~tr/K-T/0-9/;
                   10793:     $txt=~tr/k-t/0-9/;
                   10794:     $txt=~tr/U-Z/0-5/;
                   10795:     $txt=~tr/u-z/0-5/;
                   10796:     $txt=~s/\D//g;
1.564     albertel 10797:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10798:     return int($txt);
1.368     albertel 10799: }
                   10800: 
1.484     albertel 10801: sub numval2 {
                   10802:     my $txt=shift;
                   10803:     $txt=~tr/A-J/0-9/;
                   10804:     $txt=~tr/a-j/0-9/;
                   10805:     $txt=~tr/K-T/0-9/;
                   10806:     $txt=~tr/k-t/0-9/;
                   10807:     $txt=~tr/U-Z/0-5/;
                   10808:     $txt=~tr/u-z/0-5/;
                   10809:     $txt=~s/\D//g;
                   10810:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10811:     my $total;
                   10812:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10813:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10814:     return int($total);
                   10815: }
                   10816: 
1.575     albertel 10817: sub numval3 {
                   10818:     use integer;
                   10819:     my $txt=shift;
                   10820:     $txt=~tr/A-J/0-9/;
                   10821:     $txt=~tr/a-j/0-9/;
                   10822:     $txt=~tr/K-T/0-9/;
                   10823:     $txt=~tr/k-t/0-9/;
                   10824:     $txt=~tr/U-Z/0-5/;
                   10825:     $txt=~tr/u-z/0-5/;
                   10826:     $txt=~s/\D//g;
                   10827:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10828:     my $total;
                   10829:     foreach my $val (@txts) { $total+=$val; }
                   10830:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10831:     return $total;
                   10832: }
                   10833: 
1.675     albertel 10834: sub digest {
                   10835:     my ($data)=@_;
                   10836:     my $digest=&Digest::MD5::md5($data);
                   10837:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10838:     my ($e,$f);
                   10839:     {
                   10840:         use integer;
                   10841:         $e=($a+$b);
                   10842:         $f=($c+$d);
                   10843:         if ($_64bit) {
                   10844:             $e=(($e<<32)>>32);
                   10845:             $f=(($f<<32)>>32);
                   10846:         }
                   10847:     }
                   10848:     if (wantarray) {
                   10849: 	return ($e,$f);
                   10850:     } else {
                   10851: 	my $g;
                   10852: 	{
                   10853: 	    use integer;
                   10854: 	    $g=($e+$f);
                   10855: 	    if ($_64bit) {
                   10856: 		$g=(($g<<32)>>32);
                   10857: 	    }
                   10858: 	}
                   10859: 	return $g;
                   10860:     }
                   10861: }
                   10862: 
1.368     albertel 10863: sub latest_rnd_algorithm_id {
1.675     albertel 10864:     return '64bit5';
1.366     albertel 10865: }
1.32      www      10866: 
1.503     albertel 10867: sub get_rand_alg {
                   10868:     my ($courseid)=@_;
1.790     albertel 10869:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10870:     if ($courseid) {
1.620     albertel 10871: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10872:     }
                   10873:     return &latest_rnd_algorithm_id();
                   10874: }
                   10875: 
1.562     albertel 10876: sub validCODE {
                   10877:     my ($CODE)=@_;
                   10878:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10879:     return 0;
                   10880: }
                   10881: 
1.491     albertel 10882: sub getCODE {
1.620     albertel 10883:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10884:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10885: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10886: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10887: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10888:     }
                   10889:     return undef;
                   10890: }
1.1133    foxr     10891: #
                   10892: #  Determines the random seed for a specific context:
                   10893: #
                   10894: # parameters:
                   10895: #   symb      - in course context the symb for the seed.
                   10896: #   course_id - The course id of the form domain_coursenum.
                   10897: #   domain    - Domain for the user.
                   10898: #   course    - Course for the user.
                   10899: #   cenv      - environment of the course.
                   10900: #
                   10901: # NOTE:
                   10902: #   All parameters are picked out of the environment if missing
                   10903: #   or not defined.
                   10904: #   If a symb cannot be determined the current time is used instead.
                   10905: #
                   10906: #  For a given well defined symb, courside, domain, username,
                   10907: #  and course environment, the seed is reproducible.
                   10908: #
1.31      www      10909: sub rndseed {
1.1133    foxr     10910:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10911:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10912:     if (!defined($symb)) {
1.366     albertel 10913: 	unless ($symb=$wsymb) { return time; }
                   10914:     }
1.1146    foxr     10915:     if (!defined $courseid) { 
                   10916: 	$courseid=$wcourseid; 
                   10917:     }
                   10918:     if (!defined $domain) { $domain=$wdomain; }
                   10919:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10920: 
                   10921:     my $which;
                   10922:     if (defined($cenv->{'rndseed'})) {
                   10923: 	$which = $cenv->{'rndseed'};
                   10924:     } else {
                   10925: 	$which =&get_rand_alg($courseid);
                   10926:     }
1.491     albertel 10927:     if (defined(&getCODE())) {
1.675     albertel 10928: 	if ($which eq '64bit5') {
                   10929: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10930: 	} elsif ($which eq '64bit4') {
1.575     albertel 10931: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10932: 	} else {
                   10933: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10934: 	}
1.675     albertel 10935:     } elsif ($which eq '64bit5') {
                   10936: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10937:     } elsif ($which eq '64bit4') {
                   10938: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10939:     } elsif ($which eq '64bit3') {
                   10940: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10941:     } elsif ($which eq '64bit2') {
                   10942: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10943:     } elsif ($which eq '64bit') {
                   10944: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10945:     }
                   10946:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10947: }
                   10948: 
                   10949: sub rndseed_32bit {
                   10950:     my ($symb,$courseid,$domain,$username)=@_;
                   10951:     {
                   10952: 	use integer;
                   10953: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10954: 	my $symbseed=numval($symb) << 22;
                   10955: 	my $namechck=unpack("%32C*",$username) << 17;
                   10956: 	my $nameseed=numval($username) << 12;
                   10957: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10958: 	my $courseseed=unpack("%32C*",$courseid);
                   10959: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10960: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10961: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10962: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10963: 	return $num;
                   10964:     }
                   10965: }
                   10966: 
                   10967: sub rndseed_64bit {
                   10968:     my ($symb,$courseid,$domain,$username)=@_;
                   10969:     {
                   10970: 	use integer;
                   10971: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10972: 	my $symbseed=numval($symb) << 10;
                   10973: 	my $namechck=unpack("%32S*",$username);
                   10974: 	
                   10975: 	my $nameseed=numval($username) << 21;
                   10976: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10977: 	my $courseseed=unpack("%32S*",$courseid);
                   10978: 	
                   10979: 	my $num1=$symbchck+$symbseed+$namechck;
                   10980: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10981: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10982: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10983: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10984: 	return "$num1,$num2";
1.155     albertel 10985:     }
1.366     albertel 10986: }
                   10987: 
1.443     albertel 10988: sub rndseed_64bit2 {
                   10989:     my ($symb,$courseid,$domain,$username)=@_;
                   10990:     {
                   10991: 	use integer;
                   10992: 	# strings need to be an even # of cahracters long, it it is odd the
                   10993:         # last characters gets thrown away
                   10994: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10995: 	my $symbseed=numval($symb) << 10;
                   10996: 	my $namechck=unpack("%32S*",$username.' ');
                   10997: 	
                   10998: 	my $nameseed=numval($username) << 21;
1.501     albertel 10999: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11000: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11001: 	
                   11002: 	my $num1=$symbchck+$symbseed+$namechck;
                   11003: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11004: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11005: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11006: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11007: 	return "$num1,$num2";
                   11008:     }
                   11009: }
                   11010: 
                   11011: sub rndseed_64bit3 {
                   11012:     my ($symb,$courseid,$domain,$username)=@_;
                   11013:     {
                   11014: 	use integer;
                   11015: 	# strings need to be an even # of cahracters long, it it is odd the
                   11016:         # last characters gets thrown away
                   11017: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11018: 	my $symbseed=numval2($symb) << 10;
                   11019: 	my $namechck=unpack("%32S*",$username.' ');
                   11020: 	
                   11021: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11022: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11023: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11024: 	
                   11025: 	my $num1=$symbchck+$symbseed+$namechck;
                   11026: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11027: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11028: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11029: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11030: 	
1.503     albertel 11031: 	return "$num1:$num2";
1.443     albertel 11032:     }
                   11033: }
                   11034: 
1.575     albertel 11035: sub rndseed_64bit4 {
                   11036:     my ($symb,$courseid,$domain,$username)=@_;
                   11037:     {
                   11038: 	use integer;
                   11039: 	# strings need to be an even # of cahracters long, it it is odd the
                   11040:         # last characters gets thrown away
                   11041: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11042: 	my $symbseed=numval3($symb) << 10;
                   11043: 	my $namechck=unpack("%32S*",$username.' ');
                   11044: 	
                   11045: 	my $nameseed=numval3($username) << 21;
                   11046: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11047: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11048: 	
                   11049: 	my $num1=$symbchck+$symbseed+$namechck;
                   11050: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11051: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11052: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11053: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11054: 	
1.575     albertel 11055: 	return "$num1:$num2";
                   11056:     }
                   11057: }
                   11058: 
1.675     albertel 11059: sub rndseed_64bit5 {
                   11060:     my ($symb,$courseid,$domain,$username)=@_;
                   11061:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11062:     return "$num1:$num2";
                   11063: }
                   11064: 
1.366     albertel 11065: sub rndseed_CODE_64bit {
                   11066:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11067:     {
1.366     albertel 11068: 	use integer;
1.443     albertel 11069: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11070: 	my $symbseed=numval2($symb);
1.491     albertel 11071: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11072: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11073: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11074: 	my $num1=$symbseed+$CODEchck;
                   11075: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11076: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11077: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11078: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11079: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11080: 	return "$num1:$num2";
1.366     albertel 11081:     }
                   11082: }
                   11083: 
1.575     albertel 11084: sub rndseed_CODE_64bit4 {
                   11085:     my ($symb,$courseid,$domain,$username)=@_;
                   11086:     {
                   11087: 	use integer;
                   11088: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11089: 	my $symbseed=numval3($symb);
                   11090: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11091: 	my $CODEseed=numval3(&getCODE());
                   11092: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11093: 	my $num1=$symbseed+$CODEchck;
                   11094: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11095: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11096: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11097: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11098: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11099: 	return "$num1:$num2";
                   11100:     }
                   11101: }
                   11102: 
1.675     albertel 11103: sub rndseed_CODE_64bit5 {
                   11104:     my ($symb,$courseid,$domain,$username)=@_;
                   11105:     my $code = &getCODE();
                   11106:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11107:     return "$num1:$num2";
                   11108: }
                   11109: 
1.366     albertel 11110: sub setup_random_from_rndseed {
                   11111:     my ($rndseed)=@_;
1.503     albertel 11112:     if ($rndseed =~/([,:])/) {
                   11113: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 11114: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   11115:     } else {
                   11116: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11117:     }
1.36      albertel 11118: }
                   11119: 
1.474     albertel 11120: sub latest_receipt_algorithm_id {
1.835     albertel 11121:     return 'receipt3';
1.474     albertel 11122: }
                   11123: 
1.480     www      11124: sub recunique {
                   11125:     my $fucourseid=shift;
                   11126:     my $unique;
1.835     albertel 11127:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11128: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11129: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11130:     } else {
                   11131: 	$unique=$perlvar{'lonReceipt'};
                   11132:     }
                   11133:     return unpack("%32C*",$unique);
                   11134: }
                   11135: 
                   11136: sub recprefix {
                   11137:     my $fucourseid=shift;
                   11138:     my $prefix;
1.835     albertel 11139:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11140: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11141: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11142:     } else {
                   11143: 	$prefix=$perlvar{'lonHostID'};
                   11144:     }
                   11145:     return unpack("%32C*",$prefix);
                   11146: }
                   11147: 
1.76      www      11148: sub ireceipt {
1.474     albertel 11149:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11150: 
                   11151:     my $return =&recprefix($fucourseid).'-';
                   11152: 
                   11153:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11154: 	$env{'request.state'} eq 'construct') {
                   11155: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11156: 	return $return;
                   11157:     }
                   11158: 
1.76      www      11159:     my $cuname=unpack("%32C*",$funame);
                   11160:     my $cudom=unpack("%32C*",$fudom);
                   11161:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11162:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11163:     my $cunique=&recunique($fucourseid);
1.474     albertel 11164:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11165:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11166: 
1.790     albertel 11167: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11168: 			       
                   11169: 	$return.= ($cunique%$cuname+
                   11170: 		   $cunique%$cudom+
                   11171: 		   $cusymb%$cuname+
                   11172: 		   $cusymb%$cudom+
                   11173: 		   $cucourseid%$cuname+
                   11174: 		   $cucourseid%$cudom+
                   11175: 		   $cpart%$cuname+
                   11176: 		   $cpart%$cudom);
                   11177:     } else {
                   11178: 	$return.= ($cunique%$cuname+
                   11179: 		   $cunique%$cudom+
                   11180: 		   $cusymb%$cuname+
                   11181: 		   $cusymb%$cudom+
                   11182: 		   $cucourseid%$cuname+
                   11183: 		   $cucourseid%$cudom);
                   11184:     }
                   11185:     return $return;
1.76      www      11186: }
                   11187: 
                   11188: sub receipt {
1.474     albertel 11189:     my ($part)=@_;
1.790     albertel 11190:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11191:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11192: }
1.260     ng       11193: 
1.790     albertel 11194: sub whichuser {
                   11195:     my ($passedsymb)=@_;
                   11196:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11197:     if (defined($env{'form.grade_symb'})) {
                   11198: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11199: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11200: 	if (!$allowed &&
                   11201: 	    exists($env{'request.course.sec'}) &&
                   11202: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11203: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11204: 			      '/'.$env{'request.course.sec'});
                   11205: 	}
                   11206: 	if ($allowed) {
                   11207: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11208: 	    $courseid=$tmp_courseid;
                   11209: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11210: 	    ($name)=&get_env_multiple('form.grade_username');
                   11211: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11212: 	}
                   11213:     }
                   11214:     if (!$passedsymb) {
                   11215: 	$symb=&symbread();
                   11216:     } else {
                   11217: 	$symb=$passedsymb;
                   11218:     }
                   11219:     $courseid=$env{'request.course.id'};
                   11220:     $domain=$env{'user.domain'};
                   11221:     $name=$env{'user.name'};
                   11222:     if ($name eq 'public' && $domain eq 'public') {
                   11223: 	if (!defined($env{'form.username'})) {
                   11224: 	    $env{'form.username'}.=time.rand(10000000);
                   11225: 	}
                   11226: 	$name.=$env{'form.username'};
                   11227:     }
                   11228:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11229: 
                   11230: }
                   11231: 
1.36      albertel 11232: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11233: # returns either the contents of the file or 
                   11234: # -1 if the file doesn't exist
1.481     raeburn  11235: #
                   11236: # if the target is a file that was uploaded via DOCS, 
                   11237: # a check will be made to see if a current copy exists on the local server,
                   11238: # if it does this will be served, otherwise a copy will be retrieved from
                   11239: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11240: # the local server.   
1.472     albertel 11241: 
1.36      albertel 11242: sub getfile {
1.538     albertel 11243:     my ($file) = @_;
1.609     banghart 11244:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11245:     &repcopy($file);
                   11246:     return &readfile($file);
                   11247: }
                   11248: 
                   11249: sub repcopy_userfile {
                   11250:     my ($file)=@_;
1.1142    raeburn  11251:     my $londocroot = $perlvar{'lonDocRoot'};
                   11252:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11253:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11254:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11255: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11256:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11257:     if (-e "$file") {
1.828     www      11258: # we already have a local copy, check it out
1.538     albertel 11259: 	my @fileinfo = stat($file);
1.828     www      11260: 	my $rtncode;
                   11261: 	my $info;
1.538     albertel 11262: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11263: 	if ($lwpresp ne 'ok') {
1.828     www      11264: # there is no such file anymore, even though we had a local copy
1.482     albertel 11265: 	    if ($rtncode eq '404') {
1.538     albertel 11266: 		unlink($file);
1.482     albertel 11267: 	    }
                   11268: 	    return -1;
                   11269: 	}
                   11270: 	if ($info < $fileinfo[9]) {
1.828     www      11271: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11272: 	    return 'ok';
1.828     www      11273: 	} else {
                   11274: # the file is outdated, get rid of it
                   11275: 	    unlink($file);
1.482     albertel 11276: 	}
1.828     www      11277:     }
                   11278: # one way or the other, at this point, we don't have the file
                   11279: # construct the correct path for the file
                   11280:     my @parts = ($cdom,$cnum); 
                   11281:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11282: 	push @parts, split(/\//,$1);
                   11283:     }
                   11284:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11285:     foreach my $part (@parts) {
                   11286: 	$path .= '/'.$part;
                   11287: 	if (!-e $path) {
                   11288: 	    mkdir($path,0770);
1.482     albertel 11289: 	}
                   11290:     }
1.828     www      11291: # now the path exists for sure
                   11292: # get a user agent
                   11293:     my $ua=new LWP::UserAgent;
                   11294:     my $transferfile=$file.'.in.transfer';
                   11295: # FIXME: this should flock
                   11296:     if (-e $transferfile) { return 'ok'; }
                   11297:     my $request;
                   11298:     $uri=~s/^\///;
1.980     raeburn  11299:     my $homeserver = &homeserver($cnum,$cdom);
                   11300:     my $protocol = $protocol{$homeserver};
                   11301:     $protocol = 'http' if ($protocol ne 'https');
                   11302:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11303:     my $response=$ua->request($request,$transferfile);
                   11304: # did it work?
                   11305:     if ($response->is_error()) {
                   11306: 	unlink($transferfile);
                   11307: 	&logthis("Userfile repcopy failed for $uri");
                   11308: 	return -1;
                   11309:     }
                   11310: # worked, rename the transfer file
                   11311:     rename($transferfile,$file);
1.607     raeburn  11312:     return 'ok';
1.481     raeburn  11313: }
                   11314: 
1.517     albertel 11315: sub tokenwrapper {
                   11316:     my $uri=shift;
1.980     raeburn  11317:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11318:     $uri=~s|^/||;
1.620     albertel 11319:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11320:     my $token=$1;
1.552     albertel 11321:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11322:     if ($udom && $uname && $file) {
                   11323: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11324:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11325:         my $homeserver = &homeserver($uname,$udom);
                   11326:         my $protocol = $protocol{$homeserver};
                   11327:         $protocol = 'http' if ($protocol ne 'https');
                   11328:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11329:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11330:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11331:     } else {
                   11332:         return '/adm/notfound.html';
                   11333:     }
                   11334: }
                   11335: 
1.828     www      11336: # call with reqtype HEAD: get last modification time
                   11337: # call with reqtype GET: get the file contents
                   11338: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11339: #
1.481     raeburn  11340: sub getuploaded {
                   11341:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11342:     $uri=~s/^\///;
1.980     raeburn  11343:     my $homeserver = &homeserver($cnum,$cdom);
                   11344:     my $protocol = $protocol{$homeserver};
                   11345:     $protocol = 'http' if ($protocol ne 'https');
                   11346:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11347:     my $ua=new LWP::UserAgent;
                   11348:     my $request=new HTTP::Request($reqtype,$uri);
                   11349:     my $response=$ua->request($request);
                   11350:     $$rtncode = $response->code;
1.482     albertel 11351:     if (! $response->is_success()) {
                   11352: 	return 'failed';
                   11353:     }      
                   11354:     if ($reqtype eq 'HEAD') {
1.486     www      11355: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11356:     } elsif ($reqtype eq 'GET') {
                   11357: 	$$info = $response->content;
1.472     albertel 11358:     }
1.482     albertel 11359:     return 'ok';
1.36      albertel 11360: }
                   11361: 
1.481     raeburn  11362: sub readfile {
                   11363:     my $file = shift;
                   11364:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11365:     my $fh;
                   11366:     open($fh,"<$file");
                   11367:     my $a='';
1.800     albertel 11368:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11369:     return $a;
                   11370: }
                   11371: 
1.36      albertel 11372: sub filelocation {
1.590     banghart 11373:     my ($dir,$file) = @_;
                   11374:     my $location;
                   11375:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11376: 
                   11377:     if ($file =~ m-^/adm/-) {
                   11378: 	$file=~s-^/adm/wrapper/-/-;
                   11379: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11380:     }
1.882     albertel 11381: 
1.1139    www      11382:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11383:         $location = $file;
1.609     banghart 11384:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11385:         my ($udom,$uname,$filename)=
1.811     albertel 11386:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11387:         my $home=&homeserver($uname,$udom);
                   11388:         my $is_me=0;
                   11389:         my @ids=&current_machine_ids();
                   11390:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11391:         if ($is_me) {
1.1117    foxr     11392:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11393:         } else {
                   11394:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11395:   	      $udom.'/'.$uname.'/'.$filename;
                   11396:         }
1.882     albertel 11397:     } elsif ($file =~ m-^/adm/-) {
                   11398: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11399:     } else {
                   11400:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11401:         $file=~s:^/(res|priv)/:/:;
                   11402:         my $space=$1;
1.590     banghart 11403:         if ( !( $file =~ m:^/:) ) {
                   11404:             $location = $dir. '/'.$file;
                   11405:         } else {
1.1142    raeburn  11406:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11407:         }
1.59      albertel 11408:     }
1.590     banghart 11409:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11410:     while ($location=~m{/\.\./}) {
                   11411: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11412: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11413: 	} else {
                   11414: 	    $location=~ s{/\.\./}{/}g;
                   11415: 	}
                   11416:     } #remove dir/..
1.590     banghart 11417:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11418:     return $location;
1.46      www      11419: }
1.36      albertel 11420: 
1.46      www      11421: sub hreflocation {
                   11422:     my ($dir,$file)=@_;
1.980     raeburn  11423:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11424: 	$file=filelocation($dir,$file);
1.700     albertel 11425:     } elsif ($file=~m-^/adm/-) {
                   11426: 	$file=~s-^/adm/wrapper/-/-;
                   11427: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11428:     }
                   11429:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11430: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11431:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11432: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11433: 	        {/uploaded/$1/$2/}x;
1.46      www      11434:     }
1.913     albertel 11435:     if ($file=~ m{^/userfiles/}) {
                   11436: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11437:     }
1.462     albertel 11438:     return $file;
1.465     albertel 11439: }
                   11440: 
1.1139    www      11441: 
                   11442: 
                   11443: 
                   11444: 
1.465     albertel 11445: sub current_machine_domains {
1.853     albertel 11446:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   11447: }
                   11448: 
                   11449: sub machine_domains {
                   11450:     my ($hostname) = @_;
1.465     albertel 11451:     my @domains;
1.838     albertel 11452:     my %hostname = &all_hostnames();
1.465     albertel 11453:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  11454: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 11455: 	if ($hostname eq $name) {
1.844     albertel 11456: 	    push(@domains,&host_domain($id));
1.465     albertel 11457: 	}
                   11458:     }
                   11459:     return @domains;
                   11460: }
                   11461: 
                   11462: sub current_machine_ids {
1.853     albertel 11463:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   11464: }
                   11465: 
                   11466: sub machine_ids {
                   11467:     my ($hostname) = @_;
                   11468:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 11469:     my @ids;
1.888     albertel 11470:     my %name_to_host = &all_names();
1.889     albertel 11471:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   11472: 	return @{ $name_to_host{$hostname} };
                   11473:     }
                   11474:     return;
1.31      www      11475: }
                   11476: 
1.824     raeburn  11477: sub additional_machine_domains {
                   11478:     my @domains;
                   11479:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   11480:     while( my $line = <$fh>) {
                   11481:         $line =~ s/\s//g;
                   11482:         push(@domains,$line);
                   11483:     }
                   11484:     return @domains;
                   11485: }
                   11486: 
                   11487: sub default_login_domain {
                   11488:     my $domain = $perlvar{'lonDefDomain'};
                   11489:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   11490:     foreach my $posdom (&current_machine_domains(),
                   11491:                         &additional_machine_domains()) {
                   11492:         if (lc($posdom) eq lc($testdomain)) {
                   11493:             $domain=$posdom;
                   11494:             last;
                   11495:         }
                   11496:     }
                   11497:     return $domain;
                   11498: }
                   11499: 
1.31      www      11500: # ------------------------------------------------------------- Declutters URLs
                   11501: 
                   11502: sub declutter {
                   11503:     my $thisfn=shift;
1.569     albertel 11504:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 11505:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      11506:     $thisfn=~s/^\///;
1.697     albertel 11507:     $thisfn=~s|^adm/wrapper/||;
                   11508:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      11509:     $thisfn=~s/^res\///;
1.1172    bisitz   11510:     $thisfn=~s/^priv\///;
1.1032    raeburn  11511:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   11512:         $thisfn=~s/\?.+$//;
                   11513:     }
1.268     www      11514:     return $thisfn;
                   11515: }
                   11516: 
                   11517: # ------------------------------------------------------------- Clutter up URLs
                   11518: 
                   11519: sub clutter {
                   11520:     my $thisfn='/'.&declutter(shift);
1.887     albertel 11521:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 11522: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      11523:        $thisfn='/res'.$thisfn; 
                   11524:     }
1.1031    raeburn  11525:     if ($thisfn !~m|^/adm|) {
                   11526: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 11527: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 11528: 	} else {
                   11529: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   11530: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 11531: 	    if ($embstyle eq 'ssi'
                   11532: 		|| ($embstyle eq 'hdn')
                   11533: 		|| ($embstyle eq 'rat')
                   11534: 		|| ($embstyle eq 'prv')
                   11535: 		|| ($embstyle eq 'ign')) {
                   11536: 		#do nothing with these
                   11537: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 11538: 		|| ($embstyle eq 'emb')
                   11539: 		|| ($embstyle eq 'wrp')) {
                   11540: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 11541: 	    } elsif ($embstyle eq 'unk'
                   11542: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 11543: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 11544: 	    } else {
1.718     www      11545: #		&logthis("Got a blank emb style");
1.695     albertel 11546: 	    }
1.694     albertel 11547: 	}
                   11548:     }
1.31      www      11549:     return $thisfn;
1.12      www      11550: }
                   11551: 
1.787     albertel 11552: sub clutter_with_no_wrapper {
                   11553:     my $uri = &clutter(shift);
                   11554:     if ($uri =~ m-^/adm/-) {
                   11555: 	$uri =~ s-^/adm/wrapper/-/-;
                   11556: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   11557:     }
                   11558:     return $uri;
                   11559: }
                   11560: 
1.557     albertel 11561: sub freeze_escape {
                   11562:     my ($value)=@_;
                   11563:     if (ref($value)) {
                   11564: 	$value=&nfreeze($value);
                   11565: 	return '__FROZEN__'.&escape($value);
                   11566:     }
                   11567:     return &escape($value);
                   11568: }
                   11569: 
1.11      www      11570: 
1.557     albertel 11571: sub thaw_unescape {
                   11572:     my ($value)=@_;
                   11573:     if ($value =~ /^__FROZEN__/) {
                   11574: 	substr($value,0,10,undef);
                   11575: 	$value=&unescape($value);
                   11576: 	return &thaw($value);
                   11577:     }
                   11578:     return &unescape($value);
                   11579: }
                   11580: 
1.436     albertel 11581: sub correct_line_ends {
                   11582:     my ($result)=@_;
                   11583:     $$result =~s/\r\n/\n/mg;
                   11584:     $$result =~s/\r/\n/mg;
1.415     albertel 11585: }
1.1       albertel 11586: # ================================================================ Main Program
                   11587: 
1.184     www      11588: sub goodbye {
1.204     albertel 11589:    &logthis("Starting Shut down");
1.443     albertel 11590: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 11591:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 11592: #converted
1.599     albertel 11593: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11594:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11595: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11596: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11597: #1.1 only
1.870     albertel 11598: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11599: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11600: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11601: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11602:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11603:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11604:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11605:    &flushcourselogs();
                   11606:    &logthis("Shutting down");
                   11607: }
                   11608: 
1.852     albertel 11609: sub get_dns {
1.1172.2.17  raeburn  11610:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 11611:     if (!$ignore_cache) {
                   11612: 	my ($content,$cached)=
                   11613: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11614: 	if ($cached) {
1.1172.2.17  raeburn  11615: 	    &$func($content,$hashref);
1.869     albertel 11616: 	    return;
                   11617: 	}
                   11618:     }
                   11619: 
                   11620:     my %alldns;
1.852     albertel 11621:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11622:     foreach my $dns (<$config>) {
                   11623: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11624:         my $line = $1;
                   11625:         my ($host,$protocol) = split(/:/,$line);
                   11626:         if ($protocol ne 'https') {
                   11627:             $protocol = 'http';
                   11628:         }
                   11629: 	$alldns{$host} = $protocol;
1.869     albertel 11630:     }
                   11631:     while (%alldns) {
                   11632: 	my ($dns) = keys(%alldns);
1.852     albertel 11633: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11634:         $ua->timeout(30);
1.979     raeburn  11635: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11636: 	my $response=$ua->request($request);
1.979     raeburn  11637:         delete($alldns{$dns});
1.852     albertel 11638: 	next if ($response->is_error());
                   11639: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  11640:         unless ($nocache) {
1.1172.2.23! raeburn  11641: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  11642:         }
                   11643: 	&$func(\@content,$hashref);
1.869     albertel 11644: 	return;
1.852     albertel 11645:     }
                   11646:     close($config);
1.871     albertel 11647:     my $which = (split('/',$url))[3];
                   11648:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11649:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11650:     my @content = <$config>;
1.1172.2.17  raeburn  11651:     &$func(\@content,$hashref);
                   11652:     return;
                   11653: }
                   11654: 
                   11655: # ------------------------------------------------------Get DNS checksums file
                   11656: sub parse_dns_checksums_tab {
                   11657:     my ($lines,$hashref) = @_;
                   11658:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   11659:     my $loncaparev = &get_server_loncaparev($machine_dom);
                   11660:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   11661:     my (%chksum,%revnum);
                   11662:     if (ref($lines) eq 'ARRAY') {
                   11663:         chomp(@{$lines});
                   11664:         my $versions = shift(@{$lines});
                   11665:         my %supported;
                   11666:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
                   11667:             my $releaseslist = $1;
                   11668:             if ($releaseslist =~ /,/) {
                   11669:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
                   11670:             } elsif ($releaseslist) {
                   11671:                 $supported{$releaseslist} = 1;
                   11672:             }
                   11673:         }
                   11674:         if ($supported{$release}) {
                   11675:             my $matchthis = 0;
                   11676:             foreach my $line (@{$lines}) {
                   11677:                 if ($line =~ /^(\d[\w\.]+)$/) {
                   11678:                     if ($matchthis) {
                   11679:                         last;
                   11680:                     } elsif ($1 eq $release) {
                   11681:                         $matchthis = 1;
                   11682:                     }
                   11683:                 } elsif ($matchthis) {
                   11684:                     my ($file,$version,$shasum) = split(/,/,$line);
                   11685:                     $chksum{$file} = $shasum;
                   11686:                     $revnum{$file} = $version;
                   11687:                 }
                   11688:             }
                   11689:             if (ref($hashref) eq 'HASH') {
                   11690:                 %{$hashref} = (
                   11691:                                 sums     => \%chksum,
                   11692:                                 versions => \%revnum,
                   11693:                               );
                   11694:             }
                   11695:         }
                   11696:     }
1.869     albertel 11697:     return;
1.852     albertel 11698: }
1.1172.2.17  raeburn  11699: 
                   11700: sub fetch_dns_checksums {
                   11701:     my %checksums;
                   11702:     &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
                   11703:              \%checksums);
                   11704:     return \%checksums;
                   11705: }
                   11706: 
1.327     albertel 11707: # ------------------------------------------------------------ Read domain file
                   11708: {
1.852     albertel 11709:     my $loaded;
1.846     albertel 11710:     my %domain;
                   11711: 
1.852     albertel 11712:     sub parse_domain_tab {
                   11713: 	my ($lines) = @_;
                   11714: 	foreach my $line (@$lines) {
                   11715: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11716: 
1.846     albertel 11717: 	    chomp($line);
1.852     albertel 11718: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11719: 	    my %this_domain;
                   11720: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11721: 			       'lang_def', 'city', 'longi', 'lati',
                   11722: 			       'primary') {
                   11723: 		$this_domain{$field} = shift(@elements);
                   11724: 	    }
                   11725: 	    $domain{$name} = \%this_domain;
1.852     albertel 11726: 	}
                   11727:     }
1.864     albertel 11728: 
                   11729:     sub reset_domain_info {
                   11730: 	undef($loaded);
                   11731: 	undef(%domain);
                   11732:     }
                   11733: 
1.852     albertel 11734:     sub load_domain_tab {
1.869     albertel 11735: 	my ($ignore_cache) = @_;
                   11736: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11737: 	my $fh;
                   11738: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11739: 	    my @lines = <$fh>;
                   11740: 	    &parse_domain_tab(\@lines);
1.448     albertel 11741: 	}
1.852     albertel 11742: 	close($fh);
                   11743: 	$loaded = 1;
1.327     albertel 11744:     }
1.846     albertel 11745: 
                   11746:     sub domain {
1.852     albertel 11747: 	&load_domain_tab() if (!$loaded);
                   11748: 
1.846     albertel 11749: 	my ($name,$what) = @_;
                   11750: 	return if ( !exists($domain{$name}) );
                   11751: 
                   11752: 	if (!$what) {
                   11753: 	    return $domain{$name}{'description'};
                   11754: 	}
                   11755: 	return $domain{$name}{$what};
                   11756:     }
1.974     raeburn  11757: 
                   11758:     sub domain_info {
                   11759:         &load_domain_tab() if (!$loaded);
                   11760:         return %domain;
                   11761:     }
                   11762: 
1.327     albertel 11763: }
                   11764: 
                   11765: 
1.1       albertel 11766: # ------------------------------------------------------------- Read hosts file
                   11767: {
1.838     albertel 11768:     my %hostname;
1.844     albertel 11769:     my %hostdom;
1.845     albertel 11770:     my %libserv;
1.852     albertel 11771:     my $loaded;
1.888     albertel 11772:     my %name_to_host;
1.1074    raeburn  11773:     my %internetdom;
1.1107    raeburn  11774:     my %LC_dns_serv;
1.852     albertel 11775: 
                   11776:     sub parse_hosts_tab {
                   11777: 	my ($file) = @_;
                   11778: 	foreach my $configline (@$file) {
                   11779: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11780:             chomp($configline);
                   11781: 	    if ($configline =~ /^\^/) {
                   11782:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11783:                     $LC_dns_serv{$1} = 1;
                   11784:                 }
                   11785:                 next;
                   11786:             }
1.1074    raeburn  11787: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11788: 	    $name=~s/\s//g;
                   11789: 	    if ($id && $domain && $role && $name) {
                   11790: 		$hostname{$id}=$name;
1.888     albertel 11791: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11792: 		$hostdom{$id}=$domain;
                   11793: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11794:                 if (defined($protocol)) {
                   11795:                     if ($protocol eq 'https') {
                   11796:                         $protocol{$id} = $protocol;
                   11797:                     } else {
                   11798:                         $protocol{$id} = 'http'; 
                   11799:                     }
1.968     raeburn  11800:                 } else {
1.969     raeburn  11801:                     $protocol{$id} = 'http';
1.968     raeburn  11802:                 }
1.1074    raeburn  11803:                 if (defined($intdom)) {
                   11804:                     $internetdom{$id} = $intdom;
                   11805:                 }
1.852     albertel 11806: 	    }
                   11807: 	}
                   11808:     }
1.864     albertel 11809:     
                   11810:     sub reset_hosts_info {
1.897     albertel 11811: 	&purge_remembered();
1.864     albertel 11812: 	&reset_domain_info();
                   11813: 	&reset_hosts_ip_info();
1.892     albertel 11814: 	undef(%name_to_host);
1.864     albertel 11815: 	undef(%hostname);
                   11816: 	undef(%hostdom);
                   11817: 	undef(%libserv);
                   11818: 	undef($loaded);
                   11819:     }
1.1       albertel 11820: 
1.852     albertel 11821:     sub load_hosts_tab {
1.869     albertel 11822: 	my ($ignore_cache) = @_;
                   11823: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11824: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11825: 	my @config = <$config>;
                   11826: 	&parse_hosts_tab(\@config);
                   11827: 	close($config);
                   11828: 	$loaded=1;
1.1       albertel 11829:     }
1.852     albertel 11830: 
1.838     albertel 11831:     sub hostname {
1.852     albertel 11832: 	&load_hosts_tab() if (!$loaded);
                   11833: 
1.838     albertel 11834: 	my ($lonid) = @_;
                   11835: 	return $hostname{$lonid};
                   11836:     }
1.845     albertel 11837: 
1.838     albertel 11838:     sub all_hostnames {
1.852     albertel 11839: 	&load_hosts_tab() if (!$loaded);
                   11840: 
1.838     albertel 11841: 	return %hostname;
                   11842:     }
1.845     albertel 11843: 
1.888     albertel 11844:     sub all_names {
                   11845: 	&load_hosts_tab() if (!$loaded);
                   11846: 
                   11847: 	return %name_to_host;
                   11848:     }
                   11849: 
1.974     raeburn  11850:     sub all_host_domain {
                   11851:         &load_hosts_tab() if (!$loaded);
                   11852:         return %hostdom;
                   11853:     }
                   11854: 
1.845     albertel 11855:     sub is_library {
1.852     albertel 11856: 	&load_hosts_tab() if (!$loaded);
                   11857: 
1.845     albertel 11858: 	return exists($libserv{$_[0]});
                   11859:     }
                   11860: 
                   11861:     sub all_library {
1.852     albertel 11862: 	&load_hosts_tab() if (!$loaded);
                   11863: 
1.845     albertel 11864: 	return %libserv;
                   11865:     }
                   11866: 
1.1062    droeschl 11867:     sub unique_library {
                   11868: 	#2x reverse removes all hostnames that appear more than once
                   11869:         my %unique = reverse &all_library();
                   11870:         return reverse %unique;
                   11871:     }
                   11872: 
1.841     albertel 11873:     sub get_servers {
1.852     albertel 11874: 	&load_hosts_tab() if (!$loaded);
                   11875: 
1.841     albertel 11876: 	my ($domain,$type) = @_;
                   11877: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11878: 	                                          : %hostname;
                   11879: 	my %result;
1.842     albertel 11880: 	if (ref($domain) eq 'ARRAY') {
                   11881: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11882: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11883: 		    $result{$host} = $hostname;
                   11884: 		}
                   11885: 	    }
                   11886: 	} else {
                   11887: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11888: 		if ($hostdom{$host} eq $domain) {
                   11889: 		    $result{$host} = $hostname;
                   11890: 		}
1.841     albertel 11891: 	    }
                   11892: 	}
                   11893: 	return %result;
                   11894:     }
1.845     albertel 11895: 
1.1062    droeschl 11896:     sub get_unique_servers {
                   11897:         my %unique = reverse &get_servers(@_);
                   11898: 	return reverse %unique;
                   11899:     }
                   11900: 
1.844     albertel 11901:     sub host_domain {
1.852     albertel 11902: 	&load_hosts_tab() if (!$loaded);
                   11903: 
1.844     albertel 11904: 	my ($lonid) = @_;
                   11905: 	return $hostdom{$lonid};
                   11906:     }
                   11907: 
1.841     albertel 11908:     sub all_domains {
1.852     albertel 11909: 	&load_hosts_tab() if (!$loaded);
                   11910: 
1.841     albertel 11911: 	my %seen;
                   11912: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11913: 	return @uniq;
                   11914:     }
1.1074    raeburn  11915: 
                   11916:     sub internet_dom {
                   11917:         &load_hosts_tab() if (!$loaded);
                   11918: 
                   11919:         my ($lonid) = @_;
                   11920:         return $internetdom{$lonid};
                   11921:     }
1.1107    raeburn  11922: 
                   11923:     sub is_LC_dns {
                   11924:         &load_hosts_tab() if (!$loaded);
                   11925: 
                   11926:         my ($hostname) = @_;
                   11927:         return exists($LC_dns_serv{$hostname});
                   11928:     }
                   11929: 
1.1       albertel 11930: }
                   11931: 
1.847     albertel 11932: { 
                   11933:     my %iphost;
1.856     albertel 11934:     my %name_to_ip;
                   11935:     my %lonid_to_ip;
1.869     albertel 11936: 
1.847     albertel 11937:     sub get_hosts_from_ip {
                   11938: 	my ($ip) = @_;
                   11939: 	my %iphosts = &get_iphost();
                   11940: 	if (ref($iphosts{$ip})) {
                   11941: 	    return @{$iphosts{$ip}};
                   11942: 	}
                   11943: 	return;
1.839     albertel 11944:     }
1.864     albertel 11945:     
                   11946:     sub reset_hosts_ip_info {
                   11947: 	undef(%iphost);
                   11948: 	undef(%name_to_ip);
                   11949: 	undef(%lonid_to_ip);
                   11950:     }
1.856     albertel 11951: 
                   11952:     sub get_host_ip {
                   11953: 	my ($lonid) = @_;
                   11954: 	if (exists($lonid_to_ip{$lonid})) {
                   11955: 	    return $lonid_to_ip{$lonid};
                   11956: 	}
                   11957: 	my $name=&hostname($lonid);
                   11958:    	my $ip = gethostbyname($name);
                   11959: 	return if (!$ip || length($ip) ne 4);
                   11960: 	$ip=inet_ntoa($ip);
                   11961: 	$name_to_ip{$name}   = $ip;
                   11962: 	$lonid_to_ip{$lonid} = $ip;
                   11963: 	return $ip;
                   11964:     }
1.847     albertel 11965:     
                   11966:     sub get_iphost {
1.869     albertel 11967: 	my ($ignore_cache) = @_;
1.894     albertel 11968: 
1.869     albertel 11969: 	if (!$ignore_cache) {
                   11970: 	    if (%iphost) {
                   11971: 		return %iphost;
                   11972: 	    }
                   11973: 	    my ($ip_info,$cached)=
                   11974: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11975: 	    if ($cached) {
                   11976: 		%iphost      = %{$ip_info->[0]};
                   11977: 		%name_to_ip  = %{$ip_info->[1]};
                   11978: 		%lonid_to_ip = %{$ip_info->[2]};
                   11979: 		return %iphost;
                   11980: 	    }
                   11981: 	}
1.894     albertel 11982: 
                   11983: 	# get yesterday's info for fallback
                   11984: 	my %old_name_to_ip;
                   11985: 	my ($ip_info,$cached)=
                   11986: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11987: 	if ($cached) {
                   11988: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11989: 	}
                   11990: 
1.888     albertel 11991: 	my %name_to_host = &all_names();
                   11992: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11993: 	    my $ip;
                   11994: 	    if (!exists($name_to_ip{$name})) {
                   11995: 		$ip = gethostbyname($name);
                   11996: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11997: 		    if (defined($old_name_to_ip{$name})) {
                   11998: 			$ip = $old_name_to_ip{$name};
                   11999: 			&logthis("Can't find $name defaulting to old $ip");
                   12000: 		    } else {
                   12001: 			&logthis("Name $name no IP found");
                   12002: 			next;
                   12003: 		    }
                   12004: 		} else {
                   12005: 		    $ip=inet_ntoa($ip);
1.847     albertel 12006: 		}
                   12007: 		$name_to_ip{$name} = $ip;
                   12008: 	    } else {
                   12009: 		$ip = $name_to_ip{$name};
1.653     albertel 12010: 	    }
1.888     albertel 12011: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12012: 		$lonid_to_ip{$id} = $ip;
                   12013: 	    }
                   12014: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12015: 	}
1.1172.2.23! raeburn  12016: 	&do_cache_new('iphost','iphost',
        !          12017: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
        !          12018: 		      48*60*60);
1.869     albertel 12019: 
1.847     albertel 12020: 	return %iphost;
1.598     albertel 12021:     }
                   12022: 
1.992     raeburn  12023:     #
                   12024:     #  Given a DNS returns the loncapa host name for that DNS 
                   12025:     # 
                   12026:     sub host_from_dns {
                   12027:         my ($dns) = @_;
                   12028:         my @hosts;
                   12029:         my $ip;
                   12030: 
1.993     raeburn  12031:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12032:             $ip = $name_to_ip{$dns};
                   12033:         }
                   12034:         if (!$ip) {
                   12035:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12036:             if (length($ip) == 4) { 
                   12037: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12038:             }
                   12039:         }
                   12040:         if ($ip) {
                   12041: 	    @hosts = get_hosts_from_ip($ip);
                   12042: 	    return $hosts[0];
                   12043:         }
                   12044:         return undef;
1.986     foxr     12045:     }
1.992     raeburn  12046: 
1.1074    raeburn  12047:     sub get_internet_names {
                   12048:         my ($lonid) = @_;
                   12049:         return if ($lonid eq '');
                   12050:         my ($idnref,$cached)=
                   12051:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12052:         if ($cached) {
                   12053:             return $idnref;
                   12054:         }
                   12055:         my $ip = &get_host_ip($lonid);
                   12056:         my @hosts = &get_hosts_from_ip($ip);
                   12057:         my %iphost = &get_iphost();
                   12058:         my (@idns,%seen);
                   12059:         foreach my $id (@hosts) {
                   12060:             my $dom = &host_domain($id);
                   12061:             my $prim_id = &domain($dom,'primary');
                   12062:             my $prim_ip = &get_host_ip($prim_id);
                   12063:             next if ($seen{$prim_ip});
                   12064:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12065:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12066:                     my $intdom = &internet_dom($id);
                   12067:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12068:                         push(@idns,$intdom);
                   12069:                     }
                   12070:                 }
                   12071:             }
                   12072:             $seen{$prim_ip} = 1;
                   12073:         }
1.1172.2.23! raeburn  12074:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12075:     }
                   12076: 
1.986     foxr     12077: }
                   12078: 
1.1079    raeburn  12079: sub all_loncaparevs {
                   12080:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
                   12081: }
                   12082: 
1.862     albertel 12083: BEGIN {
                   12084: 
                   12085: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12086:     unless ($readit) {
                   12087: {
                   12088:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12089:     %perlvar = (%perlvar,%{$configvars});
                   12090: }
                   12091: 
                   12092: 
1.1       albertel 12093: # ------------------------------------------------------ Read spare server file
                   12094: {
1.448     albertel 12095:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12096: 
                   12097:     while (my $configline=<$config>) {
                   12098:        chomp($configline);
1.284     matthew  12099:        if ($configline) {
1.784     albertel 12100: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12101: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12102: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12103:        }
                   12104:     }
1.448     albertel 12105:     close($config);
1.1       albertel 12106: }
1.11      www      12107: # ------------------------------------------------------------ Read permissions
                   12108: {
1.448     albertel 12109:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12110: 
                   12111:     while (my $configline=<$config>) {
1.448     albertel 12112: 	chomp($configline);
                   12113: 	if ($configline) {
                   12114: 	    my ($role,$perm)=split(/ /,$configline);
                   12115: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12116: 	}
1.11      www      12117:     }
1.448     albertel 12118:     close($config);
1.11      www      12119: }
                   12120: 
                   12121: # -------------------------------------------- Read plain texts for permissions
                   12122: {
1.448     albertel 12123:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12124: 
                   12125:     while (my $configline=<$config>) {
1.448     albertel 12126: 	chomp($configline);
                   12127: 	if ($configline) {
1.742     raeburn  12128: 	    my ($short,@plain)=split(/:/,$configline);
                   12129:             %{$prp{$short}} = ();
                   12130: 	    if (@plain > 0) {
                   12131:                 $prp{$short}{'std'} = $plain[0];
                   12132:                 for (my $i=1; $i<@plain; $i++) {
                   12133:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12134:                 }
                   12135:             }
1.448     albertel 12136: 	}
1.135     www      12137:     }
1.448     albertel 12138:     close($config);
1.135     www      12139: }
                   12140: 
                   12141: # ---------------------------------------------------------- Read package table
                   12142: {
1.448     albertel 12143:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12144: 
                   12145:     while (my $configline=<$config>) {
1.483     albertel 12146: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12147: 	chomp($configline);
                   12148: 	my ($short,$plain)=split(/:/,$configline);
                   12149: 	my ($pack,$name)=split(/\&/,$short);
                   12150: 	if ($plain ne '') {
                   12151: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12152: 	    $packagetab{$short}=$plain; 
                   12153: 	}
1.11      www      12154:     }
1.448     albertel 12155:     close($config);
1.329     matthew  12156: }
                   12157: 
1.1073    raeburn  12158: # ---------------------------------------------------------- Read loncaparev table
                   12159: {
                   12160:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12161:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12162:             while (my $configline=<$config>) {
                   12163:                 chomp($configline);
                   12164:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   12165:                 $loncaparevs{$hostid}=$loncaparev;
                   12166:             }
                   12167:             close($config);
                   12168:         }
                   12169:     }
                   12170: }
                   12171: 
1.1074    raeburn  12172: # ---------------------------------------------------------- Read serverhostID table
                   12173: {
                   12174:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12175:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12176:             while (my $configline=<$config>) {
                   12177:                 chomp($configline);
                   12178:                 my ($name,$id)=split(/:/,$configline);
                   12179:                 $serverhomeIDs{$name}=$id;
                   12180:             }
                   12181:             close($config);
                   12182:         }
                   12183:     }
                   12184: }
                   12185: 
1.1079    raeburn  12186: {
                   12187:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12188:     if (-e $file) {
                   12189:         my $parser = HTML::LCParser->new($file);
                   12190:         while (my $token = $parser->get_token()) {
                   12191:             if ($token->[0] eq 'S') {
                   12192:                 my $item = $token->[1];
                   12193:                 my $name = $token->[2]{'name'};
                   12194:                 my $value = $token->[2]{'value'};
                   12195:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12196:                     my $release = $parser->get_text();
                   12197:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12198:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12199:                 }
                   12200:             }
                   12201:         }
                   12202:     }
1.1073    raeburn  12203: }
                   12204: 
1.1138    raeburn  12205: # ---------------------------------------------------------- Read managers table
                   12206: {
                   12207:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12208:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12209:             while (my $configline=<$config>) {
                   12210:                 chomp($configline);
                   12211:                 next if ($configline =~ /^\#/);
                   12212:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12213:                     $managerstab{$configline} = 1;
                   12214:                 }
                   12215:             }
                   12216:             close($config);
                   12217:         }
                   12218:     }
                   12219: }
                   12220: 
1.329     matthew  12221: # ------------- set up temporary directory
                   12222: {
1.1117    foxr     12223:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12224: 
1.11      www      12225: }
                   12226: 
1.794     albertel 12227: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12228: 				'compress_threshold'=> 20_000,
                   12229:  			        });
1.185     www      12230: 
1.281     www      12231: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12232: $dumpcount=0;
1.958     www      12233: $locknum=0;
1.22      www      12234: 
1.163     harris41 12235: &logtouch();
1.672     albertel 12236: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12237: $readit=1;
1.564     albertel 12238:     {
                   12239: 	use integer;
                   12240: 	my $test=(2**32)+1;
1.568     albertel 12241: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12242: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12243:     }
1.1172.2.18  raeburn  12244: 
                   12245:     {
                   12246:         eval {
                   12247:             ($apache) =
                   12248:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
                   12249:         };
                   12250:         if ($@) {
                   12251:            $apache = 1.3;
                   12252:         }
                   12253:     }
                   12254: 
1.195     www      12255: }
1.1       albertel 12256: }
1.179     www      12257: 
1.1       albertel 12258: 1;
1.191     harris41 12259: __END__
                   12260: 
1.243     albertel 12261: =pod
                   12262: 
1.191     harris41 12263: =head1 NAME
                   12264: 
1.243     albertel 12265: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12266: 
                   12267: =head1 SYNOPSIS
                   12268: 
1.243     albertel 12269: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12270: 
                   12271:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12272: 
1.243     albertel 12273: Common parameters:
                   12274: 
                   12275: =over 4
                   12276: 
                   12277: =item *
                   12278: 
                   12279: $uname : an internal username (if $cname expecting a course Id specifically)
                   12280: 
                   12281: =item *
                   12282: 
                   12283: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12284: 
                   12285: =item *
                   12286: 
                   12287: $symb : a resource instance identifier
                   12288: 
                   12289: =item *
                   12290: 
                   12291: $namespace : the name of a .db file that contains the data needed or
                   12292: being set.
                   12293: 
                   12294: =back
                   12295: 
1.394     bowersj2 12296: =head1 OVERVIEW
1.191     harris41 12297: 
1.394     bowersj2 12298: lonnet provides subroutines which interact with the
                   12299: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12300: about classes, users, and resources.
1.243     albertel 12301: 
                   12302: For many of these objects you can also use this to store data about
                   12303: them or modify them in various ways.
1.191     harris41 12304: 
1.394     bowersj2 12305: =head2 Symbs
1.191     harris41 12306: 
1.394     bowersj2 12307: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12308: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12309: map, the resource number of the resource in the map, and the URL of
                   12310: the resource itself. The latter is somewhat redundant, but might help
                   12311: if maps change.
                   12312: 
                   12313: An example is
                   12314: 
                   12315:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12316: 
                   12317: The respective map entry is
                   12318: 
                   12319:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12320:   title="Problem 2">
                   12321:  </resource>
                   12322: 
                   12323: Symbs are used by the random number generator, as well as to store and
                   12324: restore data specific to a certain instance of for example a problem.
                   12325: 
                   12326: =head2 Storing And Retrieving Data
                   12327: 
                   12328: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12329: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12330: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12331: is is the non-critical message twin of cstore. These functions are for
                   12332: handlers to store a perl hash to a user's permanent data space in an
                   12333: easy manner, and to retrieve it again on another call. It is expected
                   12334: that a handler would use this once at the beginning to retrieve data,
                   12335: and then again once at the end to send only the new data back.
                   12336: 
                   12337: The data is stored in the user's data directory on the user's
                   12338: homeserver under the ID of the course.
                   12339: 
                   12340: The hash that is returned by restore will have all of the previous
                   12341: value for all of the elements of the hash.
                   12342: 
                   12343: Example:
                   12344: 
                   12345:  #creating a hash
                   12346:  my %hash;
                   12347:  $hash{'foo'}='bar';
                   12348: 
                   12349:  #storing it
                   12350:  &Apache::lonnet::cstore(\%hash);
                   12351: 
                   12352:  #changing a value
                   12353:  $hash{'foo'}='notbar';
                   12354: 
                   12355:  #adding a new value
                   12356:  $hash{'bar'}='foo';
                   12357:  &Apache::lonnet::cstore(\%hash);
                   12358: 
                   12359:  #retrieving the hash
                   12360:  my %history=&Apache::lonnet::restore();
                   12361: 
                   12362:  #print the hash
                   12363:  foreach my $key (sort(keys(%history))) {
                   12364:    print("\%history{$key} = $history{$key}");
                   12365:  }
                   12366: 
                   12367: Will print out:
1.191     harris41 12368: 
1.394     bowersj2 12369:  %history{1:foo} = bar
                   12370:  %history{1:keys} = foo:timestamp
                   12371:  %history{1:timestamp} = 990455579
                   12372:  %history{2:bar} = foo
                   12373:  %history{2:foo} = notbar
                   12374:  %history{2:keys} = foo:bar:timestamp
                   12375:  %history{2:timestamp} = 990455580
                   12376:  %history{bar} = foo
                   12377:  %history{foo} = notbar
                   12378:  %history{timestamp} = 990455580
                   12379:  %history{version} = 2
                   12380: 
                   12381: Note that the special hash entries C<keys>, C<version> and
                   12382: C<timestamp> were added to the hash. C<version> will be equal to the
                   12383: total number of versions of the data that have been stored. The
                   12384: C<timestamp> attribute will be the UNIX time the hash was
                   12385: stored. C<keys> is available in every historical section to list which
                   12386: keys were added or changed at a specific historical revision of a
                   12387: hash.
                   12388: 
                   12389: B<Warning>: do not store the hash that restore returns directly. This
                   12390: will cause a mess since it will restore the historical keys as if the
                   12391: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12392: 
1.394     bowersj2 12393: Calling convention:
1.191     harris41 12394: 
1.394     bowersj2 12395:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   12396:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 12397: 
1.394     bowersj2 12398: For more detailed information, see lonnet specific documentation.
1.191     harris41 12399: 
1.394     bowersj2 12400: =head1 RETURN MESSAGES
1.191     harris41 12401: 
1.394     bowersj2 12402: =over 4
1.191     harris41 12403: 
1.394     bowersj2 12404: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12405: 
1.394     bowersj2 12406: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12407: when the connection is brought back up
1.191     harris41 12408: 
1.394     bowersj2 12409: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12410: for later delivery
1.191     harris41 12411: 
1.967     bisitz   12412: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12413: 
1.394     bowersj2 12414: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12415: that was requested
1.191     harris41 12416: 
1.243     albertel 12417: =back
1.191     harris41 12418: 
1.243     albertel 12419: =head1 PUBLIC SUBROUTINES
1.191     harris41 12420: 
1.243     albertel 12421: =head2 Session Environment Functions
1.191     harris41 12422: 
1.243     albertel 12423: =over 4
1.191     harris41 12424: 
1.394     bowersj2 12425: =item * 
                   12426: X<appenv()>
1.949     raeburn  12427: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 12428: the user envirnoment file, and will be restored for each access this
1.620     albertel 12429: user makes during this session, also modifies the %env for the current
1.949     raeburn  12430: process. Optional rolesarrayref - if defined contains a reference to an array
                   12431: of roles which are exempt from the restriction on modifying user.role entries 
                   12432: in the user's environment.db and in %env.    
1.191     harris41 12433: 
                   12434: =item *
1.394     bowersj2 12435: X<delenv()>
1.987     raeburn  12436: B<delenv($delthis,$regexp)>: removes all items from the session
                   12437: environment file that begin with $delthis. If the 
                   12438: optional second arg - $regexp - is true, $delthis is treated as a 
                   12439: regular expression, otherwise \Q$delthis\E is used. 
                   12440: The values are also deleted from the current processes %env.
1.191     harris41 12441: 
1.795     albertel 12442: =item * get_env_multiple($name) 
                   12443: 
                   12444: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   12445: values may be defined and end up as an array ref.
                   12446: 
                   12447: returns an array of values
                   12448: 
1.243     albertel 12449: =back
                   12450: 
                   12451: =head2 User Information
1.191     harris41 12452: 
1.243     albertel 12453: =over 4
1.191     harris41 12454: 
                   12455: =item *
1.394     bowersj2 12456: X<queryauthenticate()>
                   12457: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 12458: authentication scheme
                   12459: 
                   12460: =item *
1.394     bowersj2 12461: X<authenticate()>
1.1073    raeburn  12462: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 12463: authenticate user from domain's lib servers (first use the current
                   12464: one). C<$upass> should be the users password.
1.1073    raeburn  12465: $checkdefauth is optional (value is 1 if a check should be made to
                   12466:    authenticate user using default authentication method, and allow
                   12467:    account creation if username does not have account in the domain).
                   12468: $clientcancheckhost is optional (value is 1 if checking whether the
                   12469:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 12470: 
                   12471: =item *
1.394     bowersj2 12472: X<homeserver()>
                   12473: B<homeserver($uname,$udom)>: find the server which has
                   12474: the user's directory and files (there must be only one), this caches
                   12475: the answer, and also caches if there is a borken connection.
1.191     harris41 12476: 
                   12477: =item *
1.394     bowersj2 12478: X<idget()>
                   12479: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   12480: (IDs are a unique resource in a domain, there must be only 1 ID per
                   12481: username, and only 1 username per ID in a specific domain) (returns
                   12482: hash: id=>name,id=>name)
1.191     harris41 12483: 
                   12484: =item *
1.394     bowersj2 12485: X<idrget()>
                   12486: B<idrget($udom,@unames)>: find the IDs behind a list of
                   12487: usernames (returns hash: name=>id,name=>id)
1.191     harris41 12488: 
                   12489: =item *
1.394     bowersj2 12490: X<idput()>
                   12491: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 12492: 
                   12493: =item *
1.394     bowersj2 12494: X<rolesinit()>
1.1169    droeschl 12495: B<rolesinit($udom,$username)>: get user privileges.
                   12496: returns user role, first access and timer interval hashes
1.243     albertel 12497: 
                   12498: =item *
1.1171    droeschl 12499: X<privileged()>
                   12500: B<privileged($username,$domain)>: returns a true if user has a
                   12501: privileged and active role (i.e. su or dc), false otherwise.
                   12502: 
                   12503: =item *
1.551     albertel 12504: X<getsection()>
                   12505: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 12506: course $cname, return section name/number or '' for "not in course"
                   12507: and '-1' for "no section"
                   12508: 
                   12509: =item *
1.394     bowersj2 12510: X<userenvironment()>
                   12511: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 12512: passed in @what from the requested user's environment, returns a hash
                   12513: 
1.858     raeburn  12514: =item * 
                   12515: X<userlog_query()>
1.859     albertel 12516: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   12517: activity.log file. %filters defines filters applied when parsing the
                   12518: log file. These can be start or end timestamps, or the type of action
                   12519: - log to look for Login or Logout events, check for Checkin or
                   12520: Checkout, role for role selection. The response is in the form
                   12521: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   12522: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  12523: 
1.243     albertel 12524: =back
                   12525: 
                   12526: =head2 User Roles
                   12527: 
                   12528: =over 4
                   12529: 
                   12530: =item *
                   12531: 
1.810     raeburn  12532: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 12533:  F: full access
                   12534:  U,I,K: authentication modes (cxx only)
                   12535:  '': forbidden
                   12536:  1: user needs to choose course
                   12537:  2: browse allowed
1.766     albertel 12538:  A: passphrase authentication needed
1.243     albertel 12539: 
                   12540: =item *
                   12541: 
1.1172.2.13  raeburn  12542: constructaccess($url,$setpriv) : check for access to construction space URL
                   12543: 
                   12544: See if the owner domain and name in the URL match those in the
                   12545: expected environment.  If so, return three element list
                   12546: ($ownername,$ownerdomain,$ownerhome).
                   12547: 
                   12548: Otherwise return the null string.
                   12549: 
                   12550: If second argument 'setpriv' is true, it assigns the privileges,
                   12551: and returns the same three element list, unless the owner has
                   12552: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   12553: in which case the null string is returned.
                   12554: 
                   12555: =item *
                   12556: 
1.243     albertel 12557: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   12558: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   12559: and course level
                   12560: 
                   12561: =item *
                   12562: 
1.988     raeburn  12563: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   12564: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  12565: $type is Course (default) or Community.
1.988     raeburn  12566: If $forcedefault evaluates to true, text returned will be default 
                   12567: text for $type. Otherwise, if this is a course, the text returned 
                   12568: will be a custom name for the role (if defined in the course's 
                   12569: environment).  If no custom name is defined the default is returned.
                   12570:    
1.832     raeburn  12571: =item *
                   12572: 
1.1172.2.23! raeburn  12573: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  12574: All arguments are optional. Returns a hash of a roles, either for
                   12575: co-author/assistant author roles for a user's Construction Space
1.906     albertel 12576: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  12577: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   12578: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   12579: For each key, value is set to colon-separated start and end times for
                   12580: the role.  If no username and domain are specified, will default to
1.934     raeburn  12581: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  12582: of role statuses (active, future or previous), roles 
                   12583: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   12584: to restrict the list of roles reported. If no array ref is 
                   12585: provided for types, will default to return only active roles.
1.834     albertel 12586: 
1.1172.2.13  raeburn  12587: =item *
                   12588: 
                   12589: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   12590: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   12591: 
                   12592: Additional optional arguments are: $type (if role checking is to be restricted
                   12593: to certain user status types -- previous (expired roles), active (currently
                   12594: available roles) or future (roles available in the future), and
                   12595: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23! raeburn  12596: have active Domain Coordinator role in course's domain or in additional
        !          12597: domains (specified in 'Domains to check for privileged users' in course
        !          12598: environment -- set via:  Course Settings -> Classlists and staff listing).
        !          12599: 
        !          12600: =item *
        !          12601: 
        !          12602: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
        !          12603: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
        !          12604: $possdomains and $possroles are optional array refs -- to domains to check and
        !          12605: roles to check.  If $possdomains is not specified, a dump will be done of the
        !          12606: users' roles.db to check for a dc or su role in any domain. This can be
        !          12607: time consuming if &privileged is called repeatedly (e.g., when displaying a
        !          12608: classlist), so in such cases, supplying a $possdomains array is preferred, as
        !          12609: this then allows &privileged_by_domain() to be used, which caches the identity
        !          12610: of privileged users, eliminating the need for repeated calls to &dump().
        !          12611: 
        !          12612: =item *
        !          12613: 
        !          12614: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
        !          12615: where the outer hash keys are domains specified in the $possdomains array ref,
        !          12616: next inner hash keys are privileged roles specified in the $roles array ref,
        !          12617: and the innermost hash contains key = value pairs for username:domain = end:start
        !          12618: for active or future "privileged" users with that role in that domain. To avoid
        !          12619: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
        !          12620: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  12621: 
1.243     albertel 12622: =back
                   12623: 
                   12624: =head2 User Modification
                   12625: 
                   12626: =over 4
                   12627: 
                   12628: =item *
                   12629: 
1.957     raeburn  12630: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 12631: user for the level given by URL.  Optional start and end dates (leave empty
                   12632: string or zero for "no date")
1.191     harris41 12633: 
                   12634: =item *
                   12635: 
1.243     albertel 12636: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   12637: change a users, password, possible return values are: ok,
                   12638: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   12639: refused
1.191     harris41 12640: 
                   12641: =item *
                   12642: 
1.243     albertel 12643: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 12644: 
                   12645: =item *
                   12646: 
1.1058    raeburn  12647: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   12648:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   12649: 
                   12650: will update user information (firstname,middlename,lastname,generation,
                   12651: permanentemail), and if forceid is true, student/employee ID also.
                   12652: A user's institutional affiliation(s) can also be updated.
                   12653: User information fields will not be overwritten with empty entries 
                   12654: unless the field is included in the $candelete array reference.
                   12655: This array is included when a single user is modified via "Manage Users",
                   12656: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 12657: 
                   12658: =item *
                   12659: 
1.286     matthew  12660: modifystudent
                   12661: 
1.957     raeburn  12662: modify a student's enrollment and identification information.
1.286     matthew  12663: The course id is resolved based on the current users environment.  
                   12664: This means the envoking user must be a course coordinator or otherwise
                   12665: associated with a course.
                   12666: 
1.297     matthew  12667: This call is essentially a wrapper for lonnet::modifyuser and
                   12668: lonnet::modify_student_enrollment
1.286     matthew  12669: 
                   12670: Inputs: 
                   12671: 
                   12672: =over 4
                   12673: 
1.957     raeburn  12674: =item B<$udom> Student's loncapa domain
1.286     matthew  12675: 
1.957     raeburn  12676: =item B<$uname> Student's loncapa login name
1.286     matthew  12677: 
1.964     bisitz   12678: =item B<$uid> Student/Employee ID
1.286     matthew  12679: 
1.957     raeburn  12680: =item B<$umode> Student's authentication mode
1.286     matthew  12681: 
1.957     raeburn  12682: =item B<$upass> Student's password
1.286     matthew  12683: 
1.957     raeburn  12684: =item B<$first> Student's first name
1.286     matthew  12685: 
1.957     raeburn  12686: =item B<$middle> Student's middle name
1.286     matthew  12687: 
1.957     raeburn  12688: =item B<$last> Student's last name
1.286     matthew  12689: 
1.957     raeburn  12690: =item B<$gene> Student's generation
1.286     matthew  12691: 
1.957     raeburn  12692: =item B<$usec> Student's section in course
1.286     matthew  12693: 
                   12694: =item B<$end> Unix time of the roles expiration
                   12695: 
                   12696: =item B<$start> Unix time of the roles start date
                   12697: 
                   12698: =item B<$forceid> If defined, allow $uid to be changed
                   12699: 
                   12700: =item B<$desiredhome> server to use as home server for student
                   12701: 
1.957     raeburn  12702: =item B<$email> Student's permanent e-mail address
                   12703: 
                   12704: =item B<$type> Type of enrollment (auto or manual)
                   12705: 
1.963     raeburn  12706: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   12707: 
                   12708: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12709: 
1.963     raeburn  12710: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12711: 
1.963     raeburn  12712: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12713: 
1.1172.2.19  raeburn  12714: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   12715: 
                   12716: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
1.957     raeburn  12717: 
1.286     matthew  12718: =back
1.297     matthew  12719: 
                   12720: =item *
                   12721: 
                   12722: modify_student_enrollment
                   12723: 
                   12724: Change a students enrollment status in a class.  The environment variable
                   12725: 'role.request.course' must be defined for this function to proceed.
                   12726: 
                   12727: Inputs:
                   12728: 
                   12729: =over 4
                   12730: 
                   12731: =item $udom, students domain
                   12732: 
                   12733: =item $uname, students name
                   12734: 
                   12735: =item $uid, students user id
                   12736: 
                   12737: =item $first, students first name
                   12738: 
                   12739: =item $middle
                   12740: 
                   12741: =item $last
                   12742: 
                   12743: =item $gene
                   12744: 
                   12745: =item $usec
                   12746: 
                   12747: =item $end
                   12748: 
                   12749: =item $start
                   12750: 
1.957     raeburn  12751: =item $type
                   12752: 
                   12753: =item $locktype
                   12754: 
                   12755: =item $cid
                   12756: 
                   12757: =item $selfenroll
                   12758: 
                   12759: =item $context
                   12760: 
1.1172.2.19  raeburn  12761: =item $credits, number of credits student will earn from this class
                   12762: 
1.297     matthew  12763: =back
                   12764: 
1.191     harris41 12765: 
                   12766: =item *
                   12767: 
1.243     albertel 12768: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12769: custom role; give a custom role to a user for the level given by URL.  Specify
                   12770: name and domain of role author, and role name
1.191     harris41 12771: 
                   12772: =item *
                   12773: 
1.243     albertel 12774: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12775: 
                   12776: =item *
                   12777: 
1.243     albertel 12778: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12779: 
                   12780: =back
                   12781: 
                   12782: =head2 Course Infomation
                   12783: 
                   12784: =over 4
1.191     harris41 12785: 
                   12786: =item *
                   12787: 
1.1118    foxr     12788: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12789: specified course id, including all environment settings for the
                   12790: course, the description of the course will be in the hash under the
                   12791: key 'description'
1.191     harris41 12792: 
1.1118    foxr     12793: $options is an optional parameter that if supplied is a hash reference that controls
                   12794: what how this function works.  It has the following key/values:
                   12795: 
                   12796: =over 4
                   12797: 
                   12798: =item freshen_cache
                   12799: 
                   12800: If defined, and the environment cache for the course is valid, it is 
                   12801: returned in the returned hash.
                   12802: 
                   12803: =item one_time
                   12804: 
                   12805: If defined, the last cache time is set to _now_
                   12806: 
                   12807: =item user
                   12808: 
                   12809: If defined, the supplied username is used instead of the current user.
                   12810: 
                   12811: 
                   12812: =back
                   12813: 
1.191     harris41 12814: =item *
                   12815: 
1.624     albertel 12816: resdata($name,$domain,$type,@which) : request for current parameter
                   12817: setting for a specific $type, where $type is either 'course' or 'user',
                   12818: @what should be a list of parameters to ask about. This routine caches
                   12819: answers for 5 minutes.
1.243     albertel 12820: 
1.877     foxr     12821: =item *
                   12822: 
                   12823: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12824: data base, returning a hash that is keyed by the resource name and has
                   12825: values that are the resource value.  I believe that the timestamps and
                   12826: versions are also returned.
                   12827: 
1.243     albertel 12828: =back
                   12829: 
                   12830: =head2 Course Modification
                   12831: 
                   12832: =over 4
1.191     harris41 12833: 
                   12834: =item *
                   12835: 
1.243     albertel 12836: writecoursepref($courseid,%prefs) : write preferences (environment
                   12837: database) for a course
1.191     harris41 12838: 
                   12839: =item *
                   12840: 
1.1011    raeburn  12841: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12842: 
                   12843: =item *
                   12844: 
1.1038    raeburn  12845: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12846: 
1.1167    droeschl 12847: =item *
                   12848: 
                   12849: is_course($courseid), is_course($cdom, $cnum)
                   12850: 
                   12851: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12852: two component version $cdom, $cnum. It checks if the specified course exists.
                   12853: 
                   12854: Returns:
                   12855:     undef if the course doesn't exist, otherwise
                   12856:     in scalar context the combined courseid.
                   12857:     in list context the two components of the course identifier, domain and 
                   12858:     courseid.    
                   12859: 
1.243     albertel 12860: =back
                   12861: 
                   12862: =head2 Resource Subroutines
                   12863: 
                   12864: =over 4
1.191     harris41 12865: 
                   12866: =item *
                   12867: 
1.243     albertel 12868: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12869: 
                   12870: =item *
                   12871: 
1.243     albertel 12872: repcopy($filename) : subscribes to the requested file, and attempts to
                   12873: replicate from the owning library server, Might return
1.607     raeburn  12874: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12875: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12876: resource. Expects the local filesystem pathname
                   12877: (/home/httpd/html/res/....)
                   12878: 
                   12879: =back
                   12880: 
                   12881: =head2 Resource Information
                   12882: 
                   12883: =over 4
1.191     harris41 12884: 
                   12885: =item *
                   12886: 
1.243     albertel 12887: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12888: a vairety of different possible values, $varname should be a request
                   12889: string, and the other parameters can be used to specify who and what
                   12890: one is asking about.
                   12891: 
                   12892: Possible values for $varname are environment.lastname (or other item
                   12893: from the envirnment hash), user.name (or someother aspect about the
                   12894: user), resource.0.maxtries (or some other part and parameter of a
                   12895: resource)
1.204     albertel 12896: 
                   12897: =item *
                   12898: 
1.243     albertel 12899: directcondval($number) : get current value of a condition; reads from a state
                   12900: string
1.204     albertel 12901: 
                   12902: =item *
                   12903: 
1.243     albertel 12904: condval($condidx) : value of condition index based on state
1.204     albertel 12905: 
                   12906: =item *
                   12907: 
1.243     albertel 12908: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12909: resource's metadata, $what should be either a specific key, or either
                   12910: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12911: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12912: 
                   12913: this function automatically caches all requests
1.191     harris41 12914: 
                   12915: =item *
                   12916: 
1.243     albertel 12917: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12918: network of library servers; returns file handle of where SQL and regex results
                   12919: will be stored for query
1.191     harris41 12920: 
                   12921: =item *
                   12922: 
1.243     albertel 12923: symbread($filename) : return symbolic list entry (filename argument optional);
                   12924: returns the data handle
1.191     harris41 12925: 
                   12926: =item *
                   12927: 
1.1172.2.17  raeburn  12928: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  12929: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 12930: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  12931: on failure, user must be in a course, as it assumes the existence of
                   12932: the course initial hash, and uses $env('request.course.id'}.  The third
                   12933: arg is an optional reference to a scalar.  If this arg is passed in the
                   12934: call to symbverify, it will be set to 1 if the symb has been set to be 
                   12935: encrypted; otherwise it will be null.
1.243     albertel 12936: 
1.191     harris41 12937: =item *
                   12938: 
1.243     albertel 12939: symbclean($symb) : removes versions numbers from a symb, returns the
                   12940: cleaned symb
1.191     harris41 12941: 
                   12942: =item *
                   12943: 
1.243     albertel 12944: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12945: course map, user must be in a course for it to work.
1.191     harris41 12946: 
                   12947: =item *
                   12948: 
1.243     albertel 12949: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12950: 
                   12951: =item *
                   12952: 
1.243     albertel 12953: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12954: a random seed, all arguments are optional, if they aren't sent it uses the
                   12955: environment to derive them. Note: if symb isn't sent and it can't get one
                   12956: from &symbread it will use the current time as its return value
1.191     harris41 12957: 
                   12958: =item *
                   12959: 
1.243     albertel 12960: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12961: unfakeable, receipt
1.191     harris41 12962: 
                   12963: =item *
                   12964: 
1.620     albertel 12965: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12966: 
                   12967: =item *
                   12968: 
1.243     albertel 12969: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12970: 
                   12971: =item *
                   12972: 
1.243     albertel 12973: 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 12974: 
                   12975: =item *
                   12976: 
1.243     albertel 12977: 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 12978: 
                   12979: =item *
                   12980: 
1.243     albertel 12981: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12982: 
                   12983: =item *
                   12984: 
1.243     albertel 12985: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12986: forcing spreadsheet to reevaluate the resource scores next time.
                   12987: 
1.1172.2.13  raeburn  12988: =item *
                   12989: 
                   12990: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   12991: when viewing in course context.
                   12992: 
                   12993:  input: six args -- filename (decluttered), course number, course domain,
                   12994:                     url, symb (if registered) and group (if this is a
                   12995:                     group item -- e.g., bulletin board, group page etc.).
                   12996: 
                   12997:  output: array of five scalars --
                   12998:          $cfile -- url for file editing if editable on current server
                   12999:          $home -- homeserver of resource (i.e., for author if published,
                   13000:                                           or course if uploaded.).
                   13001:          $switchserver --  1 if server switch will be needed.
                   13002:          $forceedit -- 1 if icon/link should be to go to edit mode
                   13003:          $forceview -- 1 if icon/link should be to go to view mode
                   13004: 
                   13005: =item *
                   13006: 
                   13007: is_course_upload($file,$cnum,$cdom)
                   13008: 
                   13009: Used in course context to determine if current file was uploaded to
                   13010: the course (i.e., would be found in /userfiles/docs on the course's
                   13011: homeserver.
                   13012: 
                   13013:   input: 3 args -- filename (decluttered), course number and course domain.
                   13014:   output: boolean -- 1 if file was uploaded.
                   13015: 
1.243     albertel 13016: =back
                   13017: 
                   13018: =head2 Storing/Retreiving Data
                   13019: 
                   13020: =over 4
1.191     harris41 13021: 
                   13022: =item *
                   13023: 
1.243     albertel 13024: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   13025: for this url; hashref needs to be given and should be a \%hashname; the
                   13026: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 13027: be derived from the env
1.191     harris41 13028: 
                   13029: =item *
                   13030: 
1.243     albertel 13031: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   13032: uses critical subroutine
1.191     harris41 13033: 
                   13034: =item *
                   13035: 
1.243     albertel 13036: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13037: all args are optional
1.191     harris41 13038: 
                   13039: =item *
                   13040: 
1.717     albertel 13041: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13042: dumps the complete (or key matching regexp) namespace into a hash
                   13043: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13044: normally &store()ed into
                   13045: 
                   13046: $range should be either an integer '100' (give me the first 100
                   13047:                                            matching records)
                   13048:               or be  two integers sperated by a - with no spaces
                   13049:                  '30-50' (give me the 30th through the 50th matching
                   13050:                           records)
                   13051: 
                   13052: 
                   13053: =item *
                   13054: 
                   13055: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   13056: replaces a &store() version of data with a replacement set of data
                   13057: for a particular resource in a namespace passed in the $storehash hash 
                   13058: reference
                   13059: 
                   13060: =item *
                   13061: 
1.243     albertel 13062: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13063: works very similar to store/cstore, but all data is stored in a
                   13064: temporary location and can be reset using tmpreset, $storehash should
                   13065: be a hash reference, returns nothing on success
1.191     harris41 13066: 
                   13067: =item *
                   13068: 
1.243     albertel 13069: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13070: similar to restore, but all data is stored in a temporary location and
                   13071: can be reset using tmpreset. Returns a hash of values on success,
                   13072: error string otherwise.
1.191     harris41 13073: 
                   13074: =item *
                   13075: 
1.243     albertel 13076: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13077: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13078: 
                   13079: =item *
                   13080: 
1.243     albertel 13081: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13082: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13083: 
                   13084: =item *
                   13085: 
1.243     albertel 13086: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13087: namesp ($udom and $uname are optional)
1.191     harris41 13088: 
                   13089: =item *
                   13090: 
1.702     albertel 13091: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13092: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13093: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13094: 
1.702     albertel 13095: $range should be either an integer '100' (give me the first 100
                   13096:                                            matching records)
                   13097:               or be  two integers sperated by a - with no spaces
                   13098:                  '30-50' (give me the 30th through the 50th matching
                   13099:                           records)
1.449     matthew  13100: =item *
                   13101: 
                   13102: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13103: $store can be a scalar, an array reference, or if the amount to be 
                   13104: incremented is > 1, a hash reference.
                   13105: 
                   13106: ($udom and $uname are optional)
1.191     harris41 13107: 
                   13108: =item *
                   13109: 
1.243     albertel 13110: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13111: ($udom and $uname are optional)
1.191     harris41 13112: 
                   13113: =item *
                   13114: 
1.243     albertel 13115: cput($namespace,$storehash,$udom,$uname) : critical put
                   13116: ($udom and $uname are optional)
1.191     harris41 13117: 
                   13118: =item *
                   13119: 
1.748     albertel 13120: newput($namespace,$storehash,$udom,$uname) :
                   13121: 
                   13122: Attempts to store the items in the $storehash, but only if they don't
                   13123: currently exist, if this succeeds you can be certain that you have 
                   13124: successfully created a new key value pair in the $namespace db.
                   13125: 
                   13126: 
                   13127: Args:
                   13128:  $namespace: name of database to store values to
                   13129:  $storehash: hashref to store to the db
                   13130:  $udom: (optional) domain of user containing the db
                   13131:  $uname: (optional) name of user caontaining the db
                   13132: 
                   13133: Returns:
                   13134:  'ok' -> succeeded in storing all keys of $storehash
                   13135:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13136:                         least <key> already existed in the db (other
                   13137:                         requested keys may also already exist)
1.967     bisitz   13138:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13139:  'con_lost' -> unable to contact request server
                   13140:  'refused' -> action was not allowed by remote machine
                   13141: 
                   13142: 
                   13143: =item *
                   13144: 
1.243     albertel 13145: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13146: reference filled in from namesp (encrypts the return communication)
                   13147: ($udom and $uname are optional)
1.191     harris41 13148: 
                   13149: =item *
                   13150: 
1.243     albertel 13151: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13152: critical subroutine
                   13153: 
1.806     raeburn  13154: =item *
                   13155: 
1.860     raeburn  13156: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13157: array reference filled in from namespace found in domain level on either
                   13158: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13159: 
                   13160: =item *
                   13161: 
1.860     raeburn  13162: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13163: domain level either on specified domain server ($uhome) or primary domain 
                   13164: server ($udom and $uhome are optional)
1.806     raeburn  13165: 
1.943     raeburn  13166: =item * 
                   13167: 
                   13168: get_domain_defaults($target_domain) : returns hash with defaults for
                   13169: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   13170: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   13171: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   13172: Values are retrieved from cache (if current), or from domain's configuration.db
                   13173: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   13174: or lonTabs/domain.tab. 
                   13175: 
                   13176: %domdefaults = &get_auth_defaults($target_domain);
                   13177: 
1.243     albertel 13178: =back
                   13179: 
                   13180: =head2 Network Status Functions
                   13181: 
                   13182: =over 4
1.191     harris41 13183: 
                   13184: =item *
                   13185: 
1.1137    raeburn  13186: dirlist() : return directory list based on URI (first arg).
                   13187: 
                   13188: Inputs: 1 required, 5 optional.
                   13189: 
                   13190: =over
                   13191: 
                   13192: =item 
                   13193: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13194: 
                   13195: =item
                   13196: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13197: 
                   13198: =item
                   13199: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13200: 
                   13201: =item
                   13202: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13203: 
                   13204: =item
                   13205: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13206: 
                   13207: =item 
                   13208: $alternateRoot - path to prepend in place of path from $uri.
                   13209: 
                   13210: =back
                   13211: 
                   13212: Returns: Array of up to two items.
                   13213: 
                   13214: =over
                   13215: 
                   13216: a reference to an array of files/subdirectories
                   13217: 
                   13218: =over
                   13219: 
                   13220: Each element in the array of files/subdirectories is a & separated list of
                   13221: item name and the result of running stat on the item.  If dirlist was requested
                   13222: for a file instead of a directory, the item name will be ''. For a directory 
                   13223: listing, if the item is a metadata file, the element will end &N&M 
                   13224: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13225: default copyright set (1).  
                   13226: 
                   13227: =back
                   13228: 
                   13229: a scalar containing error condition (if encountered).
                   13230: 
                   13231: =over
                   13232: 
                   13233: =item 
                   13234: no_host (no homeserver identified for $username:$domain).
                   13235: 
                   13236: =item 
                   13237: no_such_host (server contacted for listing not identified as valid host).
                   13238: 
                   13239: =item 
                   13240: con_lost (connection to remote server failed).
                   13241: 
                   13242: =item 
                   13243: refused (invalid $username:$domain received on lond side).
                   13244: 
                   13245: =item 
                   13246: no_such_dir (directory at specified path on lond side does not exist). 
                   13247: 
                   13248: =item 
                   13249: empty (directory at specified path on lond side is empty).
                   13250: 
                   13251: =over
                   13252: 
                   13253: This is currently not encountered because the &ls3, &ls2, 
                   13254: &ls (_handler) routines on the lond side do not filter out
                   13255: . and .. from a directory listing. 
                   13256: 
                   13257: =back
                   13258: 
                   13259: =back
                   13260: 
                   13261: =back
1.191     harris41 13262: 
                   13263: =item *
                   13264: 
1.243     albertel 13265: spareserver() : find server with least workload from spare.tab
                   13266: 
1.986     foxr     13267: 
                   13268: =item *
                   13269: 
                   13270: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13271: if there is no corresponding loncapa host.
                   13272: 
1.243     albertel 13273: =back
                   13274: 
1.986     foxr     13275: 
1.243     albertel 13276: =head2 Apache Request
                   13277: 
                   13278: =over 4
1.191     harris41 13279: 
                   13280: =item *
                   13281: 
1.243     albertel 13282: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13283: localhost, posts hash
                   13284: 
                   13285: =back
                   13286: 
                   13287: =head2 Data to String to Data
                   13288: 
                   13289: =over 4
1.191     harris41 13290: 
                   13291: =item *
                   13292: 
1.243     albertel 13293: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13294: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13295: 
                   13296: =item *
                   13297: 
1.243     albertel 13298: hashref2str($hashref) : convert a hashref into a string complete with
                   13299: escaping and '=' and '&' separators, supports elements that are
                   13300: arrayrefs and hashrefs
1.191     harris41 13301: 
                   13302: =item *
                   13303: 
1.243     albertel 13304: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13305: with escaping and '&' separators, supports elements that are arrayrefs
                   13306: and hashrefs
1.191     harris41 13307: 
                   13308: =item *
                   13309: 
1.243     albertel 13310: str2hash($string) : convert string to hash using unescaping and
                   13311: splitting on '=' and '&', supports elements that are arrayrefs and
                   13312: hashrefs
1.191     harris41 13313: 
                   13314: =item *
                   13315: 
1.243     albertel 13316: str2array($string) : convert string to hash using unescaping and
                   13317: splitting on '&', supports elements that are arrayrefs and hashrefs
                   13318: 
                   13319: =back
                   13320: 
                   13321: =head2 Logging Routines
                   13322: 
                   13323: 
                   13324: These routines allow one to make log messages in the lonnet.log and
                   13325: lonnet.perm logfiles.
1.191     harris41 13326: 
1.1119    foxr     13327: =over 4
                   13328: 
1.191     harris41 13329: =item *
                   13330: 
1.243     albertel 13331: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 13332: 
                   13333: =item *
                   13334: 
1.243     albertel 13335: logthis() : append message to the normal lonnet.log file, it gets
                   13336: preiodically rolled over and deleted.
1.191     harris41 13337: 
                   13338: =item *
                   13339: 
1.243     albertel 13340: logperm() : append a permanent message to lonnet.perm.log, this log
                   13341: file never gets deleted by any automated portion of the system, only
                   13342: messages of critical importance should go in here.
                   13343: 
1.1119    foxr     13344: 
1.243     albertel 13345: =back
                   13346: 
                   13347: =head2 General File Helper Routines
                   13348: 
                   13349: =over 4
1.191     harris41 13350: 
                   13351: =item *
                   13352: 
1.481     raeburn  13353: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   13354: (a) files in /uploaded
                   13355:   (i) If a local copy of the file exists - 
                   13356:       compares modification date of local copy with last-modified date for 
                   13357:       definitive version stored on home server for course. If local copy is 
                   13358:       stale, requests a new version from the home server and stores it. 
                   13359:       If the original has been removed from the home server, then local copy 
                   13360:       is unlinked.
                   13361:   (ii) If local copy does not exist -
                   13362:       requests the file from the home server and stores it. 
                   13363:   
                   13364:   If $caller is 'uploadrep':  
                   13365:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   13366:     for request for files originally uploaded via DOCS. 
                   13367:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   13368:   
                   13369:   Otherwise:
                   13370:      This indicates a call from the content generation phase of the request.
                   13371:      -  returns the entire contents of the file or -1.
                   13372:      
                   13373: (b) files in /res
                   13374:    - returns the entire contents of a file or -1; 
                   13375:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 13376: 
1.712     albertel 13377: 
                   13378: =item *
                   13379: 
                   13380: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   13381:                   reference
                   13382: 
                   13383: returns either a stat() list of data about the file or an empty list
                   13384: if the file doesn't exist or couldn't find out about it (connection
                   13385: problems or user unknown)
                   13386: 
1.191     harris41 13387: =item *
                   13388: 
1.243     albertel 13389: filelocation($dir,$file) : returns file system location of a file
                   13390: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   13391: directory that relative $file lookups are to looked in ($dir of /a/dir
                   13392: and a file of ../bob will become /a/bob)
1.191     harris41 13393: 
                   13394: =item *
                   13395: 
                   13396: hreflocation($dir,$file) : returns file system location or a URL; same as
                   13397: filelocation except for hrefs
                   13398: 
                   13399: =item *
                   13400: 
                   13401: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   13402: 
1.243     albertel 13403: =back
                   13404: 
1.608     albertel 13405: =head2 Usererfile file routines (/uploaded*)
                   13406: 
                   13407: =over 4
                   13408: 
                   13409: =item *
                   13410: 
                   13411: userfileupload(): main rotine for putting a file in a user or course's
                   13412:                   filespace, arguments are,
                   13413: 
1.620     albertel 13414:  formname - required - this is the name of the element in $env where the
1.608     albertel 13415:            filename, and the contents of the file to create/modifed exist
1.620     albertel 13416:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   13417:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  13418:  context - if coursedoc, store the file in the course of the active role
                   13419:              of the current user; 
                   13420:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   13421:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 13422:  subdir - required - subdirectory to put the file in under ../userfiles/
                   13423:          if undefined, it will be placed in "unknown"
                   13424: 
                   13425:  (This routine calls clean_filename() to remove any dangerous
                   13426:  characters from the filename, and then calls finuserfileupload() to
                   13427:  complete the transaction)
                   13428: 
                   13429:  returns either the url of the uploaded file (/uploaded/....) if successful
                   13430:  and /adm/notfound.html if unsuccessful
                   13431: 
                   13432: =item *
                   13433: 
                   13434: clean_filename(): routine for cleaing a filename up for storage in
                   13435:                  userfile space, argument is:
                   13436: 
                   13437:  filename - proposed filename
                   13438: 
                   13439: returns: the new clean filename
                   13440: 
                   13441: =item *
                   13442: 
1.1090    raeburn  13443: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 13444: userspace, probably shouldn't be called directly
                   13445: 
                   13446:   docuname: username or courseid of destination for the file
                   13447:   docudom: domain of user/course of destination for the file
                   13448:   formname: same as for userfileupload()
1.1090    raeburn  13449:   fname: filename (including subdirectories) for the file
                   13450:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   13451:   allfiles: reference to hash used to store objects found by parser
                   13452:   codebase: reference to hash used for codebases of java objects found by parser
                   13453:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   13454:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   13455:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   13456:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   13457:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   13458:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  13459:   mimetype: reference to scalar to accommodate mime type determined
                   13460:             from File::MMagic if $parser = parse.
1.608     albertel 13461: 
                   13462:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  13463:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   13464:  was 'overwrite').
                   13465:  
1.608     albertel 13466: 
                   13467: =item *
                   13468: 
                   13469: renameuserfile(): renames an existing userfile to a new name
                   13470: 
                   13471:   Args:
                   13472:    docuname: username or courseid of destination for the file
                   13473:    docudom: domain of user/course of destination for the file
                   13474:    old: current file name (including any subdirs under userfiles)
                   13475:    new: desired file name (including any subdirs under userfiles)
                   13476: 
                   13477: =item *
                   13478: 
                   13479: mkdiruserfile(): creates a directory is a userfiles dir
                   13480: 
                   13481:   Args:
                   13482:    docuname: username or courseid of destination for the file
                   13483:    docudom: domain of user/course of destination for the file
                   13484:    dir: dir to create (including any subdirs under userfiles)
                   13485: 
                   13486: =item *
                   13487: 
                   13488: removeuserfile(): removes a file that exists in userfiles
                   13489: 
                   13490:   Args:
                   13491:    docuname: username or courseid of destination for the file
                   13492:    docudom: domain of user/course of destination for the file
                   13493:    fname: filname to delete (including any subdirs under userfiles)
                   13494: 
                   13495: =item *
                   13496: 
                   13497: removeuploadedurl(): convience function for removeuserfile()
                   13498: 
                   13499:   Args:
                   13500:    url:  a full /uploaded/... url to delete
                   13501: 
1.747     albertel 13502: =item * 
                   13503: 
                   13504: get_portfile_permissions():
                   13505:   Args:
                   13506:     domain: domain of user or course contain the portfolio files
                   13507:     user: name of user or num of course contain the portfolio files
                   13508:   Returns:
                   13509:     hashref of a dump of the proper file_permissions.db
                   13510:    
                   13511: 
                   13512: =item * 
                   13513: 
                   13514: get_access_controls():
                   13515: 
                   13516: Args:
                   13517:   current_permissions: the hash ref returned from get_portfile_permissions()
                   13518:   group: (optional) the group you want the files associated with
                   13519:   file: (optional) the file you want access info on
                   13520: 
                   13521: Returns:
1.749     raeburn  13522:     a hash (keys are file names) of hashes containing
                   13523:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   13524:         values are XML containing access control settings (see below) 
1.747     albertel 13525: 
                   13526: Internal notes:
                   13527: 
1.749     raeburn  13528:  access controls are stored in file_permissions.db as key=value pairs.
                   13529:     key -> path to file/file_name\0uniqueID:scope_end_start
                   13530:         where scope -> public,guest,course,group,domains or users.
                   13531:               end -> UNIX time for end of access (0 -> no end date)
                   13532:               start -> UNIX time for start of access
                   13533: 
                   13534:     value -> XML description of access control
                   13535:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   13536:             <start></start>
                   13537:             <end></end>
                   13538: 
                   13539:             <password></password>  for scope type = guest
                   13540: 
                   13541:             <domain></domain>     for scope type = course or group
                   13542:             <number></number>
                   13543:             <roles id="">
                   13544:              <role></role>
                   13545:              <access></access>
                   13546:              <section></section>
                   13547:              <group></group>
                   13548:             </roles>
                   13549: 
                   13550:             <dom></dom>         for scope type = domains
                   13551: 
                   13552:             <users>             for scope type = users
                   13553:              <user>
                   13554:               <uname></uname>
                   13555:               <udom></udom>
                   13556:              </user>
                   13557:             </users>
                   13558:            </scope> 
                   13559:               
                   13560:  Access data is also aggregated for each file in an additional key=value pair:
                   13561:  key -> path to file/file_name\0accesscontrol 
                   13562:  value -> reference to hash
                   13563:           hash contains key = value pairs
                   13564:           where key = uniqueID:scope_end_start
                   13565:                 value = UNIX time record was last updated
                   13566: 
                   13567:           Used to improve speed of look-ups of access controls for each file.  
                   13568:  
                   13569:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   13570: 
1.1172.2.13  raeburn  13571: =item *
                   13572: 
1.749     raeburn  13573: modify_access_controls():
                   13574: 
                   13575: Modifies access controls for a portfolio file
                   13576: Args
                   13577: 1. file name
                   13578: 2. reference to hash of required changes,
                   13579: 3. domain
                   13580: 4. username
                   13581:   where domain,username are the domain of the portfolio owner 
                   13582:   (either a user or a course) 
                   13583: 
                   13584: Returns:
                   13585: 1. result of additions or updates ('ok' or 'error', with error message). 
                   13586: 2. result of deletions ('ok' or 'error', with error message).
                   13587: 3. reference to hash of any new or updated access controls.
                   13588: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   13589:    key = integer (inbound ID)
1.1172.2.13  raeburn  13590:    value = uniqueID
                   13591: 
                   13592: =item *
                   13593: 
                   13594: get_timebased_id():
                   13595: 
                   13596: Attempts to get a unique timestamp-based suffix for use with items added to a
                   13597: course via the Course Editor (e.g., folders, composite pages,
                   13598: group bulletin boards).
                   13599: 
                   13600: Args: (first three required; six others optional)
                   13601: 
                   13602: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   13603:    docssequence, or name of group
                   13604: 
                   13605: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   13606:    e.g., num, boardids
                   13607: 
                   13608: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   13609:    file will be named nohist_namespace.db
                   13610: 
                   13611: 4. cdom: domain of course; default is current course domain from %env
                   13612: 
                   13613: 5. cnum: course number; default is current course number from %env
                   13614: 
                   13615: 6. idtype: set to concat if an additional digit is to be appended to the
                   13616:    unix timestamp to form the suffix, if the plain timestamp is already
                   13617:    in use.  Default is to not do this, but simply increment the unix
                   13618:    timestamp by 1 until a unique key is obtained.
                   13619: 
                   13620: 7. who: holder of locking key; defaults to user:domain for user.
                   13621: 
                   13622: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   13623:    retrying); default is 3.
                   13624: 
                   13625: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   13626: 
                   13627: Returns:
                   13628: 
                   13629: 1. suffix obtained (numeric)
                   13630: 
                   13631: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   13632: 
                   13633: 3. error: contains (localized) error message if an error occurred.
                   13634: 
1.747     albertel 13635: 
1.608     albertel 13636: =back
                   13637: 
1.243     albertel 13638: =head2 HTTP Helper Routines
                   13639: 
                   13640: =over 4
                   13641: 
1.191     harris41 13642: =item *
                   13643: 
                   13644: escape() : unpack non-word characters into CGI-compatible hex codes
                   13645: 
                   13646: =item *
                   13647: 
                   13648: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   13649: 
1.243     albertel 13650: =back
                   13651: 
                   13652: =head1 PRIVATE SUBROUTINES
                   13653: 
                   13654: =head2 Underlying communication routines (Shouldn't call)
                   13655: 
                   13656: =over 4
                   13657: 
                   13658: =item *
                   13659: 
                   13660: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   13661: 
                   13662: =item *
                   13663: 
                   13664: reply() : uses subreply to send a message to remote machine, logs all failures
                   13665: 
                   13666: =item *
                   13667: 
                   13668: critical() : passes a critical message to another server; if cannot
                   13669: get through then place message in connection buffer directory and
                   13670: returns con_delayed, if incapable of saving message, returns
                   13671: con_failed
                   13672: 
                   13673: =item *
                   13674: 
                   13675: reconlonc() : tries to reconnect lonc client processes.
                   13676: 
                   13677: =back
                   13678: 
                   13679: =head2 Resource Access Logging
                   13680: 
                   13681: =over 4
                   13682: 
                   13683: =item *
                   13684: 
                   13685: flushcourselogs() : flush (save) buffer logs and access logs
                   13686: 
                   13687: =item *
                   13688: 
                   13689: courselog($what) : save message for course in hash
                   13690: 
                   13691: =item *
                   13692: 
                   13693: courseacclog($what) : save message for course using &courselog().  Perform
                   13694: special processing for specific resource types (problems, exams, quizzes, etc).
                   13695: 
1.191     harris41 13696: =item *
                   13697: 
                   13698: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   13699: as a PerlChildExitHandler
1.243     albertel 13700: 
                   13701: =back
                   13702: 
                   13703: =head2 Other
                   13704: 
                   13705: =over 4
                   13706: 
                   13707: =item *
                   13708: 
                   13709: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 13710: 
                   13711: =back
                   13712: 
                   13713: =cut
1.877     foxr     13714: 

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