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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.75! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.74 2016/08/06 01:18:07 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.36  raeburn    78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
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 {
1.1172.2.35  raeburn   355:     my ($lonhost,$cachekeys) = @_;
                    356:     my $items;
                    357:     return unless (ref($cachekeys) eq 'ARRAY');
                    358:     my $cachestr = join('&',@{$cachekeys});
                    359:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   360: }
                    361: 
1.1       albertel  362: # -------------------------------------------------- Non-critical communication
                    363: sub subreply {
                    364:     my ($cmd,$server)=@_;
1.838     albertel  365:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      366:     #
                    367:     #  With loncnew process trimming, there's a timing hole between lonc server
                    368:     #  process exit and the master server picking up the listen on the AF_UNIX
                    369:     #  socket.  In that time interval, a lock file will exist:
                    370: 
                    371:     my $lockfile=$peerfile.".lock";
                    372:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    373: 	sleep(1);
                    374:     }
                    375:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      376:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      377:     #
1.550     foxr      378:     #   We'll give the connection a few tries before abandoning it.  If
                    379:     #   connection is not possible, we'll con_lost back to the client.
                    380:     #   
                    381:     my $client;
                    382:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    383: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    384: 				      Type    => SOCK_STREAM,
                    385: 				      Timeout => 10);
1.869     albertel  386: 	if ($client) {
1.550     foxr      387: 	    last;		# Connected!
1.850     albertel  388: 	} else {
1.853     albertel  389: 	    &create_connection(&hostname($server),$server);
1.550     foxr      390: 	}
1.850     albertel  391:         sleep(1);		# Try again later if failed connection.
1.550     foxr      392:     }
                    393:     my $answer;
                    394:     if ($client) {
1.704     albertel  395: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      396: 	$answer=<$client>;
                    397: 	if (!$answer) { $answer="con_lost"; }
                    398: 	chomp($answer);
                    399:     } else {
                    400: 	$answer = 'con_lost';	# Failed connection.
                    401:     }
1.1       albertel  402:     return $answer;
                    403: }
                    404: 
                    405: sub reply {
                    406:     my ($cmd,$server)=@_;
1.838     albertel  407:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  408:     my $answer=subreply($cmd,$server);
1.65      www       409:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  410:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       411:                 " $cmd to $server returned $answer</font>");
                    412:     }
1.1       albertel  413:     return $answer;
                    414: }
                    415: 
                    416: # ----------------------------------------------------------- Send USR1 to lonc
                    417: 
                    418: sub reconlonc {
1.891     albertel  419:     my ($lonid) = @_;
                    420:     if ($lonid) {
1.1172.2.72  raeburn   421:         my $hostname = &hostname($lonid);
1.891     albertel  422: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    423: 	if ($hostname && -e $peerfile) {
                    424: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    425: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    426: 					     Type    => SOCK_STREAM,
                    427: 					     Timeout => 10);
                    428: 	    if ($client) {
                    429: 		print $client ("reset_retries\n");
                    430: 		my $answer=<$client>;
                    431: 		#reset just this one.
                    432: 	    }
                    433: 	}
                    434: 	return;
                    435:     }
                    436: 
1.836     www       437:     &logthis("Trying to reconnect lonc");
1.1       albertel  438:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  439:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  440: 	my $loncpid=<$fh>;
                    441:         chomp($loncpid);
                    442:         if (kill 0 => $loncpid) {
                    443: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    444:             kill USR1 => $loncpid;
                    445:             sleep 1;
1.836     www       446:          } else {
1.12      www       447: 	    &logthis(
1.672     albertel  448:                "<font color=\"blue\">WARNING:".
1.12      www       449:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  450:         }
                    451:     } else {
1.836     www       452: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  453:     }
                    454: }
                    455: 
                    456: # ------------------------------------------------------ Critical communication
1.12      www       457: 
1.1       albertel  458: sub critical {
                    459:     my ($cmd,$server)=@_;
1.838     albertel  460:     unless (&hostname($server)) {
1.672     albertel  461:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       462:                " Critical message to unknown server ($server)</font>");
                    463:         return 'no_such_host';
                    464:     }
1.1       albertel  465:     my $answer=reply($cmd,$server);
                    466:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   467: 	&reconlonc($server);
1.589     albertel  468: 	my $answer=reply($cmd,$server);
1.1       albertel  469:         if ($answer eq 'con_lost') {
                    470:             my $now=time;
                    471:             my $middlename=$cmd;
1.5       www       472:             $middlename=substr($middlename,0,16);
1.1       albertel  473:             $middlename=~s/\W//g;
                    474:             my $dfilename=
1.305     www       475:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    476:             $dumpcount++;
1.1       albertel  477:             {
1.448     albertel  478: 		my $dfh;
                    479: 		if (open($dfh,">$dfilename")) {
                    480: 		    print $dfh "$cmd\n"; 
                    481: 		    close($dfh);
                    482: 		}
1.1       albertel  483:             }
                    484:             sleep 2;
                    485:             my $wcmd='';
                    486:             {
1.448     albertel  487: 		my $dfh;
                    488: 		if (open($dfh,"<$dfilename")) {
                    489: 		    $wcmd=<$dfh>; 
                    490: 		    close($dfh);
                    491: 		}
1.1       albertel  492:             }
                    493:             chomp($wcmd);
1.7       www       494:             if ($wcmd eq $cmd) {
1.672     albertel  495: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       496:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  497:                 &logperm("D:$server:$cmd");
                    498: 	        return 'con_delayed';
                    499:             } else {
1.672     albertel  500:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       501:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  502:                 &logperm("F:$server:$cmd");
                    503:                 return 'con_failed';
                    504:             }
                    505:         }
                    506:     }
                    507:     return $answer;
1.405     albertel  508: }
                    509: 
1.755     albertel  510: # ------------------------------------------- check if return value is an error
                    511: 
                    512: sub error {
                    513:     my ($result) = @_;
1.756     albertel  514:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  515: 	if ($2 == 2) { return undef; }
                    516: 	return $1;
                    517:     }
                    518:     return undef;
                    519: }
                    520: 
1.783     albertel  521: sub convert_and_load_session_env {
                    522:     my ($lonidsdir,$handle)=@_;
                    523:     my @profile;
                    524:     {
1.917     albertel  525: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    526: 	if (!$opened) {
1.915     albertel  527: 	    return 0;
                    528: 	}
1.783     albertel  529: 	flock($idf,LOCK_SH);
                    530: 	@profile=<$idf>;
                    531: 	close($idf);
                    532:     }
                    533:     my %temp_env;
                    534:     foreach my $line (@profile) {
1.786     albertel  535: 	if ($line !~ m/=/) {
                    536: 	    return 0;
                    537: 	}
1.783     albertel  538: 	chomp($line);
                    539: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    540: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    541:     }
                    542:     unlink("$lonidsdir/$handle.id");
                    543:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    544: 	    0640)) {
                    545: 	%disk_env = %temp_env;
                    546: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    547: 	untie(%disk_env);
                    548:     }
1.786     albertel  549:     return 1;
1.783     albertel  550: }
                    551: 
1.374     www       552: # ------------------------------------------- Transfer profile into environment
1.780     albertel  553: my $env_loaded;
                    554: sub transfer_profile_to_env {
1.788     albertel  555:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    556:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       557: 
1.720     albertel  558:     if (!defined($lonidsdir)) {
                    559: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    560:     }
                    561:     if (!defined($handle)) {
                    562:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    563:     }
                    564: 
1.786     albertel  565:     my $convert;
                    566:     {
1.917     albertel  567:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    568: 	if (!$opened) {
1.915     albertel  569: 	    return;
                    570: 	}
1.786     albertel  571: 	flock($idf,LOCK_SH);
                    572: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    573: 		&GDBM_READER(),0640)) {
                    574: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    575: 	    untie(%disk_env);
                    576: 	} else {
                    577: 	    $convert = 1;
                    578: 	}
                    579:     }
                    580:     if ($convert) {
                    581: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    582: 	    &logthis("Failed to load session, or convert session.");
                    583: 	}
1.374     www       584:     }
1.783     albertel  585: 
1.786     albertel  586:     my %remove;
1.783     albertel  587:     while ( my $envname = each(%env) ) {
1.433     matthew   588:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    589:             if ($time < time-300) {
1.783     albertel  590:                 $remove{$key}++;
1.433     matthew   591:             }
                    592:         }
                    593:     }
1.783     albertel  594: 
1.619     albertel  595:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  596:     $env_loaded=1;
1.783     albertel  597:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   598:         &delenv($expired_key);
1.374     www       599:     }
1.1       albertel  600: }
                    601: 
1.916     albertel  602: # ---------------------------------------------------- Check for valid session 
                    603: sub check_for_valid_session {
1.1172.2.36  raeburn   604:     my ($r,$name,$userhashref) = @_;
1.916     albertel  605:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   606:     if ($name eq '') {
                    607:         $name = 'lonID';
                    608:     }
                    609:     my $lonid=$cookies{$name};
1.916     albertel  610:     return undef if (!$lonid);
                    611: 
                    612:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   613:     my $lonidsdir;
                    614:     if ($name eq 'lonDAV') {
                    615:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    616:     } else {
                    617:         $lonidsdir=$r->dir_config('lonIDsDir');
                    618:     }
1.916     albertel  619:     return undef if (!-e "$lonidsdir/$handle.id");
                    620: 
1.917     albertel  621:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    622:     return undef if (!$opened);
1.916     albertel  623: 
                    624:     flock($idf,LOCK_SH);
                    625:     my %disk_env;
                    626:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    627: 	    &GDBM_READER(),0640)) {
                    628: 	return undef;	
                    629:     }
                    630: 
                    631:     if (!defined($disk_env{'user.name'})
                    632: 	|| !defined($disk_env{'user.domain'})) {
                    633: 	return undef;
                    634:     }
1.1172.2.18  raeburn   635: 
1.1172.2.36  raeburn   636:     if (ref($userhashref) eq 'HASH') {
                    637:         $userhashref->{'name'} = $disk_env{'user.name'};
                    638:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   639:     }
                    640: 
1.916     albertel  641:     return $handle;
                    642: }
                    643: 
1.830     albertel  644: sub timed_flock {
                    645:     my ($file,$lock_type) = @_;
                    646:     my $failed=0;
                    647:     eval {
                    648: 	local $SIG{__DIE__}='DEFAULT';
                    649: 	local $SIG{ALRM}=sub {
                    650: 	    $failed=1;
                    651: 	    die("failed lock");
                    652: 	};
                    653: 	alarm(13);
                    654: 	flock($file,$lock_type);
                    655: 	alarm(0);
                    656:     };
                    657:     if ($failed) {
                    658: 	return undef;
                    659:     } else {
                    660: 	return 1;
                    661:     }
                    662: }
                    663: 
1.5       www       664: # ---------------------------------------------------------- Append Environment
                    665: 
                    666: sub appenv {
1.949     raeburn   667:     my ($newenv,$roles) = @_;
                    668:     if (ref($newenv) eq 'HASH') {
                    669:         foreach my $key (keys(%{$newenv})) {
                    670:             my $refused = 0;
                    671: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    672:                 $refused = 1;
                    673:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   674:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   675:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    676:                         $refused = 0;
                    677:                     }
                    678:                 }
                    679:             }
                    680:             if ($refused) {
                    681:                 &logthis("<font color=\"blue\">WARNING: ".
                    682:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    683:                          .'</font>');
                    684: 	        delete($newenv->{$key});
                    685:             } else {
                    686:                 $env{$key}=$newenv->{$key};
                    687:             }
                    688:         }
                    689:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    690:         if ($opened
                    691: 	    && &timed_flock($env_file,LOCK_EX)
                    692: 	    &&
                    693: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    694: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    695: 	    while (my ($key,$value) = each(%{$newenv})) {
                    696: 	        $disk_env{$key} = $value;
                    697: 	    }
                    698: 	    untie(%disk_env);
1.35      www       699:         }
1.191     harris41  700:     }
1.56      www       701:     return 'ok';
                    702: }
                    703: # ----------------------------------------------------- Delete from Environment
                    704: 
                    705: sub delenv {
1.1104    raeburn   706:     my ($delthis,$regexp,$roles) = @_;
                    707:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    708:         my $refused = 1;
                    709:         if (ref($roles) eq 'ARRAY') {
                    710:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    711:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    712:                 $refused = 0;
                    713:             }
                    714:         }
                    715:         if ($refused) {
                    716:             &logthis("<font color=\"blue\">WARNING: ".
                    717:                      "Attempt to delete from environment ".$delthis);
                    718:             return 'error';
                    719:         }
1.56      www       720:     }
1.917     albertel  721:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    722:     if ($opened
1.915     albertel  723: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  724: 	&&
                    725: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    726: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  727: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   728: 	    if ($regexp) {
                    729:                 if ($key=~/^$delthis/) {
                    730:                     delete($env{$key});
                    731:                     delete($disk_env{$key});
                    732:                 } 
                    733:             } else {
                    734:                 if ($key=~/^\Q$delthis\E/) {
                    735: 		    delete($env{$key});
                    736: 		    delete($disk_env{$key});
                    737: 	        }
                    738:             }
1.448     albertel  739: 	}
1.783     albertel  740: 	untie(%disk_env);
1.5       www       741:     }
                    742:     return 'ok';
1.369     albertel  743: }
                    744: 
1.790     albertel  745: sub get_env_multiple {
                    746:     my ($name) = @_;
                    747:     my @values;
                    748:     if (defined($env{$name})) {
                    749:         # exists is it an array
                    750:         if (ref($env{$name})) {
                    751:             @values=@{ $env{$name} };
                    752:         } else {
                    753:             $values[0]=$env{$name};
                    754:         }
                    755:     }
                    756:     return(@values);
                    757: }
                    758: 
1.958     www       759: # ------------------------------------------------------------------- Locking
                    760: 
                    761: sub set_lock {
                    762:     my ($text)=@_;
                    763:     $locknum++;
                    764:     my $id=$$.'-'.$locknum;
                    765:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    766:              'session.lock.'.$id => $text});
                    767:     return $id;
                    768: }
                    769: 
                    770: sub get_locks {
                    771:     my $num=0;
                    772:     my %texts=();
                    773:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    774:        if ($lock=~/\w/) {
                    775:           $num++;
                    776:           $texts{$lock}=$env{'session.lock.'.$lock};
                    777:        }
                    778:    }
                    779:    return ($num,%texts);
                    780: }
                    781: 
                    782: sub remove_lock {
                    783:     my ($id)=@_;
                    784:     my $newlocks='';
                    785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    786:        if (($lock=~/\w/) && ($lock ne $id)) {
                    787:           $newlocks.=','.$lock;
                    788:        }
                    789:     }
                    790:     &appenv({'session.locks' => $newlocks});
                    791:     &delenv('session.lock.'.$id);
                    792: }
                    793: 
                    794: sub remove_all_locks {
                    795:     my $activelocks=$env{'session.locks'};
                    796:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    797:        if ($lock=~/\w/) {
                    798:           &remove_lock($lock);
                    799:        }
                    800:     }
                    801: }
                    802: 
                    803: 
1.369     albertel  804: # ------------------------------------------ Find out current server userload
                    805: sub userload {
                    806:     my $numusers=0;
                    807:     {
                    808: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    809: 	my $filename;
                    810: 	my $curtime=time;
                    811: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  812: 	    next if ($filename eq '.' || $filename eq '..');
                    813: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  814: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  815: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  816: 	}
                    817: 	closedir(LONIDS);
                    818:     }
                    819:     my $userloadpercent=0;
                    820:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    821:     if ($maxuserload) {
1.371     albertel  822: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  823:     }
1.372     albertel  824:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  825:     return $userloadpercent;
1.283     www       826: }
                    827: 
1.1       albertel  828: # ------------------------------ Find server with least workload from spare.tab
1.11      www       829: 
1.1       albertel  830: sub spareserver {
1.1083    raeburn   831:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  832:     my $spare_server;
1.370     albertel  833:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  834:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    835:                                                      :  $userloadpercent;
1.1083    raeburn   836:     my ($uint_dom,$remotesessions);
                    837:     if (($udom ne '') && (&domain($udom) ne '')) {
                    838:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    839:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    840:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    841:         $remotesessions = $udomdefaults{'remotesessions'};
                    842:     }
1.1123    raeburn   843:     my $spareshash = &this_host_spares($udom);
                    844:     if (ref($spareshash) eq 'HASH') {
                    845:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    846:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   847:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    848:                                              $try_server));
1.1123    raeburn   849: 	        ($spare_server, $lowest_load) =
                    850: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    851:             }
1.1083    raeburn   852:         }
1.784     albertel  853: 
1.1123    raeburn   854:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    855: 
                    856:         if (!$found_server) {
                    857:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    858: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   859:                     next unless (&spare_can_host($udom,$uint_dom,
                    860:                                                  $remotesessions,$try_server));
1.1123    raeburn   861: 	            ($spare_server, $lowest_load) =
                    862: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    863:                 }
                    864: 	    }
                    865:         }
1.784     albertel  866:     }
                    867: 
                    868:     if (!$want_server_name) {
1.968     raeburn   869:         my $protocol = 'http';
                    870:         if ($protocol{$spare_server} eq 'https') {
                    871:             $protocol = $protocol{$spare_server};
                    872:         }
1.1001    raeburn   873:         if (defined($spare_server)) {
                    874:             my $hostname = &hostname($spare_server);
1.1083    raeburn   875:             if (defined($hostname)) {
1.1001    raeburn   876: 	        $spare_server = $protocol.'://'.$hostname;
                    877:             }
                    878:         }
1.784     albertel  879:     }
                    880:     return $spare_server;
                    881: }
                    882: 
                    883: sub compare_server_load {
1.1172.2.41  raeburn   884:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    885: 
                    886:     if ($required) {
                    887:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    888:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    889:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    890:         if (($major eq '' && $minor eq '') ||
                    891:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    892:             return ($spare_server,$lowest_load);
                    893:         }
                    894:     }
1.784     albertel  895: 
                    896:     my $loadans     = &reply('load',    $try_server);
                    897:     my $userloadans = &reply('userload',$try_server);
                    898: 
                    899:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   900: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  901:     }
                    902: 
                    903:     my $load;
                    904:     if ($loadans =~ /\d/) {
                    905: 	if ($userloadans =~ /\d/) {
                    906: 	    #both are numbers, pick the bigger one
                    907: 	    $load = ($loadans > $userloadans) ? $loadans 
                    908: 		                              : $userloadans;
1.411     albertel  909: 	} else {
1.784     albertel  910: 	    $load = $loadans;
1.411     albertel  911: 	}
1.784     albertel  912:     } else {
                    913: 	$load = $userloadans;
                    914:     }
                    915: 
                    916:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    917: 	$spare_server = $try_server;
                    918: 	$lowest_load  = $load;
1.370     albertel  919:     }
1.784     albertel  920:     return ($spare_server,$lowest_load);
1.202     matthew   921: }
1.914     albertel  922: 
                    923: # --------------------------- ask offload servers if user already has a session
                    924: sub find_existing_session {
                    925:     my ($udom,$uname) = @_;
1.1123    raeburn   926:     my $spareshash = &this_host_spares($udom);
                    927:     if (ref($spareshash) eq 'HASH') {
                    928:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    929:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    930:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    931:             }
                    932:         }
                    933:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    934:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    936:             }
                    937:         }
1.914     albertel  938:     }
                    939:     return;
                    940: }
                    941: 
                    942: # -------------------------------- ask if server already has a session for user
                    943: sub has_user_session {
                    944:     my ($lonid,$udom,$uname) = @_;
                    945:     my $result = &reply(join(':','userhassession',
                    946: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    947:     return 1 if ($result eq 'ok');
                    948: 
                    949:     return 0;
                    950: }
                    951: 
1.1076    raeburn   952: # --------- determine least loaded server in a user's domain which allows login
                    953: 
                    954: sub choose_server {
1.1172.2.47  raeburn   955:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   956:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   957:     my %servers = &get_servers($udom);
1.1076    raeburn   958:     my $lowest_load = 30000;
1.1172.2.47  raeburn   959:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    960:     if ($skiploadbal) {
                    961:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    962:         unless (defined($cached)) {
                    963:             my $cachetime = 60*60*24;
                    964:             my %domconfig =
                    965:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    966:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    967:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    968:                                            $cachetime);
                    969:             }
                    970:         }
                    971:     }
1.1076    raeburn   972:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   973:         my $loginvia;
1.1172.2.47  raeburn   974:         if ($skiploadbal) {
                    975:             if (ref($balancers) eq 'HASH') {
                    976:                 next if (exists($balancers->{$lonhost}));
                    977:             }
                    978:         }
1.1115    raeburn   979:         if ($checkloginvia) {
                    980:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   981:             if ($loginvia) {
                    982:                 my ($server,$path) = split(/:/,$loginvia);
                    983:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   984:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   985:                 if ($login_host eq $server) {
                    986:                     $portal_path = $path;
1.1151    raeburn   987:                     $isredirect = 1;
1.1116    raeburn   988:                 }
                    989:             } else {
                    990:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn   991:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn   992:                 if ($login_host eq $lonhost) {
                    993:                     $portal_path = '';
1.1151    raeburn   994:                     $isredirect = ''; 
1.1116    raeburn   995:                 }
                    996:             }
                    997:         } else {
1.1076    raeburn   998:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn   999:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1000:         }
                   1001:     }
                   1002:     if ($login_host ne '') {
1.1116    raeburn  1003:         $hostname = &hostname($login_host);
1.1076    raeburn  1004:     }
1.1151    raeburn  1005:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn  1006: }
                   1007: 
1.202     matthew  1008: # --------------------------------------------- Try to change a user's password
                   1009: 
                   1010: sub changepass {
1.799     raeburn  1011:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1012:     $currentpass = &escape($currentpass);
                   1013:     $newpass     = &escape($newpass);
1.1030    raeburn  1014:     my $lonhost = $perlvar{'lonHostID'};
                   1015:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1016: 		       $server);
                   1017:     if (! $answer) {
                   1018: 	&logthis("No reply on password change request to $server ".
                   1019: 		 "by $uname in domain $udom.");
                   1020:     } elsif ($answer =~ "^ok") {
                   1021:         &logthis("$uname in $udom successfully changed their password ".
                   1022: 		 "on $server.");
                   1023:     } elsif ($answer =~ "^pwchange_failure") {
                   1024: 	&logthis("$uname in $udom was unable to change their password ".
                   1025: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1026: 		 "or pwchange");
                   1027:     } elsif ($answer =~ "^non_authorized") {
                   1028:         &logthis("$uname in $udom did not get their password correct when ".
                   1029: 		 "attempting to change it on $server.");
                   1030:     } elsif ($answer =~ "^auth_mode_error") {
                   1031:         &logthis("$uname in $udom attempted to change their password despite ".
                   1032: 		 "not being locally or internally authenticated on $server.");
                   1033:     } elsif ($answer =~ "^unknown_user") {
                   1034:         &logthis("$uname in $udom attempted to change their password ".
                   1035: 		 "on $server but were unable to because $server is not ".
                   1036: 		 "their home server.");
                   1037:     } elsif ($answer =~ "^refused") {
                   1038: 	&logthis("$server refused to change $uname in $udom password because ".
                   1039: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1040:     } elsif ($answer =~ "invalid_client") {
                   1041:         &logthis("$server refused to change $uname in $udom password because ".
                   1042:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1043:     }
                   1044:     return $answer;
1.1       albertel 1045: }
                   1046: 
1.169     harris41 1047: # ----------------------- Try to determine user's current authentication scheme
                   1048: 
                   1049: sub queryauthenticate {
                   1050:     my ($uname,$udom)=@_;
1.456     albertel 1051:     my $uhome=&homeserver($uname,$udom);
                   1052:     if (!$uhome) {
                   1053: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1054: 	return 'no_host';
                   1055:     }
                   1056:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1057:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1058: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1059:     }
1.456     albertel 1060:     return $answer;
1.169     harris41 1061: }
                   1062: 
1.1       albertel 1063: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1064: 
1.1       albertel 1065: sub authenticate {
1.1073    raeburn  1066:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1067:     $upass=&escape($upass);
                   1068:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1069:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1070:     my $newhome;
1.836     www      1071:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1072: # Maybe the machine was offline and only re-appeared again recently?
                   1073:         &reconlonc();
                   1074: # One more
1.952     raeburn  1075: 	$uhome=&homeserver($uname,$udom,1);
                   1076:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1077:             if (defined(&domain($udom,'primary'))) {
                   1078:                 $newhome=&domain($udom,'primary');
                   1079:             }
                   1080:             if ($newhome ne '') {
                   1081:                 $uhome = $newhome;
                   1082:             }
                   1083:         }
1.836     www      1084: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1085: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1086: 	    return 'no_host';
                   1087:         }
1.1       albertel 1088:     }
1.1073    raeburn  1089:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1090:     if ($answer eq 'authorized') {
1.952     raeburn  1091:         if ($newhome) {
                   1092:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1093:             return 'no_account_on_host'; 
                   1094:         } else {
                   1095:             &logthis("User $uname at $udom authorized by $uhome");
                   1096:             return $uhome;
                   1097:         }
1.471     albertel 1098:     }
                   1099:     if ($answer eq 'non_authorized') {
                   1100: 	&logthis("User $uname at $udom rejected by $uhome");
                   1101: 	return 'no_host'; 
1.9       www      1102:     }
1.471     albertel 1103:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1104:     return 'no_host';
                   1105: }
                   1106: 
1.1073    raeburn  1107: sub can_host_session {
1.1074    raeburn  1108:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1109:     my $canhost = 1;
1.1074    raeburn  1110:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1111:     if (ref($remotesessions) eq 'HASH') {
                   1112:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1113:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1114:                 $canhost = 0;
                   1115:             } else {
                   1116:                 $canhost = 1;
                   1117:             }
                   1118:         }
                   1119:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1120:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1121:                 $canhost = 1;
                   1122:             } else {
                   1123:                 $canhost = 0;
                   1124:             }
                   1125:         }
                   1126:         if ($canhost) {
                   1127:             if ($remotesessions->{'version'} ne '') {
                   1128:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1129:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1130:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1131:                         my $major = $1;
                   1132:                         my $minor = $2;
                   1133:                         if (($major < $reqmajor ) ||
                   1134:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1135:                             $canhost = 0;
                   1136:                         }
                   1137:                     } else {
                   1138:                         $canhost = 0;
                   1139:                     }
                   1140:                 }
                   1141:             }
                   1142:         }
                   1143:     }
                   1144:     if ($canhost) {
                   1145:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1146:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1147:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1148:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1149:                 if (($uint_dom ne '') && 
                   1150:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1151:                     $canhost = 0;
                   1152:                 } else {
                   1153:                     $canhost = 1;
                   1154:                 }
                   1155:             }
                   1156:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1157:                 if (($uint_dom ne '') && 
                   1158:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1159:                     $canhost = 1;
                   1160:                 } else {
                   1161:                     $canhost = 0;
                   1162:                 }
                   1163:             }
                   1164:         }
                   1165:     }
                   1166:     return $canhost;
                   1167: }
                   1168: 
1.1083    raeburn  1169: sub spare_can_host {
                   1170:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1171:     my $canhost=1;
1.1172.2.62  raeburn  1172:     my $try_server_hostname = &hostname($try_server);
                   1173:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1174:     my $serverhomedom = &host_domain($serverhomeID);
                   1175:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1176:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1177:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1178:             $canhost = 0;
                   1179:         }
                   1180:     }
                   1181:     if (($canhost) && ($uint_dom)) {
                   1182:         my @intdoms;
                   1183:         my $internet_names = &get_internet_names($try_server);
                   1184:         if (ref($internet_names) eq 'ARRAY') {
                   1185:             @intdoms = @{$internet_names};
                   1186:         }
                   1187:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1188:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1189:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1190:                                          $remotesessions,
                   1191:                                          $defdomdefaults{'hostedsessions'});
                   1192:         }
1.1083    raeburn  1193:     }
                   1194:     return $canhost;
                   1195: }
                   1196: 
1.1123    raeburn  1197: sub this_host_spares {
                   1198:     my ($dom) = @_;
1.1126    raeburn  1199:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1200:     my @hosts = &current_machine_ids();
                   1201:     foreach my $lonhost (@hosts) {
                   1202:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1203:             $dom_in_use = $dom;
                   1204:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1205:             last;
                   1206:         }
                   1207:     }
1.1126    raeburn  1208:     if ($dom_in_use ne '') {
                   1209:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1210:     }
                   1211:     if (ref($result) ne 'HASH') {
                   1212:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1213:         $dom_in_use = &host_domain($lonhost_in_use);
                   1214:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1215:         if (ref($result) ne 'HASH') {
                   1216:             $result = \%spareid;
                   1217:         }
                   1218:     }
                   1219:     return $result;
                   1220: }
                   1221: 
                   1222: sub spares_for_offload  {
                   1223:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1224:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1225:     if (defined($cached)) {
                   1226:         return $result;
                   1227:     } else {
1.1126    raeburn  1228:         my $cachetime = 60*60*24;
                   1229:         my %domconfig =
                   1230:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1231:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1232:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1233:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1234:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1235:                 }
                   1236:             }
                   1237:         }
                   1238:     }
1.1126    raeburn  1239:     return;
1.1123    raeburn  1240: }
                   1241: 
1.1129    raeburn  1242: sub get_lonbalancer_config {
                   1243:     my ($servers) = @_;
                   1244:     my ($currbalancer,$currtargets);
                   1245:     if (ref($servers) eq 'HASH') {
                   1246:         foreach my $server (keys(%{$servers})) {
                   1247:             my %what = (
                   1248:                          spareid => 1,
                   1249:                          perlvar => 1,
                   1250:                        );
                   1251:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1252:             if ($result eq 'ok') {
                   1253:                 if (ref($returnhash) eq 'HASH') {
                   1254:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1255:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1256:                             $currbalancer = $server;
                   1257:                             $currtargets = {};
                   1258:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1259:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1260:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1261:                                 }
                   1262:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1263:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1264:                                 }
                   1265:                             }
                   1266:                             last;
                   1267:                         }
                   1268:                     }
                   1269:                 }
                   1270:             }
                   1271:         }
                   1272:     }
                   1273:     return ($currbalancer,$currtargets);
                   1274: }
                   1275: 
                   1276: sub check_loadbalancing {
                   1277:     my ($uname,$udom) = @_;
1.1172.2.12  raeburn  1278:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1279:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1280:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1281:     my @hosts = &current_machine_ids();
1.1129    raeburn  1282:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1283:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1284:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1285:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75! raeburn  1286:     my $domneedscache; 
1.1129    raeburn  1287:     my $cachetime = 60*60*24;
                   1288: 
                   1289:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1290:         $dom_in_use = $udom;
                   1291:         $homeintdom = 1;
                   1292:     } else {
                   1293:         $dom_in_use = $serverhomedom;
                   1294:     }
                   1295:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1296:     unless (defined($cached)) {
                   1297:         my %domconfig =
                   1298:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1299:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1300:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75! raeburn  1301:         } else {
        !          1302:             $domneedscache = $dom_in_use;
1.1129    raeburn  1303:         }
                   1304:     }
                   1305:     if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1306:         ($is_balancer,$currtargets,$currrules) =
                   1307:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1308:         if ($is_balancer) {
                   1309:             if (ref($currrules) eq 'HASH') {
                   1310:                 if ($homeintdom) {
                   1311:                     if ($uname ne '') {
                   1312:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1313:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1314:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1315:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1316:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1317:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1318:                             }
                   1319:                         }
                   1320:                         if ($rule_in_effect eq '') {
                   1321:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1322:                             if ($userenv{'inststatus'} ne '') {
                   1323:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1324:                                 my ($othertitle,$usertypes,$types) =
                   1325:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1326:                                 if (ref($types) eq 'ARRAY') {
                   1327:                                     foreach my $type (@{$types}) {
                   1328:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1329:                                             if (exists($currrules->{$type})) {
                   1330:                                                 $rule_in_effect = $currrules->{$type};
                   1331:                                             }
                   1332:                                         }
                   1333:                                     }
                   1334:                                 }
                   1335:                             } else {
                   1336:                                 if (exists($currrules->{'default'})) {
                   1337:                                     $rule_in_effect = $currrules->{'default'};
                   1338:                                 }
                   1339:                             }
                   1340:                         }
                   1341:                     } else {
                   1342:                         if (exists($currrules->{'default'})) {
                   1343:                             $rule_in_effect = $currrules->{'default'};
                   1344:                         }
                   1345:                     }
                   1346:                 } else {
                   1347:                     if ($currrules->{'_LC_external'} ne '') {
                   1348:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1349:                     }
                   1350:                 }
                   1351:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1352:                                                        $uname,$udom);
                   1353:             }
                   1354:         }
                   1355:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1356:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1357:         unless (defined($cached)) {
                   1358:             my %domconfig =
                   1359:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1360:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75! raeburn  1361:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
        !          1362:             } else {
        !          1363:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1364:             }
                   1365:         }
                   1366:         if (ref($result) eq 'HASH') {
1.1172.2.12  raeburn  1367:             ($is_balancer,$currtargets,$currrules) =
                   1368:                 &check_balancer_result($result,@hosts);
                   1369:             if ($is_balancer) {
1.1129    raeburn  1370:                 if (ref($currrules) eq 'HASH') {
                   1371:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1372:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1373:                     }
                   1374:                 }
                   1375:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1376:                                                        $uname,$udom);
                   1377:             }
                   1378:         } else {
                   1379:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1380:                 $is_balancer = 1;
                   1381:                 $offloadto = &this_host_spares($dom_in_use);
                   1382:             }
1.1172.2.75! raeburn  1383:             unless (defined($cached)) {
        !          1384:                 $domneedscache = $serverhomedom;
        !          1385:             }
1.1129    raeburn  1386:         }
                   1387:     } else {
                   1388:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1389:             $is_balancer = 1;
                   1390:             $offloadto = &this_host_spares($dom_in_use);
                   1391:         }
1.1172.2.75! raeburn  1392:         unless (defined($cached)) {
        !          1393:             $domneedscache = $serverhomedom;
        !          1394:         }
        !          1395:     }
        !          1396:     if ($domneedscache) {
        !          1397:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1398:     }
1.1172.2.5  raeburn  1399:     if ($is_balancer) {
                   1400:         my $lowest_load = 30000;
                   1401:         if (ref($offloadto) eq 'HASH') {
                   1402:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1403:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1404:                     ($otherserver,$lowest_load) =
                   1405:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1406:                 }
1.1129    raeburn  1407:             }
1.1172.2.5  raeburn  1408:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1409: 
1.1172.2.5  raeburn  1410:             if (!$found_server) {
                   1411:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1412:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1413:                         ($otherserver,$lowest_load) =
                   1414:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1415:                     }
                   1416:                 }
                   1417:             }
                   1418:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1419:             if (@{$offloadto} == 1) {
                   1420:                 $otherserver = $offloadto->[0];
                   1421:             } elsif (@{$offloadto} > 1) {
                   1422:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1423:                     ($otherserver,$lowest_load) =
                   1424:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1425:                 }
                   1426:             }
                   1427:         }
1.1172.2.5  raeburn  1428:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1429:             $is_balancer = 0;
                   1430:             if ($uname ne '' && $udom ne '') {
                   1431:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1432: 
                   1433:                     &appenv({'user.loadbalexempt'     => $lonhost,
                   1434:                              'user.loadbalcheck.time' => time});
                   1435:                 }
1.1129    raeburn  1436:             }
                   1437:         }
                   1438:     }
                   1439:     return ($is_balancer,$otherserver);
                   1440: }
                   1441: 
1.1172.2.12  raeburn  1442: sub check_balancer_result {
                   1443:     my ($result,@hosts) = @_;
                   1444:     my ($is_balancer,$currtargets,$currrules);
                   1445:     if (ref($result) eq 'HASH') {
                   1446:         if ($result->{'lonhost'} ne '') {
                   1447:             my $currbalancer = $result->{'lonhost'};
                   1448:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1449:                 $is_balancer = 1;
                   1450:                 $currtargets = $result->{'targets'};
                   1451:                 $currrules = $result->{'rules'};
                   1452:             }
                   1453:         } else {
                   1454:             foreach my $key (keys(%{$result})) {
                   1455:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1456:                     (ref($result->{$key}) eq 'HASH')) {
                   1457:                     $is_balancer = 1;
                   1458:                     $currrules = $result->{$key}{'rules'};
                   1459:                     $currtargets = $result->{$key}{'targets'};
                   1460:                     last;
                   1461:                 }
                   1462:             }
                   1463:         }
                   1464:     }
                   1465:     return ($is_balancer,$currtargets,$currrules);
                   1466: }
                   1467: 
1.1129    raeburn  1468: sub get_loadbalancer_targets {
                   1469:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1470:     my $offloadto;
1.1172.2.4  raeburn  1471:     if ($rule_in_effect eq 'none') {
                   1472:         return [$perlvar{'lonHostID'}];
                   1473:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1474:         $offloadto = $currtargets;
                   1475:     } else {
                   1476:         if ($rule_in_effect eq 'homeserver') {
                   1477:             my $homeserver = &homeserver($uname,$udom);
                   1478:             if ($homeserver ne 'no_host') {
                   1479:                 $offloadto = [$homeserver];
                   1480:             }
                   1481:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1482:             my %domconfig =
                   1483:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1484:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1485:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1486:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1487:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1488:                     }
                   1489:                 }
                   1490:             } else {
1.1172.2.7  raeburn  1491:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1492:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1493:                 if (&hostname($remotebalancer) ne '') {
                   1494:                     $offloadto = [$remotebalancer];
                   1495:                 }
                   1496:             }
                   1497:         } elsif (&hostname($rule_in_effect) ne '') {
                   1498:             $offloadto = [$rule_in_effect];
                   1499:         }
                   1500:     }
                   1501:     return $offloadto;
                   1502: }
                   1503: 
1.1127    raeburn  1504: sub internet_dom_servers {
                   1505:     my ($dom) = @_;
                   1506:     my (%uniqservers,%servers);
                   1507:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1508:     my @machinedoms = &machine_domains($primaryserver);
                   1509:     foreach my $mdom (@machinedoms) {
                   1510:         my %currservers = %servers;
                   1511:         my %server = &get_servers($mdom);
                   1512:         %servers = (%currservers,%server);
                   1513:     }
                   1514:     my %by_hostname;
                   1515:     foreach my $id (keys(%servers)) {
                   1516:         push(@{$by_hostname{$servers{$id}}},$id);
                   1517:     }
                   1518:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1519:         if (@{$by_hostname{$hostname}} > 1) {
                   1520:             my $match = 0;
                   1521:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1522:                 if (&host_domain($id) eq $dom) {
                   1523:                     $uniqservers{$id} = $hostname;
                   1524:                     $match = 1;
                   1525:                 }
                   1526:             }
                   1527:             unless ($match) {
                   1528:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1529:             }
                   1530:         } else {
                   1531:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1532:         }
                   1533:     }
                   1534:     return %uniqservers;
                   1535: }
                   1536: 
1.1       albertel 1537: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1538: 
1.599     albertel 1539: my %homecache;
1.1       albertel 1540: sub homeserver {
1.230     stredwic 1541:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1542:     my $index="$uname:$udom";
1.426     albertel 1543: 
1.599     albertel 1544:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1545: 
                   1546:     my %servers = &get_servers($udom,'library');
                   1547:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1548:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1549: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1550: 
                   1551: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1552: 	if ($answer eq 'found') {
                   1553: 	    delete($badServerCache{$tryserver}); 
                   1554: 	    return $homecache{$index}=$tryserver;
                   1555: 	} elsif ($answer eq 'no_host') {
                   1556: 	    $badServerCache{$tryserver}=1;
                   1557: 	}
1.1       albertel 1558:     }    
                   1559:     return 'no_host';
1.70      www      1560: }
                   1561: 
                   1562: # ------------------------------------- Find the usernames behind a list of IDs
                   1563: 
                   1564: sub idget {
                   1565:     my ($udom,@ids)=@_;
                   1566:     my %returnhash=();
                   1567:     
1.841     albertel 1568:     my %servers = &get_servers($udom,'library');
                   1569:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1570: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1571: 	$idlist=~tr/A-Z/a-z/; 
                   1572: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1573: 	my @answer=();
                   1574: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1575: 	    @answer=split(/\&/,$reply);
                   1576: 	}                    ;
                   1577: 	my $i;
                   1578: 	for ($i=0;$i<=$#ids;$i++) {
                   1579: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1580: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1581: 	    } 
                   1582: 	}
                   1583:     } 
1.70      www      1584:     return %returnhash;
                   1585: }
                   1586: 
                   1587: # ------------------------------------- Find the IDs behind a list of usernames
                   1588: 
                   1589: sub idrget {
                   1590:     my ($udom,@unames)=@_;
                   1591:     my %returnhash=();
1.800     albertel 1592:     foreach my $uname (@unames) {
                   1593:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1594:     }
1.70      www      1595:     return %returnhash;
                   1596: }
                   1597: 
                   1598: # ------------------------------- Store away a list of names and associated IDs
                   1599: 
                   1600: sub idput {
                   1601:     my ($udom,%ids)=@_;
                   1602:     my %servers=();
1.800     albertel 1603:     foreach my $uname (keys(%ids)) {
                   1604: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1605:         my $uhom=&homeserver($uname,$udom);
1.70      www      1606:         if ($uhom ne 'no_host') {
1.800     albertel 1607:             my $id=&escape($ids{$uname});
1.70      www      1608:             $id=~tr/A-Z/a-z/;
1.800     albertel 1609:             my $esc_unam=&escape($uname);
1.70      www      1610: 	    if ($servers{$uhom}) {
1.800     albertel 1611: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1612:             } else {
1.800     albertel 1613:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1614:             }
                   1615:         }
1.191     harris41 1616:     }
1.800     albertel 1617:     foreach my $server (keys(%servers)) {
                   1618:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1619:     }
1.344     www      1620: }
                   1621: 
1.1172.2.30  raeburn  1622: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1623: 
                   1624: sub iddel {
                   1625:     my ($udom,$idshashref,$uhome)=@_;
                   1626:     my %result=();
                   1627:     unless (ref($idshashref) eq 'HASH') {
                   1628:         return %result;
                   1629:     }
                   1630:     my %servers=();
                   1631:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1632:         my $uhom;
                   1633:         if ($uhome) {
                   1634:             $uhom = $uhome;
                   1635:         } else {
                   1636:             $uhom=&homeserver($uname,$udom);
                   1637:         }
                   1638:         if ($uhom ne 'no_host') {
                   1639:             if ($servers{$uhom}) {
                   1640:                 $servers{$uhom}.='&'.&escape($id);
                   1641:             } else {
                   1642:                 $servers{$uhom}=&escape($id);
                   1643:             }
                   1644:         }
                   1645:     }
                   1646:     foreach my $server (keys(%servers)) {
                   1647:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1648:     }
                   1649:     return %result;
                   1650: }
                   1651: 
1.1023    raeburn  1652: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1653: sub dump_dom {
1.1165    droeschl 1654:     my ($namespace, $udom, $regexp) = @_;
                   1655: 
                   1656:     $udom ||= $env{'user.domain'};
                   1657: 
                   1658:     return () unless $udom;
                   1659: 
                   1660:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1661: }
                   1662: 
1.1023    raeburn  1663: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1664: 
                   1665: sub get_dom {
1.860     raeburn  1666:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1667:     return if ($udom eq 'public');
1.806     raeburn  1668:     my $items='';
                   1669:     foreach my $item (@$storearr) {
                   1670:         $items.=&escape($item).'&';
                   1671:     }
                   1672:     $items=~s/\&$//;
1.860     raeburn  1673:     if (!$udom) {
                   1674:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1675:         return if ($udom eq 'public');
1.860     raeburn  1676:         if (defined(&domain($udom,'primary'))) {
                   1677:             $uhome=&domain($udom,'primary');
                   1678:         } else {
1.874     albertel 1679:             undef($uhome);
1.860     raeburn  1680:         }
                   1681:     } else {
                   1682:         if (!$uhome) {
                   1683:             if (defined(&domain($udom,'primary'))) {
                   1684:                 $uhome=&domain($udom,'primary');
                   1685:             }
                   1686:         }
                   1687:     }
                   1688:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1689:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1690:         my %returnhash;
1.875     albertel 1691:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1692:             return %returnhash;
                   1693:         }
1.806     raeburn  1694:         my @pairs=split(/\&/,$rep);
                   1695:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1696:             return @pairs;
                   1697:         }
                   1698:         my $i=0;
                   1699:         foreach my $item (@$storearr) {
                   1700:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1701:             $i++;
                   1702:         }
                   1703:         return %returnhash;
                   1704:     } else {
1.880     banghart 1705:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1706:     }
                   1707: }
                   1708: 
                   1709: # -------------------------------------------- put items in domain db files 
                   1710: 
                   1711: sub put_dom {
1.860     raeburn  1712:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1713:     if (!$udom) {
                   1714:         $udom=$env{'user.domain'};
                   1715:         if (defined(&domain($udom,'primary'))) {
                   1716:             $uhome=&domain($udom,'primary');
                   1717:         } else {
1.874     albertel 1718:             undef($uhome);
1.860     raeburn  1719:         }
                   1720:     } else {
                   1721:         if (!$uhome) {
                   1722:             if (defined(&domain($udom,'primary'))) {
                   1723:                 $uhome=&domain($udom,'primary');
                   1724:             }
                   1725:         }
                   1726:     } 
                   1727:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1728:         my $items='';
                   1729:         foreach my $item (keys(%$storehash)) {
                   1730:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1731:         }
                   1732:         $items=~s/\&$//;
                   1733:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1734:     } else {
1.860     raeburn  1735:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1736:     }
                   1737: }
                   1738: 
1.1023    raeburn  1739: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1740: sub newput_dom {
1.1023    raeburn  1741:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1742:     my $result;
                   1743:     if (!$udom) {
                   1744:         $udom=$env{'user.domain'};
                   1745:     }
1.1023    raeburn  1746:     if ($udom) {
                   1747:         my $uname = &get_domainconfiguser($udom);
                   1748:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1749:     }
                   1750:     return $result;
                   1751: }
                   1752: 
1.1023    raeburn  1753: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1754: sub del_dom {
1.1023    raeburn  1755:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1756:     if (ref($storearr) eq 'ARRAY') {
                   1757:         if (!$udom) {
                   1758:             $udom=$env{'user.domain'};
                   1759:         }
1.1023    raeburn  1760:         if ($udom) {
                   1761:             my $uname = &get_domainconfiguser($udom); 
                   1762:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1763:         }
                   1764:     }
                   1765: }
                   1766: 
1.1023    raeburn  1767: # ----------------------------------construct domainconfig user for a domain 
                   1768: sub get_domainconfiguser {
                   1769:     my ($udom) = @_;
                   1770:     return $udom.'-domainconfig';
                   1771: }
                   1772: 
1.837     raeburn  1773: sub retrieve_inst_usertypes {
                   1774:     my ($udom) = @_;
                   1775:     my (%returnhash,@order);
1.989     raeburn  1776:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1777:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1778:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1779:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1780:     } else {
                   1781:         if (defined(&domain($udom,'primary'))) {
                   1782:             my $uhome=&domain($udom,'primary');
                   1783:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1784:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1785:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1786:                 return (\%returnhash,\@order);
                   1787:             }
                   1788:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1789:             my @pairs=split(/\&/,$hashitems);
                   1790:             foreach my $item (@pairs) {
                   1791:                 my ($key,$value)=split(/=/,$item,2);
                   1792:                 $key = &unescape($key);
                   1793:                 next if ($key =~ /^error: 2 /);
                   1794:                 $returnhash{$key}=&thaw_unescape($value);
                   1795:             }
                   1796:             my @esc_order = split(/\&/,$orderitems);
                   1797:             foreach my $item (@esc_order) {
                   1798:                 push(@order,&unescape($item));
                   1799:             }
                   1800:         } else {
1.1172.2.44  raeburn  1801:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1802:         }
1.1172.2.44  raeburn  1803:         return (\%returnhash,\@order);
1.837     raeburn  1804:     }
                   1805: }
                   1806: 
1.868     raeburn  1807: sub is_domainimage {
                   1808:     my ($url) = @_;
1.1172.2.74  raeburn  1809:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1810:         if (&domain($1) ne '') {
                   1811:             return '1';
                   1812:         }
                   1813:     }
                   1814:     return;
                   1815: }
                   1816: 
1.899     raeburn  1817: sub inst_directory_query {
                   1818:     my ($srch) = @_;
                   1819:     my $udom = $srch->{'srchdomain'};
                   1820:     my %results;
                   1821:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1822:     my $outcome;
1.899     raeburn  1823:     if ($homeserver ne '') {
1.904     albertel 1824: 	my $queryid=&reply("querysend:instdirsearch:".
                   1825: 			   &escape($srch->{'srchby'}).':'.
                   1826: 			   &escape($srch->{'srchterm'}).':'.
                   1827: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1828: 	my $host=&hostname($homeserver);
                   1829: 	if ($queryid !~/^\Q$host\E\_/) {
                   1830: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1831: 	    return;
                   1832: 	}
                   1833: 	my $response = &get_query_reply($queryid);
                   1834: 	my $maxtries = 5;
                   1835: 	my $tries = 1;
                   1836: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1837: 	    $response = &get_query_reply($queryid);
                   1838: 	    $tries ++;
                   1839: 	}
                   1840: 
                   1841:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1842:             if ($response eq 'unavailable') {
                   1843:                 $outcome = $response;
                   1844:             } else {
                   1845:                 $outcome = 'ok';
                   1846:                 my @matches = split(/\n/,$response);
                   1847:                 foreach my $match (@matches) {
                   1848:                     my ($key,$value) = split(/=/,$match);
                   1849:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1850:                 }
1.899     raeburn  1851:             }
                   1852:         }
                   1853:     }
1.909     raeburn  1854:     return ($outcome,%results);
1.899     raeburn  1855: }
                   1856: 
                   1857: sub usersearch {
                   1858:     my ($srch) = @_;
                   1859:     my $dom = $srch->{'srchdomain'};
                   1860:     my %results;
                   1861:     my %libserv = &all_library();
                   1862:     my $query = 'usersearch';
                   1863:     foreach my $tryserver (keys(%libserv)) {
                   1864:         if (&host_domain($tryserver) eq $dom) {
                   1865:             my $host=&hostname($tryserver);
                   1866:             my $queryid=
1.911     raeburn  1867:                 &reply("querysend:".&escape($query).':'.
                   1868:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1869:                        &escape($srch->{'srchtype'}).':'.
                   1870:                        &escape($srch->{'srchterm'}),$tryserver);
                   1871:             if ($queryid !~/^\Q$host\E\_/) {
                   1872:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1873:                 next;
1.899     raeburn  1874:             }
                   1875:             my $reply = &get_query_reply($queryid);
                   1876:             my $maxtries = 1;
                   1877:             my $tries = 1;
                   1878:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1879:                 $reply = &get_query_reply($queryid);
                   1880:                 $tries ++;
                   1881:             }
                   1882:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1883:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1884:             } else {
1.911     raeburn  1885:                 my @matches;
                   1886:                 if ($reply =~ /\n/) {
                   1887:                     @matches = split(/\n/,$reply);
                   1888:                 } else {
                   1889:                     @matches = split(/\&/,$reply);
                   1890:                 }
1.899     raeburn  1891:                 foreach my $match (@matches) {
                   1892:                     my ($uname,$udom,%userhash);
1.911     raeburn  1893:                     foreach my $entry (split(/:/,$match)) {
                   1894:                         my ($key,$value) =
                   1895:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1896:                         $userhash{$key} = $value;
                   1897:                         if ($key eq 'username') {
                   1898:                             $uname = $value;
                   1899:                         } elsif ($key eq 'domain') {
                   1900:                             $udom = $value;
1.911     raeburn  1901:                         }
1.899     raeburn  1902:                     }
                   1903:                     $results{$uname.':'.$udom} = \%userhash;
                   1904:                 }
                   1905:             }
                   1906:         }
                   1907:     }
                   1908:     return %results;
                   1909: }
                   1910: 
1.912     raeburn  1911: sub get_instuser {
                   1912:     my ($udom,$uname,$id) = @_;
                   1913:     my $homeserver = &domain($udom,'primary');
                   1914:     my ($outcome,%results);
                   1915:     if ($homeserver ne '') {
                   1916:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1917:                            &escape($id).':'.&escape($udom),$homeserver);
                   1918:         my $host=&hostname($homeserver);
                   1919:         if ($queryid !~/^\Q$host\E\_/) {
                   1920:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1921:             return;
                   1922:         }
                   1923:         my $response = &get_query_reply($queryid);
                   1924:         my $maxtries = 5;
                   1925:         my $tries = 1;
                   1926:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1927:             $response = &get_query_reply($queryid);
                   1928:             $tries ++;
                   1929:         }
                   1930:         if (!&error($response) && $response ne 'refused') {
                   1931:             if ($response eq 'unavailable') {
                   1932:                 $outcome = $response;
                   1933:             } else {
                   1934:                 $outcome = 'ok';
                   1935:                 my @matches = split(/\n/,$response);
                   1936:                 foreach my $match (@matches) {
                   1937:                     my ($key,$value) = split(/=/,$match);
                   1938:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1939:                 }
                   1940:             }
                   1941:         }
                   1942:     }
                   1943:     my %userinfo;
                   1944:     if (ref($results{$uname}) eq 'HASH') {
                   1945:         %userinfo = %{$results{$uname}};
                   1946:     } 
                   1947:     return ($outcome,%userinfo);
                   1948: }
                   1949: 
1.1172.2.69  raeburn  1950: sub get_multiple_instusers {
                   1951:     my ($udom,$users,$caller) = @_;
                   1952:     my ($outcome,$results);
                   1953:     if (ref($users) eq 'HASH') {
                   1954:         my $count = keys(%{$users});
                   1955:         my $requested = &freeze_escape($users);
                   1956:         my $homeserver = &domain($udom,'primary');
                   1957:         if ($homeserver ne '') {
                   1958:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   1959:             my $host=&hostname($homeserver);
                   1960:             if ($queryid !~/^\Q$host\E\_/) {
                   1961:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   1962:                          ' for host: '.$homeserver.'in domain '.$udom);
                   1963:                 return ($outcome,$results);
                   1964:             }
                   1965:             my $response = &get_query_reply($queryid);
                   1966:             my $maxtries = 5;
                   1967:             if ($count > 100) {
                   1968:                 $maxtries = 1+int($count/20);
                   1969:             }
                   1970:             my $tries = 1;
                   1971:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   1972:                 $response = &get_query_reply($queryid);
                   1973:                 $tries ++;
                   1974:             }
                   1975:             if ($response eq '') {
                   1976:                 $results = {};
                   1977:                 foreach my $key (keys(%{$users})) {
                   1978:                     my ($uname,$id);
                   1979:                     if ($caller eq 'id') {
                   1980:                         $id = $key;
                   1981:                     } else {
                   1982:                         $uname = $key;
                   1983:                     }
                   1984:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   1985:                     $outcome = $resp;
                   1986:                     if ($resp eq 'ok') {
                   1987:                         %{$results} = (%{$results}, %info);
                   1988:                     } else {
                   1989:                         last;
                   1990:                     }
                   1991:                 }
                   1992:             } elsif(!&error($response) && ($response ne 'refused')) {
                   1993:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   1994:                     $outcome = $response;
                   1995:                 } else {
                   1996:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   1997:                     if ($outcome eq 'ok') {
                   1998:                         $results = &thaw_unescape($userdata);
                   1999:                     }
                   2000:                 }
                   2001:             }
                   2002:         }
                   2003:     }
                   2004:     return ($outcome,$results);
                   2005: }
                   2006: 
1.912     raeburn  2007: sub inst_rulecheck {
1.923     raeburn  2008:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2009:     my %returnhash;
                   2010:     if ($udom ne '') {
                   2011:         if (ref($rules) eq 'ARRAY') {
                   2012:             @{$rules} = map {&escape($_);} (@{$rules});
                   2013:             my $rulestr = join(':',@{$rules});
                   2014:             my $homeserver=&domain($udom,'primary');
                   2015:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2016:                 my $response;
                   2017:                 if ($item eq 'username') {                
                   2018:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2019:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2020:                                               $homeserver));
1.923     raeburn  2021:                 } elsif ($item eq 'id') {
                   2022:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2023:                                               ':'.&escape($id).':'.$rulestr,
                   2024:                                               $homeserver));
1.945     raeburn  2025:                 } elsif ($item eq 'selfcreate') {
                   2026:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2027:                                                &escape($udom).':'.&escape($uname).
                   2028:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2029:                 }
1.912     raeburn  2030:                 if ($response ne 'refused') {
                   2031:                     my @pairs=split(/\&/,$response);
                   2032:                     foreach my $item (@pairs) {
                   2033:                         my ($key,$value)=split(/=/,$item,2);
                   2034:                         $key = &unescape($key);
                   2035:                         next if ($key =~ /^error: 2 /);
                   2036:                         $returnhash{$key}=&thaw_unescape($value);
                   2037:                     }
                   2038:                 }
                   2039:             }
                   2040:         }
                   2041:     }
                   2042:     return %returnhash;
                   2043: }
                   2044: 
                   2045: sub inst_userrules {
1.923     raeburn  2046:     my ($udom,$check) = @_;
1.912     raeburn  2047:     my (%ruleshash,@ruleorder);
                   2048:     if ($udom ne '') {
                   2049:         my $homeserver=&domain($udom,'primary');
                   2050:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2051:             my $response;
                   2052:             if ($check eq 'id') {
                   2053:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2054:                                  $homeserver);
1.943     raeburn  2055:             } elsif ($check eq 'email') {
                   2056:                 $response=&reply('instemailrules:'.&escape($udom),
                   2057:                                  $homeserver);
1.923     raeburn  2058:             } else {
                   2059:                 $response=&reply('instuserrules:'.&escape($udom),
                   2060:                                  $homeserver);
                   2061:             }
1.912     raeburn  2062:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2063:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2064:                 ($response ne 'no_such_host')) {
                   2065:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2066:                 my @pairs=split(/\&/,$hashitems);
                   2067:                 foreach my $item (@pairs) {
                   2068:                     my ($key,$value)=split(/=/,$item,2);
                   2069:                     $key = &unescape($key);
                   2070:                     next if ($key =~ /^error: 2 /);
                   2071:                     $ruleshash{$key}=&thaw_unescape($value);
                   2072:                 }
                   2073:                 my @esc_order = split(/\&/,$orderitems);
                   2074:                 foreach my $item (@esc_order) {
                   2075:                     push(@ruleorder,&unescape($item));
                   2076:                 }
                   2077:             }
                   2078:         }
                   2079:     }
                   2080:     return (\%ruleshash,\@ruleorder);
                   2081: }
                   2082: 
1.976     raeburn  2083: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2084: 
                   2085: sub get_domain_defaults {
1.1172.2.35  raeburn  2086:     my ($domain,$ignore_cache) = @_;
                   2087:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2088:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2089:     unless ($ignore_cache) {
                   2090:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2091:         if (defined($cached)) {
                   2092:             if (ref($result) eq 'HASH') {
                   2093:                 return %{$result};
                   2094:             }
1.943     raeburn  2095:         }
                   2096:     }
                   2097:     my %domdefaults;
                   2098:     my %domconfig =
1.989     raeburn  2099:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2100:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2101:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2102:                                   'requestauthor','selfenrollment',
                   2103:                                   'coursecategories'],$domain);
1.1172.2.41  raeburn  2104:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2105:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2106:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2107:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2108:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2109:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2110:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2111:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2112:     } else {
                   2113:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2114:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2115:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2116:     }
1.976     raeburn  2117:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2118:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2119:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2120:         } else {
                   2121:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2122:         }
1.1172.2.6  raeburn  2123:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2124:         foreach my $item (@usertools) {
                   2125:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2126:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2127:             }
                   2128:         }
1.1172.2.29  raeburn  2129:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2130:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2131:         }
1.976     raeburn  2132:     }
1.985     raeburn  2133:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2134:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2135:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2136:         }
                   2137:     }
1.1172.2.9  raeburn  2138:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2139:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2140:     }
1.989     raeburn  2141:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2142:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2143:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2144:         }
                   2145:     }
1.1047    raeburn  2146:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2147:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2148:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2149:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2150:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2151:         }
1.1172.2.41  raeburn  2152:         foreach my $type (@coursetypes) {
                   2153:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2154:                 unless ($type eq 'community') {
                   2155:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2156:                 }
                   2157:             }
                   2158:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2159:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2160:             }
1.1172.2.60  raeburn  2161:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2162:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2163:                     $domdefaults{$type.'postsubtimeout'} =
                   2164:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2165:                 }
                   2166:             }
1.1172.2.30  raeburn  2167:         }
1.1172.2.67  raeburn  2168:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2169:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2170:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2171:                 if (@clonecodes) {
                   2172:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2173:                 }
                   2174:             }
                   2175:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2176:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2177:         }
1.1047    raeburn  2178:     }
1.1073    raeburn  2179:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2180:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2181:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2182:         }
                   2183:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2184:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2185:         }
1.1172.2.62  raeburn  2186:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2187:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2188:         }
1.1073    raeburn  2189:     }
1.1172.2.41  raeburn  2190:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2191:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2192:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2193:                             'approval','limit');
                   2194:             foreach my $type (@coursetypes) {
                   2195:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2196:                     my @mgrdc = ();
                   2197:                     foreach my $item (@settings) {
                   2198:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2199:                             push(@mgrdc,$item);
                   2200:                         }
                   2201:                     }
                   2202:                     if (@mgrdc) {
                   2203:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2204:                     }
                   2205:                 }
                   2206:             }
                   2207:         }
                   2208:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2209:             foreach my $type (@coursetypes) {
                   2210:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2211:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2212:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2213:                     }
                   2214:                 }
                   2215:             }
                   2216:         }
                   2217:     }
1.1172.2.46  raeburn  2218:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2219:         $domdefaults{'catauth'} = 'std';
                   2220:         $domdefaults{'catunauth'} = 'std';
                   2221:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2222:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2223:         }
                   2224:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2225:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2226:         }
                   2227:     }
1.1172.2.23  raeburn  2228:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2229:     return %domdefaults;
                   2230: }
                   2231: 
1.344     www      2232: # --------------------------------------------------- Assign a key to a student
                   2233: 
                   2234: sub assign_access_key {
1.364     www      2235: #
                   2236: # a valid key looks like uname:udom#comments
                   2237: # comments are being appended
                   2238: #
1.498     www      2239:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2240:     $kdom=
1.620     albertel 2241:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2242:     $knum=
1.620     albertel 2243:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2244:     $cdom=
1.620     albertel 2245:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2246:     $cnum=
1.620     albertel 2247:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2248:     $udom=$env{'user.name'} unless (defined($udom));
                   2249:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2250:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2251:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2252:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2253:                                                   # assigned to this person
                   2254:                                                   # - this should not happen,
1.345     www      2255:                                                   # unless something went wrong
                   2256:                                                   # the first time around
                   2257: # ready to assign
1.364     www      2258:         $logentry=$1.'; '.$logentry;
1.496     www      2259:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2260:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2261: # key now belongs to user
1.346     www      2262: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2263:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2264:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2265:                 return 'ok';
                   2266:             } else {
                   2267:                 return 
                   2268:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2269: 	    }
                   2270:         } else {
                   2271:             return 'error: Could not assign key, try again later.';
                   2272:         }
1.364     www      2273:     } elsif (!$existing{$ckey}) {
1.345     www      2274: # the key does not exist
                   2275: 	return 'error: The key does not exist';
                   2276:     } else {
                   2277: # the key is somebody else's
                   2278: 	return 'error: The key is already in use';
                   2279:     }
1.344     www      2280: }
                   2281: 
1.364     www      2282: # ------------------------------------------ put an additional comment on a key
                   2283: 
                   2284: sub comment_access_key {
                   2285: #
                   2286: # a valid key looks like uname:udom#comments
                   2287: # comments are being appended
                   2288: #
                   2289:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2290:     $cdom=
1.620     albertel 2291:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2292:     $cnum=
1.620     albertel 2293:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2294:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2295:     if ($existing{$ckey}) {
                   2296:         $existing{$ckey}.='; '.$logentry;
                   2297: # ready to assign
1.367     www      2298:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2299:                                                  $cdom,$cnum) eq 'ok') {
                   2300: 	    return 'ok';
                   2301:         } else {
                   2302: 	    return 'error: Count not store comment.';
                   2303:         }
                   2304:     } else {
                   2305: # the key does not exist
                   2306: 	return 'error: The key does not exist';
                   2307:     }
                   2308: }
                   2309: 
1.344     www      2310: # ------------------------------------------------------ Generate a set of keys
                   2311: 
                   2312: sub generate_access_keys {
1.364     www      2313:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2314:     $cdom=
1.620     albertel 2315:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2316:     $cnum=
1.620     albertel 2317:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2318:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2319:     unless (($cdom) && ($cnum)) { return 0; }
                   2320:     if ($number>10000) { return 0; }
                   2321:     sleep(2); # make sure don't get same seed twice
                   2322:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2323:     my $total=0;
                   2324:     for (my $i=1;$i<=$number;$i++) {
                   2325:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2326:                   sprintf("%lx",int(100000*rand)).'-'.
                   2327:                   sprintf("%lx",int(100000*rand));
                   2328:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2329:        $newkey=~s/0/h/g; # and also 0 and O
                   2330:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2331:        if ($existing{$newkey}) {
                   2332:            $i--;
                   2333:        } else {
1.364     www      2334: 	  if (&put('accesskeys',
                   2335:               { $newkey => '# generated '.localtime().
1.620     albertel 2336:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2337:                            '; '.$logentry },
                   2338: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2339:               $total++;
                   2340: 	  }
                   2341:        }
                   2342:     }
1.620     albertel 2343:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2344:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2345:     return $total;
                   2346: }
                   2347: 
                   2348: # ------------------------------------------------------- Validate an accesskey
                   2349: 
                   2350: sub validate_access_key {
                   2351:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2352:     $cdom=
1.620     albertel 2353:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2354:     $cnum=
1.620     albertel 2355:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2356:     $udom=$env{'user.domain'} unless (defined($udom));
                   2357:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2358:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2359:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2360: }
                   2361: 
                   2362: # ------------------------------------- Find the section of student in a course
1.652     albertel 2363: sub devalidate_getsection_cache {
                   2364:     my ($udom,$unam,$courseid)=@_;
                   2365:     my $hashid="$udom:$unam:$courseid";
                   2366:     &devalidate_cache_new('getsection',$hashid);
                   2367: }
1.298     matthew  2368: 
1.815     albertel 2369: sub courseid_to_courseurl {
                   2370:     my ($courseid) = @_;
                   2371:     #already url style courseid
                   2372:     return $courseid if ($courseid =~ m{^/});
                   2373: 
                   2374:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2375: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2376: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2377: 	return "/$cdom/$cnum";
                   2378:     }
                   2379: 
                   2380:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2381:     if (exists($courseinfo{'num'})) {
                   2382: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2383:     }
                   2384: 
                   2385:     return undef;
                   2386: }
                   2387: 
1.298     matthew  2388: sub getsection {
                   2389:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2390:     my $cachetime=1800;
1.551     albertel 2391: 
                   2392:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2393:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2394:     if (defined($cached)) { return $result; }
                   2395: 
1.298     matthew  2396:     my %Pending; 
                   2397:     my %Expired;
                   2398:     #
                   2399:     # Each role can either have not started yet (pending), be active, 
                   2400:     #    or have expired.
                   2401:     #
                   2402:     # If there is an active role, we are done.
                   2403:     #
                   2404:     # If there is more than one role which has not started yet, 
                   2405:     #     choose the one which will start sooner
                   2406:     # If there is one role which has not started yet, return it.
                   2407:     #
                   2408:     # If there is more than one expired role, choose the one which ended last.
                   2409:     # If there is a role which has expired, return it.
                   2410:     #
1.815     albertel 2411:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2412:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2413:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2414:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2415:         my $section=$1;
                   2416:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2417:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2418:         my $now=time;
1.548     albertel 2419:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2420:             $Expired{$end}=$section;
                   2421:             next;
                   2422:         }
1.548     albertel 2423:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2424:             $Pending{$start}=$section;
                   2425:             next;
                   2426:         }
1.599     albertel 2427:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2428:     }
                   2429:     #
                   2430:     # Presumedly there will be few matching roles from the above
                   2431:     # loop and the sorting time will be negligible.
                   2432:     if (scalar(keys(%Pending))) {
                   2433:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2434:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2435:     } 
                   2436:     if (scalar(keys(%Expired))) {
                   2437:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2438:         my $time = pop(@sorted);
1.599     albertel 2439:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2440:     }
1.599     albertel 2441:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2442: }
1.70      www      2443: 
1.599     albertel 2444: sub save_cache {
                   2445:     &purge_remembered();
1.722     albertel 2446:     #&Apache::loncommon::validate_page();
1.620     albertel 2447:     undef(%env);
1.780     albertel 2448:     undef($env_loaded);
1.599     albertel 2449: }
1.452     albertel 2450: 
1.599     albertel 2451: my $to_remember=-1;
                   2452: my %remembered;
                   2453: my %accessed;
                   2454: my $kicks=0;
                   2455: my $hits=0;
1.849     albertel 2456: sub make_key {
                   2457:     my ($name,$id) = @_;
1.872     albertel 2458:     if (length($id) > 65 
                   2459: 	&& length(&escape($id)) > 200) {
                   2460: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2461:     }
1.849     albertel 2462:     return &escape($name.':'.$id);
                   2463: }
                   2464: 
1.599     albertel 2465: sub devalidate_cache_new {
                   2466:     my ($name,$id,$debug) = @_;
                   2467:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2468:     $id=&make_key($name,$id);
1.599     albertel 2469:     $memcache->delete($id);
                   2470:     delete($remembered{$id});
                   2471:     delete($accessed{$id});
                   2472: }
                   2473: 
                   2474: sub is_cached_new {
                   2475:     my ($name,$id,$debug) = @_;
1.849     albertel 2476:     $id=&make_key($name,$id);
1.599     albertel 2477:     if (exists($remembered{$id})) {
1.1133    foxr     2478: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2479: 	$accessed{$id}=[&gettimeofday()];
                   2480: 	$hits++;
                   2481: 	return ($remembered{$id},1);
                   2482:     }
                   2483:     my $value = $memcache->get($id);
                   2484:     if (!(defined($value))) {
                   2485: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2486: 	return (undef,undef);
1.416     albertel 2487:     }
1.599     albertel 2488:     if ($value eq '__undef__') {
                   2489: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2490: 	$value=undef;
                   2491:     }
                   2492:     &make_room($id,$value,$debug);
                   2493:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2494:     return ($value,1);
                   2495: }
                   2496: 
                   2497: sub do_cache_new {
                   2498:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2499:     $id=&make_key($name,$id);
1.599     albertel 2500:     my $setvalue=$value;
                   2501:     if (!defined($setvalue)) {
                   2502: 	$setvalue='__undef__';
                   2503:     }
1.623     albertel 2504:     if (!defined($time) ) {
                   2505: 	$time=600;
                   2506:     }
1.599     albertel 2507:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2508:     my $result = $memcache->set($id,$setvalue,$time);
                   2509:     if (! $result) {
1.872     albertel 2510: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2511: 	$memcache->disconnect_all();
1.872     albertel 2512:     }
1.600     albertel 2513:     # need to make a copy of $value
1.919     albertel 2514:     &make_room($id,$value,$debug);
1.599     albertel 2515:     return $value;
                   2516: }
                   2517: 
                   2518: sub make_room {
                   2519:     my ($id,$value,$debug)=@_;
1.919     albertel 2520: 
                   2521:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2522:                                     : $value;
1.599     albertel 2523:     if ($to_remember<0) { return; }
                   2524:     $accessed{$id}=[&gettimeofday()];
                   2525:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2526:     my $to_kick;
                   2527:     my $max_time=0;
                   2528:     foreach my $other (keys(%accessed)) {
                   2529: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2530: 	    $to_kick=$other;
                   2531: 	    $max_time=&tv_interval($accessed{$other});
                   2532: 	}
                   2533:     }
                   2534:     delete($remembered{$to_kick});
                   2535:     delete($accessed{$to_kick});
                   2536:     $kicks++;
                   2537:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2538:     return;
                   2539: }
                   2540: 
1.599     albertel 2541: sub purge_remembered {
1.604     albertel 2542:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2543:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2544:     undef(%remembered);
                   2545:     undef(%accessed);
1.428     albertel 2546: }
1.70      www      2547: # ------------------------------------- Read an entry from a user's environment
                   2548: 
                   2549: sub userenvironment {
                   2550:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2551:     my $items;
                   2552:     foreach my $item (@what) {
                   2553:         $items.=&escape($item).'&';
                   2554:     }
                   2555:     $items=~s/\&$//;
1.70      www      2556:     my %returnhash=();
1.1009    raeburn  2557:     my $uhome = &homeserver($unam,$udom);
                   2558:     unless ($uhome eq 'no_host') {
                   2559:         my @answer=split(/\&/, 
                   2560:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2561:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2562:             return %returnhash;
                   2563:         }
1.1009    raeburn  2564:         my $i;
                   2565:         for ($i=0;$i<=$#what;$i++) {
                   2566: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2567:         }
1.70      www      2568:     }
                   2569:     return %returnhash;
1.1       albertel 2570: }
                   2571: 
1.617     albertel 2572: # ---------------------------------------------------------- Get a studentphoto
                   2573: sub studentphoto {
                   2574:     my ($udom,$unam,$ext) = @_;
                   2575:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2576:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2577:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2578:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2579:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2580:             } else {
                   2581:                 my ($result,$perm_reqd)=
1.707     albertel 2582: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2583:                 if ($result eq 'ok') {
                   2584:                     if (!($perm_reqd eq 'yes')) {
                   2585:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2586:                     }
                   2587:                 }
                   2588:             }
                   2589:         }
                   2590:     } else {
                   2591:         my ($result,$perm_reqd) = 
1.707     albertel 2592: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2593:         if ($result eq 'ok') {
                   2594:             if (!($perm_reqd eq 'yes')) {
                   2595:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2596:             }
                   2597:         }
                   2598:     }
                   2599:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2600: }
                   2601: 
                   2602: sub retrievestudentphoto {
                   2603:     my ($udom,$unam,$ext,$type) = @_;
                   2604:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2605:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2606:     if ($ret eq 'ok') {
                   2607:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2608:         if ($type eq 'thumbnail') {
                   2609:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2610:         }
                   2611:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2612:         return $tokenurl;
                   2613:     } else {
                   2614:         if ($type eq 'thumbnail') {
                   2615:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2616:         } else { 
                   2617:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2618:         }
1.617     albertel 2619:     }
                   2620: }
                   2621: 
1.263     www      2622: # -------------------------------------------------------------------- New chat
                   2623: 
                   2624: sub chatsend {
1.724     raeburn  2625:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2626:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2627:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2628:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2629:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2630: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2631: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2632: }
                   2633: 
                   2634: # ------------------------------------------ Find current version of a resource
                   2635: 
                   2636: sub getversion {
                   2637:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2638:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2639:     return &currentversion(&filelocation('',$fname));
                   2640: }
                   2641: 
                   2642: sub currentversion {
                   2643:     my $fname=shift;
                   2644:     my $author=$fname;
                   2645:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2646:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2647:     my $home=&homeserver($uname,$udom);
1.292     www      2648:     if ($home eq 'no_host') { 
                   2649:         return -1; 
                   2650:     }
1.1112    www      2651:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2652:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2653: 	return -1;
                   2654:     }
1.1112    www      2655:     return $answer;
1.263     www      2656: }
                   2657: 
1.1111    www      2658: #
                   2659: # Return special version number of resource if set by override, empty otherwise
                   2660: #
                   2661: sub usedversion {
                   2662:     my $fname=shift;
                   2663:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2664:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2665:     if ($urlversion) { return $urlversion; }
                   2666:     return '';
                   2667: }
                   2668: 
1.1       albertel 2669: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2670: 
1.1       albertel 2671: sub subscribe {
                   2672:     my $fname=shift;
1.761     raeburn  2673:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2674:     $fname=~s/[\n\r]//g;
1.1       albertel 2675:     my $author=$fname;
                   2676:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2677:     my ($udom,$uname)=split(/\//,$author);
                   2678:     my $home=homeserver($uname,$udom);
1.335     albertel 2679:     if ($home eq 'no_host') {
                   2680:         return 'not_found';
1.1       albertel 2681:     }
                   2682:     my $answer=reply("sub:$fname",$home);
1.64      www      2683:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2684: 	$answer.=' by '.$home;
                   2685:     }
1.1       albertel 2686:     return $answer;
                   2687: }
                   2688:     
1.8       www      2689: # -------------------------------------------------------------- Replicate file
                   2690: 
                   2691: sub repcopy {
                   2692:     my $filename=shift;
1.23      www      2693:     $filename=~s/\/+/\//g;
1.1142    raeburn  2694:     my $londocroot = $perlvar{'lonDocRoot'};
                   2695:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2696:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2697:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2698: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2699: 	return &repcopy_userfile($filename);
                   2700:     }
1.532     albertel 2701:     $filename=~s/[\n\r]//g;
1.8       www      2702:     my $transname="$filename.in.transfer";
1.828     www      2703: # FIXME: this should flock
1.607     raeburn  2704:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2705:     my $remoteurl=subscribe($filename);
1.64      www      2706:     if ($remoteurl =~ /^con_lost by/) {
                   2707: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2708:            return 'unavailable';
1.8       www      2709:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2710: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2711: 	   return 'not_found';
1.64      www      2712:     } elsif ($remoteurl =~ /^rejected by/) {
                   2713: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2714:            return 'forbidden';
1.20      www      2715:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2716:            return 'ok';
1.8       www      2717:     } else {
1.290     www      2718:         my $author=$filename;
                   2719:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2720:         my ($udom,$uname)=split(/\//,$author);
                   2721:         my $home=homeserver($uname,$udom);
                   2722:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2723:            my @parts=split(/\//,$filename);
                   2724:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2725:            if ($path ne "$londocroot/res") {
1.8       www      2726:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2727: 	       return 'bad_request';
1.8       www      2728:            }
                   2729:            my $count;
                   2730:            for ($count=5;$count<$#parts;$count++) {
                   2731:                $path.="/$parts[$count]";
                   2732:                if ((-e $path)!=1) {
                   2733: 		   mkdir($path,0777);
                   2734:                }
                   2735:            }
                   2736:            my $ua=new LWP::UserAgent;
                   2737:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2738:            my $response=$ua->request($request,$transname);
                   2739:            if ($response->is_error()) {
                   2740: 	       unlink($transname);
                   2741:                my $message=$response->status_line;
1.672     albertel 2742:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2743:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2744:                return 'unavailable';
1.8       www      2745:            } else {
1.16      www      2746: 	       if ($remoteurl!~/\.meta$/) {
                   2747:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2748:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2749:                   if ($mresponse->is_error()) {
                   2750: 		      unlink($filename.'.meta');
                   2751:                       &logthis(
1.672     albertel 2752:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2753:                   }
                   2754: 	       }
1.8       www      2755:                rename($transname,$filename);
1.607     raeburn  2756:                return 'ok';
1.8       www      2757:            }
1.290     www      2758:        }
1.8       www      2759:     }
1.330     www      2760: }
                   2761: 
                   2762: # ------------------------------------------------ Get server side include body
                   2763: sub ssi_body {
1.381     albertel 2764:     my ($filelink,%form)=@_;
1.606     matthew  2765:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2766:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2767:     }
1.953     www      2768:     my $output='';
                   2769:     my $response;
1.980     raeburn  2770:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2771:        ($output,$response)=&externalssi($filelink);
1.953     www      2772:     } else {
1.1004    droeschl 2773:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2774:        $filelink .= 'inhibitmenu=yes';
1.953     www      2775:        ($output,$response)=&ssi($filelink,%form);
                   2776:     }
1.778     albertel 2777:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2778:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2779:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2780:     if (wantarray) {
                   2781:         return ($output, $response);
                   2782:     } else {
                   2783:         return $output;
                   2784:     }
1.8       www      2785: }
                   2786: 
1.15      www      2787: # --------------------------------------------------------- Server Side Include
                   2788: 
1.782     albertel 2789: sub absolute_url {
                   2790:     my ($host_name) = @_;
                   2791:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2792:     if ($host_name eq '') {
                   2793: 	$host_name = $ENV{'SERVER_NAME'};
                   2794:     }
                   2795:     return $protocol.$host_name;
                   2796: }
                   2797: 
1.942     foxr     2798: #
                   2799: #   Server side include.
                   2800: # Parameters:
                   2801: #  fn     Possibly encrypted resource name/id.
                   2802: #  form   Hash that describes how the rendering should be done
                   2803: #         and other things.
1.944     foxr     2804: # Returns:
1.950     raeburn  2805: #   Scalar context: The content of the response.
                   2806: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2807: #     
1.15      www      2808: sub ssi {
                   2809: 
1.944     foxr     2810:     my ($fn,%form)=@_;
1.15      www      2811:     my $ua=new LWP::UserAgent;
1.23      www      2812:     my $request;
1.711     albertel 2813: 
                   2814:     $form{'no_update_last_known'}=1;
1.895     albertel 2815:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2816:     if (%form) {
1.782     albertel 2817:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  2818:       $request->content(join('&',map {
                   2819:             my $name = escape($_);
                   2820:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   2821:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   2822:             : &escape($form{$_}) );
                   2823:         } keys(%form)));
1.23      www      2824:     } else {
1.782     albertel 2825:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2826:     }
                   2827: 
1.15      www      2828:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2829:     my $response= $ua->request($request);
1.944     foxr     2830:     if (wantarray) {
1.1172.2.3  raeburn  2831: 	return ($response->content, $response);
1.944     foxr     2832:     } else {
1.1172.2.3  raeburn  2833: 	return $response->content;
1.942     foxr     2834:     }
1.324     www      2835: }
                   2836: 
                   2837: sub externalssi {
                   2838:     my ($url)=@_;
                   2839:     my $ua=new LWP::UserAgent;
                   2840:     my $request=new HTTP::Request('GET',$url);
                   2841:     my $response=$ua->request($request);
1.954     raeburn  2842:     if (wantarray) {
                   2843:         return ($response->content, $response);
                   2844:     } else {
                   2845:         return $response->content;
                   2846:     }
1.15      www      2847: }
1.254     www      2848: 
1.492     albertel 2849: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2850: 
                   2851: sub allowuploaded {
                   2852:     my ($srcurl,$url)=@_;
                   2853:     $url=&clutter(&declutter($url));
                   2854:     my $dir=$url;
                   2855:     $dir=~s/\/[^\/]+$//;
                   2856:     my %httpref=();
                   2857:     my $httpurl=&hreflocation('',$url);
                   2858:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2859:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2860: }
1.477     raeburn  2861: 
1.1172.2.13  raeburn  2862: #
                   2863: # Determine if the current user should be able to edit a particular resource,
                   2864: # when viewing in course context.
                   2865: # (a) When viewing resource used to determine if "Edit" item is included in
                   2866: #     Functions.
                   2867: # (b) When displaying folder contents in course editor, used to determine if
                   2868: #     "Edit" link will be displayed alongside resource.
                   2869: #
                   2870: #  input: six args -- filename (decluttered), course number, course domain,
                   2871: #                   url, symb (if registered) and group (if this is a group
                   2872: #                   item -- e.g., bulletin board, group page etc.).
                   2873: #  output: array of five scalars --
                   2874: #          $cfile -- url for file editing if editable on current server
                   2875: #          $home -- homeserver of resource (i.e., for author if published,
                   2876: #                                           or course if uploaded.).
                   2877: #          $switchserver --  1 if server switch will be needed.
                   2878: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2879: #          $forceview -- 1 if icon/link should be to go to view mode
                   2880: #
                   2881: 
                   2882: sub can_edit_resource {
                   2883:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2884:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2885: #
                   2886: # For aboutme pages user can only edit his/her own.
                   2887: #
                   2888:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2889:         my ($sdom,$sname) = ($1,$2);
                   2890:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2891:             $home = $env{'user.home'};
                   2892:             $cfile = $resurl;
                   2893:             if ($env{'form.forceedit'}) {
                   2894:                 $forceview = 1;
                   2895:             } else {
                   2896:                 $forceedit = 1;
                   2897:             }
                   2898:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2899:         } else {
                   2900:             return;
                   2901:         }
                   2902:     }
                   2903: 
                   2904:     if ($env{'request.course.id'}) {
                   2905:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2906:         if ($group ne '') {
                   2907: # if this is a group homepage or group bulletin board, check group privs
                   2908:             my $allowed = 0;
                   2909:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2910:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2911:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2912:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2913:                     $allowed = 1;
                   2914:                 }
                   2915:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2916:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2917:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2918:                     $allowed = 1;
                   2919:                 }
                   2920:             }
                   2921:             if ($allowed) {
                   2922:                 $home=&homeserver($cnum,$cdom);
                   2923:                 if ($env{'form.forceedit'}) {
                   2924:                     $forceview = 1;
                   2925:                 } else {
                   2926:                     $forceedit = 1;
                   2927:                 }
                   2928:                 $cfile = $resurl;
                   2929:             } else {
                   2930:                 return;
                   2931:             }
                   2932:         } else {
1.1172.2.15  raeburn  2933:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2934:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2935:                     return;
                   2936:                 }
                   2937:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2938: #
                   2939: # No edit allowed where CC has switched to student role.
                   2940: #
                   2941:                 return;
                   2942:             }
                   2943:         }
                   2944:     }
                   2945: 
                   2946:     if ($file ne '') {
                   2947:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2948:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2949:                 $uploaded = 1;
                   2950:                 $incourse = 1;
                   2951:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2952:                     $cfile = &hreflocation('',$file);
                   2953:                     if ($env{'form.forceedit'}) {
                   2954:                         $forceview = 1;
                   2955:                     } else {
                   2956:                         $forceedit = 1;
                   2957:                     }
                   2958:                 }
                   2959:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2960:                 $incourse = 1;
                   2961:                 if ($env{'form.forceedit'}) {
                   2962:                     $forceview = 1;
                   2963:                 } else {
                   2964:                     $forceedit = 1;
                   2965:                 }
                   2966:                 $cfile = $resurl;
                   2967:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2968:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2969:                     $incourse = 1;
                   2970:                     if ($env{'form.forceedit'}) {
                   2971:                         $forceview = 1;
                   2972:                     } else {
                   2973:                         $forceedit = 1;
                   2974:                     }
                   2975:                     $cfile = $resurl;
                   2976:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2977:                     $incourse = 1;
                   2978:                     $cfile = $resurl.'/smpedit';
                   2979:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2980:                     $incourse = 1;
                   2981:                     if ($env{'form.forceedit'}) {
                   2982:                         $forceview = 1;
                   2983:                     } else {
                   2984:                         $forceedit = 1;
                   2985:                     }
                   2986:                     $cfile = $resurl;
1.1172.2.15  raeburn  2987:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2988:                     $incourse = 1;
                   2989:                     if ($env{'form.forceedit'}) {
                   2990:                         $forceview = 1;
                   2991:                     } else {
                   2992:                         $forceedit = 1;
                   2993:                     }
                   2994:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  2995:                 }
                   2996:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2997:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2998:                 if (&is_on_map($template)) {
                   2999:                     $incourse = 1;
                   3000:                     $forceview = 1;
                   3001:                     $cfile = $template;
                   3002:                 }
                   3003:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3004:                     $incourse = 1;
                   3005:                     if ($env{'form.forceedit'}) {
                   3006:                         $forceview = 1;
                   3007:                     } else {
                   3008:                         $forceedit = 1;
                   3009:                     }
                   3010:                     $cfile = $resurl;
                   3011:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3012:                 $incourse = 1;
                   3013:                 $forceview = 1;
                   3014:                 if ($symb) {
                   3015:                     my ($map,$id,$res)=&decode_symb($symb);
                   3016:                     $env{'request.symb'} = $symb;
                   3017:                     $cfile = &clutter($res);
                   3018:                 } else {
                   3019:                     $cfile = $env{'form.suppurl'};
                   3020:                     $cfile =~ s{^http://}{};
                   3021:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3022:                 }
1.1172.2.31  raeburn  3023:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3024:                 if ($env{'form.forceedit'}) {
                   3025:                     $forceview = 1;
                   3026:                 } else {
                   3027:                     $forceedit = 1;
                   3028:                 }
                   3029:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3030:             }
                   3031:         }
                   3032:         if ($uploaded || $incourse) {
                   3033:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3034:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3035:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3036:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3037:             # Check that the user has permission to edit this resource
                   3038:             my $setpriv = 1;
                   3039:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3040:             if (defined($cfudom)) {
                   3041:                 $home=&homeserver($cfuname,$cfudom);
                   3042:                 $cfile=$file;
                   3043:             }
                   3044:         }
                   3045:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3046:             (($home ne '') && ($home ne 'no_host'))) {
                   3047:             my @ids=&current_machine_ids();
                   3048:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3049:                 $switchserver=1;
                   3050:             }
                   3051:         }
                   3052:     }
                   3053:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3054: }
                   3055: 
                   3056: sub is_course_upload {
                   3057:     my ($file,$cnum,$cdom) = @_;
                   3058:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3059:     $uploadpath =~ s{^\/}{};
                   3060:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3061:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3062:         return 1;
                   3063:     }
                   3064:     return;
                   3065: }
                   3066: 
                   3067: sub in_course {
                   3068:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3069:     if ($hideprivileged) {
                   3070:         my $skipuser;
1.1172.2.23  raeburn  3071:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3072:         my @possdoms = ($cdom);
                   3073:         if ($coursehash{'checkforpriv'}) {
                   3074:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3075:         }
                   3076:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3077:             $skipuser = 1;
                   3078:             if ($coursehash{'nothideprivileged'}) {
                   3079:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3080:                     my $user;
                   3081:                     if ($item =~ /:/) {
                   3082:                         $user = $item;
                   3083:                     } else {
                   3084:                         $user = join(':',split(/[\@]/,$item));
                   3085:                     }
                   3086:                     if ($user eq $uname.':'.$udom) {
                   3087:                         undef($skipuser);
                   3088:                         last;
                   3089:                     }
                   3090:                 }
                   3091:             }
                   3092:             if ($skipuser) {
                   3093:                 return 0;
                   3094:             }
                   3095:         }
                   3096:     }
                   3097:     $type ||= 'any';
                   3098:     if (!defined($cdom) || !defined($cnum)) {
                   3099:         my $cid  = $env{'request.course.id'};
                   3100:         $cdom = $env{'course.'.$cid.'.domain'};
                   3101:         $cnum = $env{'course.'.$cid.'.num'};
                   3102:     }
                   3103:     my $typesref;
                   3104:     if (($type eq 'any') || ($type eq 'all')) {
                   3105:         $typesref = ['active','previous','future'];
                   3106:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3107:         $typesref = [$type];
                   3108:     }
                   3109:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3110:                               $typesref,undef,[$cdom]);
                   3111:     my ($tmp) = keys(%roles);
                   3112:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3113:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3114:     if (@course_roles > 0) {
                   3115:         return 1;
                   3116:     }
                   3117:     return 0;
                   3118: }
                   3119: 
1.478     albertel 3120: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3121: # input: action, courseID, current domain, intended
1.637     raeburn  3122: #        path to file, source of file, instruction to parse file for objects,
                   3123: #        ref to hash for embedded objects,
                   3124: #        ref to hash for codebase of java objects.
1.1095    raeburn  3125: #        reference to scalar to accommodate mime type determined
                   3126: #          from File::MMagic if $parser = parse.
1.637     raeburn  3127: #
1.485     raeburn  3128: # output: url to file (if action was uploaddoc), 
                   3129: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3130: #
1.478     albertel 3131: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3132: # course.
1.477     raeburn  3133: #
1.478     albertel 3134: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3135: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3136: #          course's home server.
1.477     raeburn  3137: #
1.478     albertel 3138: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3139: #          be copied from $source (current location) to 
                   3140: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3141: #         and will then be copied to
                   3142: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3143: #         course's home server.
1.485     raeburn  3144: #
1.481     raeburn  3145: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3146: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3147: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3148: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3149: #         in course's home server.
1.637     raeburn  3150: #
1.477     raeburn  3151: 
                   3152: sub process_coursefile {
1.1095    raeburn  3153:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3154:         $mimetype)=@_;
1.477     raeburn  3155:     my $fetchresult;
1.638     albertel 3156:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3157:     if ($action eq 'propagate') {
1.638     albertel 3158:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3159: 			     $home);
1.481     raeburn  3160:     } else {
1.477     raeburn  3161:         my $fpath = '';
                   3162:         my $fname = $file;
1.478     albertel 3163:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3164:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3165:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3166:         if ($action eq 'copy') {
                   3167:             if ($source eq '') {
                   3168:                 $fetchresult = 'no source file';
                   3169:                 return $fetchresult;
                   3170:             } else {
                   3171:                 my $destination = $filepath.'/'.$fname;
                   3172:                 rename($source,$destination);
                   3173:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3174:                                  $home);
1.481     raeburn  3175:             }
                   3176:         } elsif ($action eq 'uploaddoc') {
                   3177:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3178:             print $fh $env{'form.'.$source};
1.481     raeburn  3179:             close($fh);
1.637     raeburn  3180:             if ($parser eq 'parse') {
1.1024    raeburn  3181:                 my $mm = new File::MMagic;
1.1095    raeburn  3182:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3183:                 if ($type eq 'text/html') {
1.1024    raeburn  3184:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3185:                     unless ($parse_result eq 'ok') {
                   3186:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3187:                     }
1.637     raeburn  3188:                 }
1.1095    raeburn  3189:                 if (ref($mimetype)) {
                   3190:                     $$mimetype = $type;
                   3191:                 } 
1.637     raeburn  3192:             }
1.477     raeburn  3193:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3194:                                  $home);
1.481     raeburn  3195:             if ($fetchresult eq 'ok') {
                   3196:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3197:             } else {
                   3198:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3199:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3200:                 return '/adm/notfound.html';
                   3201:             }
1.477     raeburn  3202:         }
                   3203:     }
1.485     raeburn  3204:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3205:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3206:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3207:     }
                   3208:     return $fetchresult;
                   3209: }
                   3210: 
1.637     raeburn  3211: sub build_filepath {
                   3212:     my ($fpath) = @_;
                   3213:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3214:     unless ($fpath eq '') {
                   3215:         my @parts=split('/',$fpath);
                   3216:         foreach my $part (@parts) {
                   3217:             $filepath.= '/'.$part;
                   3218:             if ((-e $filepath)!=1) {
                   3219:                 mkdir($filepath,0777);
                   3220:             }
                   3221:         }
                   3222:     }
                   3223:     return $filepath;
                   3224: }
                   3225: 
                   3226: sub store_edited_file {
1.638     albertel 3227:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3228:     my $file = $primary_url;
                   3229:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3230:     my $fpath = '';
                   3231:     my $fname = $file;
                   3232:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3233:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3234:     my $filepath = &build_filepath($fpath);
                   3235:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3236:     print $fh $content;
                   3237:     close($fh);
1.638     albertel 3238:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3239:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3240: 			  $home);
1.637     raeburn  3241:     if ($$fetchresult eq 'ok') {
                   3242:         return '/uploaded/'.$fpath.'/'.$fname;
                   3243:     } else {
1.638     albertel 3244:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3245: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3246:         return '/adm/notfound.html';
                   3247:     }
                   3248: }
                   3249: 
1.531     albertel 3250: sub clean_filename {
1.831     albertel 3251:     my ($fname,$args)=@_;
1.315     www      3252: # Replace Windows backslashes by forward slashes
1.257     www      3253:     $fname=~s/\\/\//g;
1.831     albertel 3254:     if (!$args->{'keep_path'}) {
                   3255:         # Get rid of everything but the actual filename
                   3256: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3257:     }
1.315     www      3258: # Replace spaces by underscores
                   3259:     $fname=~s/\s+/\_/g;
                   3260: # Replace all other weird characters by nothing
1.831     albertel 3261:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3262: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3263: # numbers
                   3264:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3265:     return $fname;
                   3266: }
1.1051    raeburn  3267: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3268: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3269: # image with the same aspect ratio as the original, but with dimensions which do 
                   3270: # not exceed $resizewidth and $resizeheight.
                   3271:  
1.984     neumanie 3272: sub resizeImage {
1.1051    raeburn  3273:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3274:     my $ima = Image::Magick->new;
                   3275:     my $resized;
                   3276:     if (-e $img_path) {
                   3277:         $ima->Read($img_path);
                   3278:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3279:             my $width = $ima->Get('width');
                   3280:             my $height = $ima->Get('height');
                   3281:             if ($width > $resizewidth) {
                   3282: 	        my $factor = $width/$resizewidth;
                   3283:                 my $newheight = $height/$factor;
                   3284:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3285:                 $resized = 1;
                   3286:             }
                   3287:         }
                   3288:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3289:             my $width = $ima->Get('width');
                   3290:             my $height = $ima->Get('height');
                   3291:             if ($height > $resizeheight) {
                   3292:                 my $factor = $height/$resizeheight;
                   3293:                 my $newwidth = $width/$factor;
                   3294:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3295:                 $resized = 1;
                   3296:             }
                   3297:         }
                   3298:         if ($resized) {
                   3299:             $ima->Write($img_path);
                   3300:         }
                   3301:     }
                   3302:     return;
1.977     amueller 3303: }
                   3304: 
1.608     albertel 3305: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3306: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3307: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3308: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3309: #                                    canceloverwrite, or ''. 
                   3310: #                   if 'coursedoc': upload to the current course
                   3311: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3312: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3313: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3314: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3315: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3316: #        $allfiles - reference to hash for embedded objects
                   3317: #        $codebase - reference to hash for codebase of java objects
                   3318: #        $desuname - username for permanent storage of uploaded file
                   3319: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3320: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3321: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3322: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3323: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3324: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3325: #                    from File::MMagic.
1.858     raeburn  3326: # 
1.686     albertel 3327: # output: url of file in userspace, or error: <message> 
                   3328: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3329: 
1.531     albertel 3330: sub userfileupload {
1.1090    raeburn  3331:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3332:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3333:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3334:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3335:     $fname=&clean_filename($fname);
1.1090    raeburn  3336:     # See if there is anything left
1.257     www      3337:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3338:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3339:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3340:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3341:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3342:         my $now = time;
1.1090    raeburn  3343:         my $filepath;
1.1095    raeburn  3344:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3345:              $filepath = 'tmp/helprequests/'.$now;
                   3346:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3347:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3348:                          '_'.$env{'user.domain'}.'/pending';
                   3349:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3350:             my ($docuname,$docudom);
                   3351:             if ($destudom) {
                   3352:                 $docudom = $destudom;
                   3353:             } else {
                   3354:                 $docudom = $env{'user.domain'};
                   3355:             }
                   3356:             if ($destuname) {
                   3357:                 $docuname = $destuname;
                   3358:             } else {
                   3359:                 $docuname = $env{'user.name'};
                   3360:             }
                   3361:             if (exists($env{'form.group'})) {
                   3362:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3363:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3364:             }
                   3365:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3366:             if ($context eq 'canceloverwrite') {
                   3367:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3368:                 if (-e  $tempfile) {
                   3369:                     my @info = stat($tempfile);
                   3370:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3371:                         unlink($tempfile);
                   3372:                     }
                   3373:                 }
                   3374:                 return;
1.523     raeburn  3375:             }
                   3376:         }
1.1090    raeburn  3377:         # Create the directory if not present
1.741     raeburn  3378:         my @parts=split(/\//,$filepath);
                   3379:         my $fullpath = $perlvar{'lonDaemons'};
                   3380:         for (my $i=0;$i<@parts;$i++) {
                   3381:             $fullpath .= '/'.$parts[$i];
                   3382:             if ((-e $fullpath)!=1) {
                   3383:                 mkdir($fullpath,0777);
                   3384:             }
                   3385:         }
                   3386:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3387:         print $fh $env{'form.'.$formname};
                   3388:         close($fh);
1.1090    raeburn  3389:         if ($context eq 'existingfile') {
                   3390:             my @info = stat($fullpath.'/'.$fname);
                   3391:             return ($fullpath.'/'.$fname,$info[9]);
                   3392:         } else {
                   3393:             return $fullpath.'/'.$fname;
                   3394:         }
1.523     raeburn  3395:     }
1.995     raeburn  3396:     if ($subdir eq 'scantron') {
                   3397:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3398:     } else {
1.995     raeburn  3399:         $fname="$subdir/$fname";
                   3400:     }
1.1090    raeburn  3401:     if ($context eq 'coursedoc') {
1.638     albertel 3402: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3403: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3404:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3405:             return &finishuserfileupload($docuname,$docudom,
                   3406: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3407: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3408:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3409:         } else {
1.1172.2.21  raeburn  3410:             if ($env{'form.folder'}) {
                   3411:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3412:             }
1.638     albertel 3413:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3414: 				       $fname,$formname,$parser,
1.1095    raeburn  3415: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3416:         }
1.719     banghart 3417:     } elsif (defined($destuname)) {
                   3418:         my $docuname=$destuname;
                   3419:         my $docudom=$destudom;
1.860     raeburn  3420: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3421: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3422:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3423:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3424:     } else {
1.638     albertel 3425:         my $docuname=$env{'user.name'};
                   3426:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3427:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3428:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3429:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3430:         }
1.860     raeburn  3431: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3432: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3433:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3434:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3435:     }
1.271     www      3436: }
                   3437: 
                   3438: sub finishuserfileupload {
1.860     raeburn  3439:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3440:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3441:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3442:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3443:   
1.860     raeburn  3444:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3445:     $file=$fname;
                   3446:     if ($fname=~m|/|) {
                   3447:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3448: 	$path.=$fnamepath.'/';
                   3449:     }
1.259     www      3450:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3451:     my $count;
                   3452:     for ($count=4;$count<=$#parts;$count++) {
                   3453:         $filepath.="/$parts[$count]";
                   3454:         if ((-e $filepath)!=1) {
                   3455: 	    mkdir($filepath,0777);
                   3456:         }
                   3457:     }
1.984     neumanie 3458: 
1.258     www      3459: # Save the file
                   3460:     {
1.701     albertel 3461: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3462: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3463: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3464: 	    return '/adm/notfound.html';
                   3465: 	}
1.1090    raeburn  3466:         if ($context eq 'overwrite') {
1.1117    foxr     3467:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3468:             my $target = $filepath.'/'.$file;
                   3469:             if (-e $source) {
                   3470:                 my @info = stat($source);
                   3471:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3472:                     unless (&File::Copy::move($source,$target)) {
                   3473:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3474:                         return "Moving from $source failed";
                   3475:                     }
                   3476:                 } else {
                   3477:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3478:                 }
                   3479:             } else {
                   3480:                 return "Temporary file: $source missing";
                   3481:             }
                   3482:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3483: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3484: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3485: 	    return '/adm/notfound.html';
                   3486: 	}
1.570     albertel 3487: 	close(FH);
1.1051    raeburn  3488:         if ($resizewidth && $resizeheight) {
                   3489:             my $mm = new File::MMagic;
                   3490:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3491:             if ($mime_type =~ m{^image/}) {
                   3492: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3493:             }  
1.977     amueller 3494: 	}
1.258     www      3495:     }
1.1152    raeburn  3496:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3497:         if (ref($mimetype)) {
                   3498:             if ($$mimetype eq '') {
                   3499:                 my $mm = new File::MMagic;
                   3500:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3501:                 $$mimetype = $type;
                   3502:             }
                   3503:         }
                   3504:     }
1.637     raeburn  3505:     if ($parser eq 'parse') {
1.1152    raeburn  3506:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3507:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3508:                                                        $allfiles,$codebase);
                   3509:             unless ($parse_result eq 'ok') {
                   3510:                 &logthis('Failed to parse '.$filepath.$file.
                   3511: 	   	         ' for embedded media: '.$parse_result); 
                   3512:             }
1.637     raeburn  3513:         }
                   3514:     }
1.860     raeburn  3515:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3516:         my $input = $filepath.'/'.$file;
                   3517:         my $output = $filepath.'/'.'tn-'.$file;
                   3518:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3519:         system("convert -sample $thumbsize $input $output");
                   3520:         if (-e $filepath.'/'.'tn-'.$file) {
                   3521:             $fetchthumb  = 1; 
                   3522:         }
                   3523:     }
1.858     raeburn  3524:  
1.259     www      3525: # Notify homeserver to grep it
                   3526: #
1.984     neumanie 3527:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3528:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3529:     if ($fetchresult eq 'ok') {
1.860     raeburn  3530:         if ($fetchthumb) {
                   3531:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3532:             if ($thumbresult ne 'ok') {
                   3533:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3534:                          $docuhome.': '.$thumbresult);
                   3535:             }
                   3536:         }
1.259     www      3537: #
1.258     www      3538: # Return the URL to it
1.494     albertel 3539:         return '/uploaded/'.$path.$file;
1.263     www      3540:     } else {
1.494     albertel 3541:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3542: 		 ': '.$fetchresult);
1.263     www      3543:         return '/adm/notfound.html';
1.858     raeburn  3544:     }
1.493     albertel 3545: }
                   3546: 
1.637     raeburn  3547: sub extract_embedded_items {
1.961     raeburn  3548:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3549:     my @state = ();
1.1164    raeburn  3550:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3551:     my %javafiles = (
                   3552:                       codebase => '',
                   3553:                       code => '',
                   3554:                       archive => ''
                   3555:                     );
                   3556:     my %mediafiles = (
                   3557:                       src => '',
                   3558:                       movie => '',
                   3559:                      );
1.648     raeburn  3560:     my $p;
                   3561:     if ($content) {
                   3562:         $p = HTML::LCParser->new($content);
                   3563:     } else {
1.961     raeburn  3564:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3565:     }
1.641     albertel 3566:     while (my $t=$p->get_token()) {
1.640     albertel 3567: 	if ($t->[0] eq 'S') {
                   3568: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3569: 	    push(@state, $tagname);
1.648     raeburn  3570:             if (lc($tagname) eq 'allow') {
                   3571:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3572:             }
1.640     albertel 3573: 	    if (lc($tagname) eq 'img') {
                   3574: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3575: 	    }
1.886     albertel 3576: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3577:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3578: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3579:                 }
1.886     albertel 3580: 	    }
1.645     raeburn  3581:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3582:                 my $src;
1.645     raeburn  3583:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3584:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3585:                 } else {
1.1164    raeburn  3586:                     if ($attr->{'src'} ne '') {
                   3587:                         $src = $attr->{'src'};
                   3588:                         &add_filetype($allfiles,$src,'src');
                   3589:                     }
                   3590:                 }
                   3591:                 my $text = $p->get_trimmed_text();
                   3592:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3593:                     my @swfargs = split(/,/,$1);
                   3594:                     foreach my $item (@swfargs) {
                   3595:                         $item =~ s/["']//g;
                   3596:                         $item =~ s/^\s+//;
                   3597:                         $item =~ s/\s+$//;
                   3598:                     }
                   3599:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3600:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3601:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3602:                         } else {
                   3603:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3604:                         }
                   3605:                     }
1.645     raeburn  3606:                 }
                   3607:             }
                   3608:             if (lc($tagname) eq 'link') {
                   3609:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3610:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3611:                 }
                   3612:             }
1.640     albertel 3613: 	    if (lc($tagname) eq 'object' ||
                   3614: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3615: 		foreach my $item (keys(%javafiles)) {
                   3616: 		    $javafiles{$item} = '';
                   3617: 		}
1.1164    raeburn  3618:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3619:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3620:                 }
1.640     albertel 3621: 	    }
                   3622: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3623: 		my $name = lc($attr->{'name'});
                   3624: 		foreach my $item (keys(%javafiles)) {
                   3625: 		    if ($name eq $item) {
                   3626: 			$javafiles{$item} = $attr->{'value'};
                   3627: 			last;
                   3628: 		    }
                   3629: 		}
1.1164    raeburn  3630:                 my $pathfrom;
1.640     albertel 3631: 		foreach my $item (keys(%mediafiles)) {
                   3632: 		    if ($name eq $item) {
1.1164    raeburn  3633:                         $pathfrom = $attr->{'value'};
                   3634:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3635: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3636: 			last;
                   3637: 		    }
                   3638: 		}
1.1164    raeburn  3639:                 if ($name eq 'flashvars') {
                   3640:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3641:                 }
                   3642:                 if ($pathfrom ne '') {
                   3643:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3644:                                          $pathfrom);
                   3645:                 }
1.640     albertel 3646: 	    }
                   3647: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3648: 		foreach my $item (keys(%javafiles)) {
                   3649: 		    if ($attr->{$item}) {
                   3650: 			$javafiles{$item} = $attr->{$item};
                   3651: 			last;
                   3652: 		    }
                   3653: 		}
                   3654: 		foreach my $item (keys(%mediafiles)) {
                   3655: 		    if ($attr->{$item}) {
                   3656: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3657: 			last;
                   3658: 		    }
                   3659: 		}
1.1164    raeburn  3660:                 if (lc($tagname) eq 'embed') {
                   3661:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3662:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3663:                                              $attr->{'src'});
                   3664:                     }
                   3665:                 }
1.640     albertel 3666: 	    }
1.1172.2.35  raeburn  3667:             if (lc($tagname) eq 'iframe') {
                   3668:                 my $src = $attr->{'src'} ;
                   3669:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3670:                     &add_filetype($allfiles,$src,'src');
                   3671:                 } elsif ($src =~ m{^/}) {
                   3672:                     if ($env{'request.course.id'}) {
                   3673:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3674:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3675:                         my $url = &hreflocation('',$fullpath);
                   3676:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3677:                             my $relpath = $1;
                   3678:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3679:                                 &add_filetype($allfiles,$1,'src');
                   3680:                             }
                   3681:                         }
                   3682:                     }
                   3683:                 }
                   3684:             }
1.1164    raeburn  3685:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3686:                 pop(@state);
1.1164    raeburn  3687:             }
1.640     albertel 3688: 	} elsif ($t->[0] eq 'E') {
                   3689: 	    my ($tagname) = ($t->[1]);
                   3690: 	    if ($javafiles{'codebase'} ne '') {
                   3691: 		$javafiles{'codebase'} .= '/';
                   3692: 	    }  
                   3693: 	    if (lc($tagname) eq 'applet' ||
                   3694: 		lc($tagname) eq 'object' ||
                   3695: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3696: 		) {
                   3697: 		foreach my $item (keys(%javafiles)) {
                   3698: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3699: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3700: 			&add_filetype($allfiles,$file,$item);
                   3701: 		    }
                   3702: 		}
                   3703: 	    } 
                   3704: 	    pop @state;
                   3705: 	}
                   3706:     }
1.1164    raeburn  3707:     foreach my $id (sort(keys(%flashvars))) {
                   3708:         if ($shockwave{$id} ne '') {
                   3709:             my @pairs = split(/\&/,$flashvars{$id});
                   3710:             foreach my $pair (@pairs) {
                   3711:                 my ($key,$value) = split(/\=/,$pair);
                   3712:                 if ($key eq 'thumb') {
                   3713:                     &add_filetype($allfiles,$value,$key);
                   3714:                 } elsif ($key eq 'content') {
                   3715:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3716:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3717:                     if ($ext ne '') {
                   3718:                         &add_filetype($allfiles,$path.$value,$ext);
                   3719:                     }
                   3720:                 }
                   3721:             }
                   3722:         }
                   3723:     }
1.637     raeburn  3724:     return 'ok';
                   3725: }
                   3726: 
1.639     albertel 3727: sub add_filetype {
                   3728:     my ($allfiles,$file,$type)=@_;
                   3729:     if (exists($allfiles->{$file})) {
                   3730: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3731: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3732: 	}
                   3733:     } else {
                   3734: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3735:     }
                   3736: }
                   3737: 
1.1164    raeburn  3738: sub embedded_dependency {
                   3739:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3740:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3741:         if (($identifier ne '') &&
                   3742:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3743:             ($pathfrom ne '')) {
                   3744:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3745:             foreach my $dep (@{$related->{$identifier}}) {
                   3746:                 &add_filetype($allfiles,$path.$dep,'object');
                   3747:             }
                   3748:         }
                   3749:     }
                   3750:     return;
                   3751: }
                   3752: 
1.493     albertel 3753: sub removeuploadedurl {
1.984     neumanie 3754:     my ($url)=@_;	
                   3755:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3756:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3757: }
                   3758: 
                   3759: sub removeuserfile {
                   3760:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3761:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3762:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3763:     if ($result eq 'ok') {	
1.798     raeburn  3764:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3765:             my $metafile = $fname.'.meta';
                   3766:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3767: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3768:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3769:             my $sqlresult = 
1.823     albertel 3770:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3771:                                         'portfolio_metadata',$group,
                   3772:                                         'delete');
1.798     raeburn  3773:         }
                   3774:     }
                   3775:     return $result;
1.257     www      3776: }
1.15      www      3777: 
1.530     albertel 3778: sub mkdiruserfile {
                   3779:     my ($docuname,$docudom,$dir)=@_;
                   3780:     my $home=&homeserver($docuname,$docudom);
                   3781:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3782: }
                   3783: 
1.531     albertel 3784: sub renameuserfile {
                   3785:     my ($docuname,$docudom,$old,$new)=@_;
                   3786:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3787:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3788:                         &escape("$old").':'.&escape("$new"),$home);
                   3789:     if ($result eq 'ok') {
                   3790:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3791:             my $oldmeta = $old.'.meta';
                   3792:             my $newmeta = $new.'.meta';
                   3793:             my $metaresult = 
                   3794:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3795: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3796:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3797:             my $sqlresult = 
1.823     albertel 3798:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3799:                                         'portfolio_metadata',$group,
                   3800:                                         'delete');
1.798     raeburn  3801:         }
                   3802:     }
                   3803:     return $result;
1.531     albertel 3804: }
                   3805: 
1.14      www      3806: # ------------------------------------------------------------------------- Log
                   3807: 
                   3808: sub log {
                   3809:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3810:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3811: }
                   3812: 
                   3813: # ------------------------------------------------------------------ Course Log
1.352     www      3814: #
                   3815: # This routine flushes several buffers of non-mission-critical nature
                   3816: #
1.157     www      3817: 
                   3818: sub flushcourselogs {
1.352     www      3819:     &logthis('Flushing log buffers');
                   3820: #
                   3821: # course logs
                   3822: # This is a log of all transactions in a course, which can be used
                   3823: # for data mining purposes
                   3824: #
                   3825: # It also collects the courseid database, which lists last transaction
                   3826: # times and course titles for all courseids
                   3827: #
                   3828:     my %courseidbuffer=();
1.921     raeburn  3829:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3830:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3831: 		          &escape($courselogs{$crsid}),
                   3832: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3833: 	    delete $courselogs{$crsid};
                   3834:         } else {
                   3835:             &logthis('Failed to flush log buffer for '.$crsid);
                   3836:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3837:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3838:                         " exceeded maximum size, deleting.</font>");
                   3839:                delete $courselogs{$crsid};
                   3840:             }
1.352     www      3841:         }
1.920     raeburn  3842:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3843:             'description' => $coursedescrbuf{$crsid},
                   3844:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3845:             'type'        => $coursetypebuf{$crsid},
                   3846:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3847:         };
1.191     harris41 3848:     }
1.352     www      3849: #
                   3850: # Write course id database (reverse lookup) to homeserver of courses 
                   3851: # Is used in pickcourse
                   3852: #
1.840     albertel 3853:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3854:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3855:                                     $courseidbuffer{$crs_home},
                   3856:                                     $crs_home,'timeonly');
1.352     www      3857:     }
                   3858: #
                   3859: # File accesses
                   3860: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3861: #
1.449     matthew  3862:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3863:         if ($entry =~ /___count$/) {
                   3864:             my ($dom,$name);
1.807     albertel 3865:             ($dom,$name,undef)=
1.811     albertel 3866: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3867:             if (! defined($dom) || $dom eq '' || 
                   3868:                 ! defined($name) || $name eq '') {
1.620     albertel 3869:                 my $cid = $env{'request.course.id'};
                   3870:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3871:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3872:             }
1.450     matthew  3873:             my $value = $accesshash{$entry};
                   3874:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3875:             my %temphash=($url => $value);
1.449     matthew  3876:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3877:             if ($result eq 'ok') {
                   3878:                 delete $accesshash{$entry};
                   3879:             }
                   3880:         } else {
1.811     albertel 3881:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3882:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3883:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3884:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3885:                 delete $accesshash{$entry};
                   3886:             }
1.185     www      3887:         }
1.191     harris41 3888:     }
1.352     www      3889: #
                   3890: # Roles
                   3891: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3892: #
1.800     albertel 3893:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3894:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3895: 	    split(/\:/,$entry);
                   3896:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3897:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3898:                 $rudom,$runame) eq 'ok') {
                   3899: 	    delete $userrolehash{$entry};
                   3900:         }
                   3901:     }
1.662     raeburn  3902: #
                   3903: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3904: #
                   3905:     my %domrolebuffer = ();
1.1000    raeburn  3906:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3907:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3908:         if ($domrolebuffer{$rudom}) {
                   3909:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3910:                       '='.&escape($domainrolehash{$entry});
                   3911:         } else {
                   3912:             $domrolebuffer{$rudom}.=&escape($entry).
                   3913:                       '='.&escape($domainrolehash{$entry});
                   3914:         }
                   3915:         delete $domainrolehash{$entry};
                   3916:     }
                   3917:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3918: 	my %servers = &get_servers($dom,'library');
                   3919: 	foreach my $tryserver (keys(%servers)) {
                   3920: 	    unless (&reply('domroleput:'.$dom.':'.
                   3921: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3922: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3923: 	    }
1.662     raeburn  3924:         }
                   3925:     }
1.186     www      3926:     $dumpcount++;
1.157     www      3927: }
                   3928: 
                   3929: sub courselog {
                   3930:     my $what=shift;
1.158     www      3931:     $what=time.':'.$what;
1.620     albertel 3932:     unless ($env{'request.course.id'}) { return ''; }
                   3933:     $coursedombuf{$env{'request.course.id'}}=
                   3934:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3935:     $coursenumbuf{$env{'request.course.id'}}=
                   3936:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3937:     $coursehombuf{$env{'request.course.id'}}=
                   3938:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3939:     $coursedescrbuf{$env{'request.course.id'}}=
                   3940:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3941:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3942:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3943:     $courseownerbuf{$env{'request.course.id'}}=
                   3944:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3945:     $coursetypebuf{$env{'request.course.id'}}=
                   3946:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3947:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3948: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3949:     } else {
1.620     albertel 3950: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3951:     }
1.620     albertel 3952:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3953: 	&flushcourselogs();
                   3954:     }
1.158     www      3955: }
                   3956: 
                   3957: sub courseacclog {
                   3958:     my $fnsymb=shift;
1.620     albertel 3959:     unless ($env{'request.course.id'}) { return ''; }
                   3960:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3961:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3962:         $what.=':POST';
1.583     matthew  3963:         # FIXME: Probably ought to escape things....
1.800     albertel 3964: 	foreach my $key (keys(%env)) {
                   3965:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3966:                 my $formitem = $1;
                   3967:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3968:                     $what.=':'.$formitem.'='.$env{$key};
                   3969:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3970:                     $what.=':'.$formitem.'='.$env{$key};
                   3971:                 }
1.158     www      3972:             }
1.191     harris41 3973:         }
1.583     matthew  3974:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3975:         # FIXME: We should not be depending on a form parameter that someone
                   3976:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3977:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3978:             $what.= ':POST';
                   3979:             # FIXME: Probably ought to escape things....
                   3980:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3981:                                  'crsdiscuss') {
1.620     albertel 3982:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3983:             }
                   3984:         }
1.158     www      3985:     }
                   3986:     &courselog($what);
1.149     www      3987: }
                   3988: 
1.185     www      3989: sub countacc {
                   3990:     my $url=&declutter(shift);
1.458     matthew  3991:     return if (! defined($url) || $url eq '');
1.620     albertel 3992:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3993: #
                   3994: # Mark that this url was used in this course
                   3995: #
1.620     albertel 3996:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3997: #
                   3998: # Increase the access count for this resource in this child process
                   3999: #
1.281     www      4000:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4001:     $accesshash{$key}++;
1.185     www      4002: }
1.349     www      4003: 
1.361     www      4004: sub linklog {
                   4005:     my ($from,$to)=@_;
                   4006:     $from=&declutter($from);
                   4007:     $to=&declutter($to);
                   4008:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4009:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4010: }
1.1160    www      4011: 
                   4012: sub statslog {
                   4013:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4014:     if ($users<2) { return; }
                   4015:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4016:             'course'       => $env{'request.course.id'},
                   4017:             'sections'     => '"all"',
                   4018:             'num_students' => $users,
                   4019:             'part'         => $part,
                   4020:             'symb'         => $symb,
                   4021:             'mean_tries'   => $av_attempts,
                   4022:             'deg_of_diff'  => $degdiff});
                   4023:     foreach my $key (keys(%dynstore)) {
                   4024:         $accesshash{$key}=$dynstore{$key};
                   4025:     }
                   4026: }
1.361     www      4027:   
1.349     www      4028: sub userrolelog {
                   4029:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4030:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4031:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4032:        $userrolehash
                   4033:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4034:                     =$tend.':'.$tstart;
1.662     raeburn  4035:     }
1.1169    droeschl 4036:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4037:        $userrolehash
                   4038:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4039:                     =$tend.':'.$tstart;
                   4040:     }
1.1169    droeschl 4041:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  4042:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4043:        $domainrolehash
                   4044:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4045:                     = $tend.':'.$tstart;
                   4046:     }
1.351     www      4047: }
                   4048: 
1.957     raeburn  4049: sub courserolelog {
                   4050:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4051:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4052:         my $cdom = $1;
                   4053:         my $cnum = $2;
                   4054:         my $sec = $3;
                   4055:         my $namespace = 'rolelog';
                   4056:         my %storehash = (
                   4057:                            role    => $trole,
                   4058:                            start   => $tstart,
                   4059:                            end     => $tend,
                   4060:                            selfenroll => $selfenroll,
                   4061:                            context    => $context,
                   4062:                         );
                   4063:         if ($trole eq 'gr') {
                   4064:             $namespace = 'groupslog';
                   4065:             $storehash{'group'} = $sec;
                   4066:         } else {
                   4067:             $storehash{'section'} = $sec;
                   4068:         }
                   4069:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4070:                    $domain,$cnum,$cdom);
                   4071:         if (($trole ne 'st') || ($sec ne '')) {
                   4072:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4073:         }
                   4074:     }
                   4075:     return;
                   4076: }
                   4077: 
1.1172.2.9  raeburn  4078: sub domainrolelog {
                   4079:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4080:     if ($area =~ m{^/($match_domain)/$}) {
                   4081:         my $cdom = $1;
                   4082:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4083:         my $namespace = 'rolelog';
                   4084:         my %storehash = (
                   4085:                            role    => $trole,
                   4086:                            start   => $tstart,
                   4087:                            end     => $tend,
                   4088:                            context => $context,
                   4089:                         );
                   4090:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4091:                    $domain,$domconfiguser,$cdom);
                   4092:     }
                   4093:     return;
                   4094: 
                   4095: }
                   4096: 
                   4097: sub coauthorrolelog {
                   4098:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4099:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4100:         my $audom = $1;
                   4101:         my $auname = $2;
                   4102:         my $namespace = 'rolelog';
                   4103:         my %storehash = (
                   4104:                            role    => $trole,
                   4105:                            start   => $tstart,
                   4106:                            end     => $tend,
                   4107:                            context => $context,
                   4108:                         );
                   4109:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4110:                    $domain,$auname,$audom);
                   4111:     }
                   4112:     return;
                   4113: }
                   4114: 
1.351     www      4115: sub get_course_adv_roles {
1.948     raeburn  4116:     my ($cid,$codes) = @_;
1.620     albertel 4117:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4118:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4119:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4120:     my %nothide=();
1.800     albertel 4121:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4122:         if ($user !~ /:/) {
                   4123: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4124:         } else {
                   4125:             $nothide{$user}=1;
                   4126:         }
1.470     www      4127:     }
1.1172.2.23  raeburn  4128:     my @possdoms = ($coursehash{'domain'});
                   4129:     if ($coursehash{'checkforpriv'}) {
                   4130:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4131:     }
1.351     www      4132:     my %returnhash=();
                   4133:     my %dumphash=
                   4134:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4135:     my $now=time;
1.997     raeburn  4136:     my %privileged;
1.1000    raeburn  4137:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4138: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4139:         if (($tstart) && ($tstart<0)) { next; }
                   4140:         if (($tend) && ($tend<$now)) { next; }
                   4141:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4142:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4143: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4144:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4145:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4146: 	if ($role eq 'cr') { next; }
1.948     raeburn  4147:         if ($codes) {
                   4148:             if ($section) { $role .= ':'.$section; }
                   4149:             if ($returnhash{$role}) {
                   4150:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4151:             } else {
                   4152:                 $returnhash{$role}=$username.':'.$domain;
                   4153:             }
1.351     www      4154:         } else {
1.988     raeburn  4155:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4156:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4157:             if ($returnhash{$key}) {
                   4158: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4159:             } else {
                   4160:                 $returnhash{$key}=$username.':'.$domain;
                   4161:             }
1.351     www      4162:         }
1.948     raeburn  4163:     }
1.400     www      4164:     return %returnhash;
                   4165: }
                   4166: 
                   4167: sub get_my_roles {
1.937     raeburn  4168:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4169:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4170:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4171:     my (%dumphash,%nothide);
1.1086    raeburn  4172:     if ($context eq 'userroles') {
1.1166    raeburn  4173:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4174:     } else {
1.1172.2.23  raeburn  4175:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4176:         if ($hidepriv) {
                   4177:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4178:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4179:                 if ($user !~ /:/) {
                   4180:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4181:                 } else {
                   4182:                     $nothide{$user} = 1;
                   4183:                 }
                   4184:             }
                   4185:         }
1.858     raeburn  4186:     }
1.400     www      4187:     my %returnhash=();
                   4188:     my $now=time;
1.999     raeburn  4189:     my %privileged;
1.800     albertel 4190:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4191:         my ($role,$tend,$tstart);
                   4192:         if ($context eq 'userroles') {
1.1149    raeburn  4193:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4194: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4195:         } else {
                   4196:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4197:         }
1.400     www      4198:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4199:         my $status = 'active';
1.939     raeburn  4200:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4201:             $status = 'previous';
                   4202:         } 
                   4203:         if (($tstart) && ($now<$tstart)) {
                   4204:             $status = 'future';
                   4205:         }
                   4206:         if (ref($types) eq 'ARRAY') {
                   4207:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4208:                 next;
                   4209:             } 
                   4210:         } else {
                   4211:             if ($status ne 'active') {
                   4212:                 next;
                   4213:             }
                   4214:         }
1.867     raeburn  4215:         my ($rolecode,$username,$domain,$section,$area);
                   4216:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4217:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4218:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4219:         } else {
                   4220:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4221:         }
1.832     raeburn  4222:         if (ref($roledoms) eq 'ARRAY') {
                   4223:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4224:                 next;
                   4225:             }
                   4226:         }
                   4227:         if (ref($roles) eq 'ARRAY') {
                   4228:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4229:                 if ($role =~ /^cr\//) {
                   4230:                     if (!grep(/^cr$/,@{$roles})) {
                   4231:                         next;
                   4232:                     }
1.1104    raeburn  4233:                 } elsif ($role =~ /^gr\//) {
                   4234:                     if (!grep(/^gr$/,@{$roles})) {
                   4235:                         next;
                   4236:                     }
1.922     raeburn  4237:                 } else {
                   4238:                     next;
                   4239:                 }
1.832     raeburn  4240:             }
1.867     raeburn  4241:         }
1.937     raeburn  4242:         if ($hidepriv) {
1.1172.2.23  raeburn  4243:             my @privroles = ('dc','su');
1.999     raeburn  4244:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4245:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4246:             } else {
1.1172.2.23  raeburn  4247:                 my $possdoms = [$domain];
                   4248:                 if (ref($roledoms) eq 'ARRAY') {
                   4249:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4250:                 }
1.1172.2.23  raeburn  4251:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4252:                     if (!$nothide{$username.':'.$domain}) {
                   4253:                         next;
                   4254:                     }
                   4255:                 }
1.937     raeburn  4256:             }
                   4257:         }
1.933     raeburn  4258:         if ($withsec) {
                   4259:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4260:                 $tstart.':'.$tend;
                   4261:         } else {
                   4262:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4263:         }
1.832     raeburn  4264:     }
1.373     www      4265:     return %returnhash;
1.399     www      4266: }
                   4267: 
                   4268: # ----------------------------------------------------- Frontpage Announcements
                   4269: #
                   4270: #
                   4271: 
                   4272: sub postannounce {
                   4273:     my ($server,$text)=@_;
1.844     albertel 4274:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4275:     unless ($text=~/\w/) { $text=''; }
                   4276:     return &reply('setannounce:'.&escape($text),$server);
                   4277: }
                   4278: 
                   4279: sub getannounce {
1.448     albertel 4280: 
                   4281:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4282: 	my $announcement='';
1.800     albertel 4283: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4284: 	close($fh);
1.399     www      4285: 	if ($announcement=~/\w/) { 
                   4286: 	    return 
                   4287:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4288:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4289: 	} else {
                   4290: 	    return '';
                   4291: 	}
                   4292:     } else {
                   4293: 	return '';
                   4294:     }
1.351     www      4295: }
1.353     www      4296: 
                   4297: # ---------------------------------------------------------- Course ID routines
                   4298: # Deal with domain's nohist_courseid.db files
                   4299: #
                   4300: 
                   4301: sub courseidput {
1.921     raeburn  4302:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4303:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4304:     my $outcome;
                   4305:     if ($caller eq 'timeonly') {
                   4306:         my $cids = '';
                   4307:         foreach my $item (keys(%$storehash)) {
                   4308:             $cids.=&escape($item).'&';
                   4309:         }
                   4310:         $cids=~s/\&$//;
                   4311:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4312:                           $coursehome);       
                   4313:     } else {
                   4314:         my $items = '';
                   4315:         foreach my $item (keys(%$storehash)) {
                   4316:             $items.= &escape($item).'='.
                   4317:                      &freeze_escape($$storehash{$item}).'&';
                   4318:         }
                   4319:         $items=~s/\&$//;
                   4320:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4321:                           $coursehome);
1.918     raeburn  4322:     }
                   4323:     if ($outcome eq 'unknown_cmd') {
                   4324:         my $what;
                   4325:         foreach my $cid (keys(%$storehash)) {
                   4326:             $what .= &escape($cid).'=';
1.921     raeburn  4327:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4328:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4329:             }
                   4330:             $what =~ s/\:$/&/;
                   4331:         }
                   4332:         $what =~ s/\&$//;  
                   4333:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4334:     } else {
                   4335:         return $outcome;
                   4336:     }
1.353     www      4337: }
                   4338: 
                   4339: sub courseiddump {
1.921     raeburn  4340:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4341:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4342:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4343:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  4344:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4345:     my $as_hash = 1;
                   4346:     my %returnhash;
                   4347:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4348:     my %libserv = &all_library();
                   4349:     foreach my $tryserver (keys(%libserv)) {
                   4350:         if ( (  $hostidflag == 1 
                   4351: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4352: 	     || (!defined($hostidflag)) ) {
                   4353: 
1.918     raeburn  4354: 	    if (($domfilter eq '') ||
                   4355: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4356:                 my $rep;
                   4357:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4358:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4359:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4360:                                 &escape($descfilter), &escape($instcodefilter),
                   4361:                                 &escape($ownerfilter), &escape($coursefilter),
                   4362:                                 &escape($typefilter), &escape($regexp_ok),
                   4363:                                 $as_hash, &escape($selfenrollonly),
                   4364:                                 &escape($catfilter), $showhidden, $caller,
                   4365:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4366:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  4367:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4368:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  4369:                 } else {
                   4370:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4371:                              $sincefilter.':'.&escape($descfilter).':'.
                   4372:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4373:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4374:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4375:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4376:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4377:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4378:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  4379:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4380:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  4381:                 }
                   4382: 
1.918     raeburn  4383:                 my @pairs=split(/\&/,$rep);
                   4384:                 foreach my $item (@pairs) {
                   4385:                     my ($key,$value)=split(/\=/,$item,2);
                   4386:                     $key = &unescape($key);
                   4387:                     next if ($key =~ /^error: 2 /);
                   4388:                     my $result = &thaw_unescape($value);
                   4389:                     if (ref($result) eq 'HASH') {
                   4390:                         $returnhash{$key}=$result;
                   4391:                     } else {
1.921     raeburn  4392:                         my @responses = split(/:/,$value);
                   4393:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4394:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4395:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4396:                         }
1.1008    raeburn  4397:                     }
1.353     www      4398:                 }
                   4399:             }
                   4400:         }
                   4401:     }
                   4402:     return %returnhash;
                   4403: }
                   4404: 
1.1055    raeburn  4405: sub courselastaccess {
                   4406:     my ($cdom,$cnum,$hostidref) = @_;
                   4407:     my %returnhash;
                   4408:     if ($cdom && $cnum) {
                   4409:         my $chome = &homeserver($cnum,$cdom);
                   4410:         if ($chome ne 'no_host') {
                   4411:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4412:             &extract_lastaccess(\%returnhash,$rep);
                   4413:         }
                   4414:     } else {
                   4415:         if (!$cdom) { $cdom=''; }
                   4416:         my %libserv = &all_library();
                   4417:         foreach my $tryserver (keys(%libserv)) {
                   4418:             if (ref($hostidref) eq 'ARRAY') {
                   4419:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4420:             } 
                   4421:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4422:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4423:                 &extract_lastaccess(\%returnhash,$rep);
                   4424:             }
                   4425:         }
                   4426:     }
                   4427:     return %returnhash;
                   4428: }
                   4429: 
                   4430: sub extract_lastaccess {
                   4431:     my ($returnhash,$rep) = @_;
                   4432:     if (ref($returnhash) eq 'HASH') {
                   4433:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4434:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4435:                  $rep eq '') {
                   4436:             my @pairs=split(/\&/,$rep);
                   4437:             foreach my $item (@pairs) {
                   4438:                 my ($key,$value)=split(/\=/,$item,2);
                   4439:                 $key = &unescape($key);
                   4440:                 next if ($key =~ /^error: 2 /);
                   4441:                 $returnhash->{$key} = &thaw_unescape($value);
                   4442:             }
                   4443:         }
                   4444:     }
                   4445:     return;
                   4446: }
                   4447: 
1.658     raeburn  4448: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4449: 
                   4450: sub dcmailput {
1.685     raeburn  4451:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4452:     my $status = &Apache::lonnet::critical(
1.740     www      4453:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4454:        &escape($message),$server);
1.662     raeburn  4455:     return $status;
                   4456: }
                   4457: 
1.658     raeburn  4458: sub dcmaildump {
                   4459:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4460:     my %returnhash=();
1.846     albertel 4461: 
                   4462:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4463:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4464:                                                          &escape($enddate).':';
                   4465: 	my @esc_senders=map { &escape($_)} @$senders;
                   4466: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4467: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4468:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4469:             if (($key) && ($value)) {
                   4470:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4471:             }
                   4472:         }
                   4473:     }
                   4474:     return %returnhash;
                   4475: }
1.662     raeburn  4476: # ---------------------------------------------------------- Domain roles
                   4477: 
                   4478: sub get_domain_roles {
                   4479:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4480:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4481:         $startdate = '.';
                   4482:     }
1.1018    raeburn  4483:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4484:         $enddate = '.';
                   4485:     }
1.922     raeburn  4486:     my $rolelist;
                   4487:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4488:         $rolelist = join('&',@{$roles});
1.922     raeburn  4489:     }
1.662     raeburn  4490:     my %personnel = ();
1.841     albertel 4491: 
                   4492:     my %servers = &get_servers($dom,'library');
                   4493:     foreach my $tryserver (keys(%servers)) {
                   4494: 	%{$personnel{$tryserver}}=();
                   4495: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4496: 					    &escape($startdate).':'.
                   4497: 					    &escape($enddate).':'.
                   4498: 					    &escape($rolelist), $tryserver))) {
                   4499: 	    my ($key,$value) = split(/\=/,$line,2);
                   4500: 	    if (($key) && ($value)) {
                   4501: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4502: 	    }
                   4503: 	}
1.662     raeburn  4504:     }
                   4505:     return %personnel;
                   4506: }
1.658     raeburn  4507: 
1.1057    www      4508: # ----------------------------------------------------------- Interval timing 
1.149     www      4509: 
1.1153    www      4510: {
                   4511: # Caches needed for speedup of navmaps
                   4512: # We don't want to cache this for very long at all (5 seconds at most)
                   4513: # 
                   4514: # The user for whom we cache
                   4515: my $cachedkey='';
                   4516: # The cached times for this user
                   4517: my %cachedtimes=();
                   4518: # When this was last done
1.1172.2.66  raeburn  4519: my $cachedtime='';
1.1153    www      4520: 
                   4521: sub load_all_first_access {
1.1154    raeburn  4522:     my ($uname,$udom)=@_;
1.1156    www      4523:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4524:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4525:         return;
                   4526:     }
                   4527:     $cachedtime=time;
                   4528:     $cachedkey=$uname.':'.$udom;
                   4529:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4530: }
                   4531: 
1.504     albertel 4532: sub get_first_access {
1.1162    raeburn  4533:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4534:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4535:     if ($argsymb) { $symb=$argsymb; }
                   4536:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4537:     if ($argmap) { $map = $argmap; }
1.926     albertel 4538:     if ($type eq 'course') {
                   4539: 	$res='course';
                   4540:     } elsif ($type eq 'map') {
1.588     albertel 4541: 	$res=&symbread($map);
                   4542:     } else {
                   4543: 	$res=$symb;
                   4544:     }
1.1153    www      4545:     &load_all_first_access($uname,$udom);
                   4546:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4547: }
                   4548: 
                   4549: sub set_first_access {
1.1162    raeburn  4550:     my ($type,$interval)=@_;
1.790     albertel 4551:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4552:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4553:     if ($type eq 'course') {
                   4554: 	$res='course';
                   4555:     } elsif ($type eq 'map') {
1.588     albertel 4556: 	$res=&symbread($map);
                   4557:     } else {
                   4558: 	$res=$symb;
                   4559:     }
1.1153    www      4560:     $cachedkey='';
1.1162    raeburn  4561:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4562:     if (!$firstaccess) {
1.1162    raeburn  4563:         my $start = time;
                   4564: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4565:                           $udom,$uname);
                   4566:         if ($putres eq 'ok') {
                   4567:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4568:                  $udom,$uname); 
                   4569:             &appenv(
                   4570:                      {
                   4571:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4572:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4573:                      }
                   4574:                   );
                   4575:         }
                   4576:         return $putres;
1.505     albertel 4577:     }
                   4578:     return 'already_set';
1.504     albertel 4579: }
1.1153    www      4580: }
1.1172.2.32  raeburn  4581: 
                   4582: sub checkout {
                   4583:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4584:     my $now=time;
                   4585:     my $lonhost=$perlvar{'lonHostID'};
                   4586:     my $infostr=&escape(
                   4587:                  'CHECKOUTTOKEN&'.
                   4588:                  $tuname.'&'.
                   4589:                  $tudom.'&'.
                   4590:                  $tcrsid.'&'.
                   4591:                  $symb.'&'.
                   4592:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4593:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4594:     if ($token=~/^error\:/) {
                   4595:         &logthis("<font color=\"blue\">WARNING: ".
                   4596:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4597:                  "</font>");
                   4598:         return '';
                   4599:     }
                   4600: 
                   4601:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4602:     $token=~tr/a-z/A-Z/;
                   4603: 
                   4604:     my %infohash=('resource.0.outtoken' => $token,
                   4605:                   'resource.0.checkouttime' => $now,
                   4606:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4607: 
                   4608:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4609:        return '';
                   4610:     } else {
                   4611:         &logthis("<font color=\"blue\">WARNING: ".
                   4612:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4613:                  "</font>");
                   4614:     }
                   4615: 
                   4616:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4617:                          &escape('Checkout '.$infostr.' - '.
                   4618:                                                  $token)) ne 'ok') {
                   4619:         return '';
                   4620:     } else {
                   4621:         &logthis("<font color=\"blue\">WARNING: ".
                   4622:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4623:                  "</font>");
                   4624:     }
                   4625:     return $token;
                   4626: }
                   4627: 
                   4628: # ------------------------------------------------------------ Check in an item
                   4629: 
                   4630: sub checkin {
                   4631:     my $token=shift;
                   4632:     my $now=time;
                   4633:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4634:     $lonhost=~tr/A-Z/a-z/;
                   4635:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4636:     $dtoken=~s/\W/\_/g;
                   4637:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4638:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4639: 
                   4640:     unless (($tuname) && ($tudom)) {
                   4641:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4642:         return '';
                   4643:     }
                   4644: 
                   4645:     unless (&allowed('mgr',$tcrsid)) {
                   4646:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4647:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4648:         return '';
                   4649:     }
                   4650: 
                   4651:     my %infohash=('resource.0.intoken' => $token,
                   4652:                   'resource.0.checkintime' => $now,
                   4653:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4654: 
                   4655:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4656:        return '';
                   4657:     }
                   4658: 
                   4659:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4660:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4661:         return '';
                   4662:     }
                   4663: 
                   4664:     return ($symb,$tuname,$tudom,$tcrsid);
                   4665: }
                   4666: 
1.110     www      4667: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4668: 
                   4669: sub expirespread {
                   4670:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4671:     my $cid=$env{'request.course.id'}; 
1.110     www      4672:     if ($cid) {
                   4673:        my $now=time;
                   4674:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4675:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4676:                             $env{'course.'.$cid.'.num'}.
1.110     www      4677: 	        	    ':nohist_expirationdates:'.
                   4678:                             &escape($key).'='.$now,
1.620     albertel 4679:                             $env{'course.'.$cid.'.home'})
1.110     www      4680:     }
                   4681:     return 'ok';
1.14      www      4682: }
                   4683: 
1.109     www      4684: # ----------------------------------------------------- Devalidate Spreadsheets
                   4685: 
                   4686: sub devalidate {
1.325     www      4687:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4688:     my $cid=$env{'request.course.id'}; 
1.109     www      4689:     if ($cid) {
1.391     matthew  4690:         # delete the stored spreadsheets for
                   4691:         # - the student level sheet of this user in course's homespace
                   4692:         # - the assessment level sheet for this resource 
                   4693:         #   for this user in user's homespace
1.553     albertel 4694: 	# - current conditional state info
1.325     www      4695: 	my $key=$uname.':'.$udom.':';
1.109     www      4696:         my $status=
1.299     matthew  4697: 	    &del('nohist_calculatedsheets',
1.391     matthew  4698: 		 [$key.'studentcalc:'],
1.620     albertel 4699: 		 $env{'course.'.$cid.'.domain'},
                   4700: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4701: 		.' '.
                   4702: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4703: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4704:         unless ($status eq 'ok ok') {
                   4705:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4706:                     $uname.' at '.$udom.' for '.
1.109     www      4707: 		    $symb.': '.$status);
1.133     albertel 4708:         }
1.553     albertel 4709: 	&delenv('user.state.'.$cid);
1.109     www      4710:     }
                   4711: }
                   4712: 
1.265     albertel 4713: sub get_scalar {
                   4714:     my ($string,$end) = @_;
                   4715:     my $value;
                   4716:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4717: 	$value = $1;
                   4718:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4719: 	$value = $1;
                   4720:     }
                   4721:     return &unescape($value);
                   4722: }
                   4723: 
                   4724: sub array2str {
                   4725:   my (@array) = @_;
                   4726:   my $result=&arrayref2str(\@array);
                   4727:   $result=~s/^__ARRAY_REF__//;
                   4728:   $result=~s/__END_ARRAY_REF__$//;
                   4729:   return $result;
                   4730: }
                   4731: 
1.204     albertel 4732: sub arrayref2str {
                   4733:   my ($arrayref) = @_;
1.265     albertel 4734:   my $result='__ARRAY_REF__';
1.204     albertel 4735:   foreach my $elem (@$arrayref) {
1.265     albertel 4736:     if(ref($elem) eq 'ARRAY') {
                   4737:       $result.=&arrayref2str($elem).'&';
                   4738:     } elsif(ref($elem) eq 'HASH') {
                   4739:       $result.=&hashref2str($elem).'&';
                   4740:     } elsif(ref($elem)) {
                   4741:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4742:     } else {
                   4743:       $result.=&escape($elem).'&';
                   4744:     }
                   4745:   }
                   4746:   $result=~s/\&$//;
1.265     albertel 4747:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4748:   return $result;
                   4749: }
                   4750: 
1.168     albertel 4751: sub hash2str {
1.204     albertel 4752:   my (%hash) = @_;
                   4753:   my $result=&hashref2str(\%hash);
1.265     albertel 4754:   $result=~s/^__HASH_REF__//;
                   4755:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4756:   return $result;
                   4757: }
                   4758: 
                   4759: sub hashref2str {
                   4760:   my ($hashref)=@_;
1.265     albertel 4761:   my $result='__HASH_REF__';
1.800     albertel 4762:   foreach my $key (sort(keys(%$hashref))) {
                   4763:     if (ref($key) eq 'ARRAY') {
                   4764:       $result.=&arrayref2str($key).'=';
                   4765:     } elsif (ref($key) eq 'HASH') {
                   4766:       $result.=&hashref2str($key).'=';
                   4767:     } elsif (ref($key)) {
1.265     albertel 4768:       $result.='=';
1.800     albertel 4769:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4770:     } else {
1.1132    raeburn  4771: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4772:     }
                   4773: 
1.800     albertel 4774:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4775:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4776:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4777:       $result.=&hashref2str($hashref->{$key}).'&';
                   4778:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4779:        $result.='&';
1.800     albertel 4780:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4781:     } else {
1.800     albertel 4782:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4783:     }
                   4784:   }
1.168     albertel 4785:   $result=~s/\&$//;
1.265     albertel 4786:   $result .= '__END_HASH_REF__';
1.168     albertel 4787:   return $result;
                   4788: }
                   4789: 
                   4790: sub str2hash {
1.265     albertel 4791:     my ($string)=@_;
                   4792:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4793:     return %$hash;
                   4794: }
                   4795: 
                   4796: sub str2hashref {
1.168     albertel 4797:   my ($string) = @_;
1.265     albertel 4798: 
                   4799:   my %hash;
                   4800: 
                   4801:   if($string !~ /^__HASH_REF__/) {
                   4802:       if (! ($string eq '' || !defined($string))) {
                   4803: 	  $hash{'error'}='Not hash reference';
                   4804:       }
                   4805:       return (\%hash, $string);
                   4806:   }
                   4807: 
                   4808:   $string =~ s/^__HASH_REF__//;
                   4809: 
                   4810:   while($string !~ /^__END_HASH_REF__/) {
                   4811:       #key
                   4812:       my $key='';
                   4813:       if($string =~ /^__HASH_REF__/) {
                   4814:           ($key, $string)=&str2hashref($string);
                   4815:           if(defined($key->{'error'})) {
                   4816:               $hash{'error'}='Bad data';
                   4817:               return (\%hash, $string);
                   4818:           }
                   4819:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4820:           ($key, $string)=&str2arrayref($string);
                   4821:           if($key->[0] eq 'Array reference error') {
                   4822:               $hash{'error'}='Bad data';
                   4823:               return (\%hash, $string);
                   4824:           }
                   4825:       } else {
                   4826:           $string =~ s/^(.*?)=//;
1.267     albertel 4827: 	  $key=&unescape($1);
1.265     albertel 4828:       }
                   4829:       $string =~ s/^=//;
                   4830: 
                   4831:       #value
                   4832:       my $value='';
                   4833:       if($string =~ /^__HASH_REF__/) {
                   4834:           ($value, $string)=&str2hashref($string);
                   4835:           if(defined($value->{'error'})) {
                   4836:               $hash{'error'}='Bad data';
                   4837:               return (\%hash, $string);
                   4838:           }
                   4839:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4840:           ($value, $string)=&str2arrayref($string);
                   4841:           if($value->[0] eq 'Array reference error') {
                   4842:               $hash{'error'}='Bad data';
                   4843:               return (\%hash, $string);
                   4844:           }
                   4845:       } else {
                   4846: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4847:       }
                   4848:       $string =~ s/^&//;
                   4849: 
                   4850:       $hash{$key}=$value;
1.204     albertel 4851:   }
1.265     albertel 4852: 
                   4853:   $string =~ s/^__END_HASH_REF__//;
                   4854: 
                   4855:   return (\%hash, $string);
1.204     albertel 4856: }
                   4857: 
                   4858: sub str2array {
1.265     albertel 4859:     my ($string)=@_;
                   4860:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4861:     return @$array;
                   4862: }
                   4863: 
                   4864: sub str2arrayref {
1.204     albertel 4865:   my ($string) = @_;
1.265     albertel 4866:   my @array;
                   4867: 
                   4868:   if($string !~ /^__ARRAY_REF__/) {
                   4869:       if (! ($string eq '' || !defined($string))) {
                   4870: 	  $array[0]='Array reference error';
                   4871:       }
                   4872:       return (\@array, $string);
                   4873:   }
                   4874: 
                   4875:   $string =~ s/^__ARRAY_REF__//;
                   4876: 
                   4877:   while($string !~ /^__END_ARRAY_REF__/) {
                   4878:       my $value='';
                   4879:       if($string =~ /^__HASH_REF__/) {
                   4880:           ($value, $string)=&str2hashref($string);
                   4881:           if(defined($value->{'error'})) {
                   4882:               $array[0] ='Array reference error';
                   4883:               return (\@array, $string);
                   4884:           }
                   4885:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4886:           ($value, $string)=&str2arrayref($string);
                   4887:           if($value->[0] eq 'Array reference error') {
                   4888:               $array[0] ='Array reference error';
                   4889:               return (\@array, $string);
                   4890:           }
                   4891:       } else {
                   4892: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4893:       }
                   4894:       $string =~ s/^&//;
                   4895: 
                   4896:       push(@array, $value);
1.191     harris41 4897:   }
1.265     albertel 4898: 
                   4899:   $string =~ s/^__END_ARRAY_REF__//;
                   4900: 
                   4901:   return (\@array, $string);
1.168     albertel 4902: }
                   4903: 
1.167     albertel 4904: # -------------------------------------------------------------------Temp Store
                   4905: 
1.168     albertel 4906: sub tmpreset {
                   4907:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4908:   if (!$symb) {
                   4909:     $symb=&symbread();
1.620     albertel 4910:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4911:   }
                   4912:   $symb=escape($symb);
                   4913: 
1.620     albertel 4914:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4915:   $namespace=~s/\//\_/g;
                   4916:   $namespace=~s/\W//g;
                   4917: 
1.620     albertel 4918:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4919:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4920:   if ($domain eq 'public' && $stuname eq 'public') {
                   4921:       $stuname=$ENV{'REMOTE_ADDR'};
                   4922:   }
1.1117    foxr     4923:   my $path=LONCAPA::tempdir();
1.168     albertel 4924:   my %hash;
                   4925:   if (tie(%hash,'GDBM_File',
                   4926: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4927: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4928:     foreach my $key (keys(%hash)) {
1.180     albertel 4929:       if ($key=~ /:$symb/) {
1.168     albertel 4930: 	delete($hash{$key});
                   4931:       }
                   4932:     }
                   4933:   }
                   4934: }
                   4935: 
1.167     albertel 4936: sub tmpstore {
1.168     albertel 4937:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4938: 
                   4939:   if (!$symb) {
                   4940:     $symb=&symbread();
1.620     albertel 4941:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4942:   }
                   4943:   $symb=escape($symb);
                   4944: 
                   4945:   if (!$namespace) {
                   4946:     # I don't think we would ever want to store this for a course.
                   4947:     # it seems this will only be used if we don't have a course.
1.620     albertel 4948:     #$namespace=$env{'request.course.id'};
1.168     albertel 4949:     #if (!$namespace) {
1.620     albertel 4950:       $namespace=$env{'request.state'};
1.168     albertel 4951:     #}
                   4952:   }
                   4953:   $namespace=~s/\//\_/g;
                   4954:   $namespace=~s/\W//g;
1.620     albertel 4955:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4956:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4957:   if ($domain eq 'public' && $stuname eq 'public') {
                   4958:       $stuname=$ENV{'REMOTE_ADDR'};
                   4959:   }
1.168     albertel 4960:   my $now=time;
                   4961:   my %hash;
1.1117    foxr     4962:   my $path=LONCAPA::tempdir();
1.168     albertel 4963:   if (tie(%hash,'GDBM_File',
                   4964: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4965: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4966:     $hash{"version:$symb"}++;
                   4967:     my $version=$hash{"version:$symb"};
                   4968:     my $allkeys=''; 
                   4969:     foreach my $key (keys(%$storehash)) {
                   4970:       $allkeys.=$key.':';
1.591     albertel 4971:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4972:     }
                   4973:     $hash{"$version:$symb:timestamp"}=$now;
                   4974:     $allkeys.='timestamp';
                   4975:     $hash{"$version:keys:$symb"}=$allkeys;
                   4976:     if (untie(%hash)) {
                   4977:       return 'ok';
                   4978:     } else {
                   4979:       return "error:$!";
                   4980:     }
                   4981:   } else {
                   4982:     return "error:$!";
                   4983:   }
                   4984: }
1.167     albertel 4985: 
1.168     albertel 4986: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4987: 
1.168     albertel 4988: sub tmprestore {
                   4989:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4990: 
1.168     albertel 4991:   if (!$symb) {
                   4992:     $symb=&symbread();
1.620     albertel 4993:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4994:   }
                   4995:   $symb=escape($symb);
                   4996: 
1.620     albertel 4997:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4998: 
1.620     albertel 4999:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5000:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5001:   if ($domain eq 'public' && $stuname eq 'public') {
                   5002:       $stuname=$ENV{'REMOTE_ADDR'};
                   5003:   }
1.168     albertel 5004:   my %returnhash;
                   5005:   $namespace=~s/\//\_/g;
                   5006:   $namespace=~s/\W//g;
                   5007:   my %hash;
1.1117    foxr     5008:   my $path=LONCAPA::tempdir();
1.168     albertel 5009:   if (tie(%hash,'GDBM_File',
                   5010: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5011: 	  &GDBM_READER(),0640)) {
1.168     albertel 5012:     my $version=$hash{"version:$symb"};
                   5013:     $returnhash{'version'}=$version;
                   5014:     my $scope;
                   5015:     for ($scope=1;$scope<=$version;$scope++) {
                   5016:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5017:       my @keys=split(/:/,$vkeys);
                   5018:       my $key;
                   5019:       $returnhash{"$scope:keys"}=$vkeys;
                   5020:       foreach $key (@keys) {
1.591     albertel 5021: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5022: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5023:       }
                   5024:     }
1.168     albertel 5025:     if (!(untie(%hash))) {
                   5026:       return "error:$!";
                   5027:     }
                   5028:   } else {
                   5029:     return "error:$!";
                   5030:   }
                   5031:   return %returnhash;
1.167     albertel 5032: }
                   5033: 
1.9       www      5034: # ----------------------------------------------------------------------- Store
                   5035: 
                   5036: sub store {
1.1172.2.64  raeburn  5037:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5038:     my $home='';
                   5039: 
1.168     albertel 5040:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5041: 
1.213     www      5042:     $symb=&symbclean($symb);
1.122     albertel 5043:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5044: 
1.620     albertel 5045:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5046:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5047: 
                   5048:     &devalidate($symb,$stuname,$domain);
1.109     www      5049: 
                   5050:     $symb=escape($symb);
1.187     www      5051:     if (!$namespace) { 
1.620     albertel 5052:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5053:           return ''; 
                   5054:        } 
                   5055:     }
1.620     albertel 5056:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5057: 
                   5058:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5059:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5060: 
1.12      www      5061:     my $namevalue='';
1.800     albertel 5062:     foreach my $key (keys(%$storehash)) {
                   5063:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5064:     }
1.12      www      5065:     $namevalue=~s/\&$//;
1.187     www      5066:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5067:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5068: }
                   5069: 
1.47      www      5070: # -------------------------------------------------------------- Critical Store
                   5071: 
                   5072: sub cstore {
1.1172.2.64  raeburn  5073:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5074:     my $home='';
                   5075: 
1.168     albertel 5076:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5077: 
1.213     www      5078:     $symb=&symbclean($symb);
1.122     albertel 5079:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5080: 
1.620     albertel 5081:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5082:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5083: 
                   5084:     &devalidate($symb,$stuname,$domain);
1.109     www      5085: 
                   5086:     $symb=escape($symb);
1.187     www      5087:     if (!$namespace) { 
1.620     albertel 5088:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5089:           return ''; 
                   5090:        } 
                   5091:     }
1.620     albertel 5092:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5093: 
                   5094:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5095:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5096: 
1.47      www      5097:     my $namevalue='';
1.800     albertel 5098:     foreach my $key (keys(%$storehash)) {
                   5099:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5100:     }
1.47      www      5101:     $namevalue=~s/\&$//;
1.187     www      5102:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5103:     return critical
1.1172.2.64  raeburn  5104:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5105: }
                   5106: 
1.9       www      5107: # --------------------------------------------------------------------- Restore
                   5108: 
                   5109: sub restore {
1.124     www      5110:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5111:     my $home='';
                   5112: 
1.168     albertel 5113:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5114: 
1.122     albertel 5115:     if (!$symb) {
1.1172.2.26  raeburn  5116:         return if ($namespace eq 'courserequests');
                   5117:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5118:     } else {
1.1172.2.26  raeburn  5119:         unless ($namespace eq 'courserequests') {
                   5120:             $symb=&escape(&symbclean($symb));
                   5121:         }
1.122     albertel 5122:     }
1.188     www      5123:     if (!$namespace) { 
1.620     albertel 5124:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5125:           return ''; 
                   5126:        } 
                   5127:     }
1.620     albertel 5128:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5129:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5130:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5131:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5132: 
1.12      www      5133:     my %returnhash=();
1.800     albertel 5134:     foreach my $line (split(/\&/,$answer)) {
                   5135: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5136:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5137:     }
1.75      www      5138:     my $version;
                   5139:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5140:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5141:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5142:        }
1.75      www      5143:     }
1.13      www      5144:     return %returnhash;
1.34      www      5145: }
                   5146: 
                   5147: # ---------------------------------------------------------- Course Description
1.1118    foxr     5148: #
                   5149: #  
1.34      www      5150: 
                   5151: sub coursedescription {
1.731     albertel 5152:     my ($courseid,$args)=@_;
1.34      www      5153:     $courseid=~s/^\///;
1.49      www      5154:     $courseid=~s/\_/\//g;
1.34      www      5155:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5156:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5157:     my $normalid=$cdomain.'_'.$cnum;
                   5158:     # need to always cache even if we get errors otherwise we keep 
                   5159:     # trying and trying and trying to get the course description.
                   5160:     my %envhash=();
                   5161:     my %returnhash=();
1.731     albertel 5162:     
                   5163:     my $expiretime=600;
                   5164:     if ($env{'request.course.id'} eq $normalid) {
                   5165: 	$expiretime=120;
                   5166:     }
                   5167: 
                   5168:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5169:     if (!$args->{'freshen_cache'}
                   5170: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5171: 	foreach my $key (keys(%env)) {
                   5172: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5173: 	    my ($setting) = $1;
                   5174: 	    $returnhash{$setting} = $env{$key};
                   5175: 	}
                   5176: 	return %returnhash;
                   5177:     }
                   5178: 
1.1118    foxr     5179:     # get the data again
                   5180: 
1.731     albertel 5181:     if (!$args->{'one_time'}) {
                   5182: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5183:     }
1.811     albertel 5184: 
1.34      www      5185:     if ($chome ne 'no_host') {
1.302     albertel 5186:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5187:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5188: 	   my $username = $env{'user.name'}; # Defult username
                   5189: 	   if(defined $args->{'user'}) {
                   5190: 	       $username = $args->{'user'};
                   5191: 	   }
1.129     albertel 5192:            $returnhash{'home'}= $chome;
                   5193: 	   $returnhash{'domain'} = $cdomain;
                   5194: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5195:            if (!defined($returnhash{'type'})) {
                   5196:                $returnhash{'type'} = 'Course';
                   5197:            }
1.130     albertel 5198:            while (my ($name,$value) = each %returnhash) {
1.53      www      5199:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5200:            }
1.270     www      5201:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5202:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5203: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5204:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5205:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5206:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5207:        }
                   5208:     }
1.731     albertel 5209:     if (!$args->{'one_time'}) {
1.949     raeburn  5210: 	&appenv(\%envhash);
1.731     albertel 5211:     }
1.302     albertel 5212:     return %returnhash;
1.461     www      5213: }
                   5214: 
1.1080    raeburn  5215: sub update_released_required {
                   5216:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5217:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5218:         $cid = $env{'request.course.id'};
                   5219:         $cdom = $env{'course.'.$cid.'.domain'};
                   5220:         $cnum = $env{'course.'.$cid.'.num'};
                   5221:         $chome = $env{'course.'.$cid.'.home'};
                   5222:     }
                   5223:     if ($needsrelease) {
                   5224:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5225:         my $needsupdate;
                   5226:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5227:             $needsupdate = 1;
                   5228:         } else {
                   5229:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5230:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5231:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5232:                 $needsupdate = 1;
                   5233:             }
                   5234:         }
                   5235:         if ($needsupdate) {
                   5236:             my %needshash = (
                   5237:                              'internal.releaserequired' => $needsrelease,
                   5238:                             );
                   5239:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5240:             if ($putresult eq 'ok') {
                   5241:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5242:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5243:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5244:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5245:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5246:                 }
                   5247:             }
                   5248:         }
                   5249:     }
                   5250:     return;
                   5251: }
                   5252: 
1.461     www      5253: # -------------------------------------------------See if a user is privileged
                   5254: 
                   5255: sub privileged {
1.1172.2.23  raeburn  5256:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5257:     my $now = time;
1.1172.2.23  raeburn  5258:     my $roles;
                   5259:     if (ref($possroles) eq 'ARRAY') {
                   5260:         $roles = $possroles;
                   5261:     } else {
                   5262:         $roles = ['dc','su'];
                   5263:     }
                   5264:     if (ref($possdomains) eq 'ARRAY') {
                   5265:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5266:         foreach my $dom (@{$possdomains}) {
                   5267:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5268:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5269:                 foreach my $role (@{$roles}) {
                   5270:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5271:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5272:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5273:                             return 1 unless (($end && $end < $now) ||
                   5274:                                              ($start && $start > $now));
                   5275:                         }
                   5276:                     }
                   5277:                 }
                   5278:             }
                   5279:         }
                   5280:     } else {
                   5281:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5282:         my $now = time;
1.1170    droeschl 5283: 
1.1172.2.58  raeburn  5284:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5285:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5286:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5287:                 return 1 unless ($tend && $tend < $now)
                   5288:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5289:             }
1.1172.2.23  raeburn  5290:         }
                   5291:     }
1.461     www      5292:     return 0;
1.9       www      5293: }
1.1       albertel 5294: 
1.1172.2.23  raeburn  5295: sub privileged_by_domain {
                   5296:     my ($domains,$roles) = @_;
                   5297:     my %privileged = ();
                   5298:     my $cachetime = 60*60*24;
                   5299:     my $now = time;
                   5300:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5301:         return %privileged;
                   5302:     }
                   5303:     foreach my $dom (@{$domains}) {
                   5304:         next if (ref($privileged{$dom}) eq 'HASH');
                   5305:         my $needroles;
                   5306:         foreach my $role (@{$roles}) {
                   5307:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5308:             if (defined($cached)) {
                   5309:                 if (ref($result) eq 'HASH') {
                   5310:                     $privileged{$dom}{$role} = $result;
                   5311:                 }
                   5312:             } else {
                   5313:                 $needroles = 1;
                   5314:             }
                   5315:         }
                   5316:         if ($needroles) {
                   5317:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5318:             $privileged{$dom} = {};
                   5319:             foreach my $server (keys(%dompersonnel)) {
                   5320:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5321:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5322:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5323:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5324:                         next if ($end && $end < $now);
                   5325:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5326:                             $dompersonnel{$server}{$item};
                   5327:                     }
                   5328:                 }
                   5329:             }
                   5330:             if (ref($privileged{$dom}) eq 'HASH') {
                   5331:                 foreach my $role (@{$roles}) {
                   5332:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5333:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5334:                     } else {
                   5335:                         my %hash = ();
                   5336:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5337:                     }
                   5338:                 }
                   5339:             }
                   5340:         }
                   5341:     }
                   5342:     return %privileged;
                   5343: }
                   5344: 
1.103     harris41 5345: # -------------------------------------------------------- Get user privileges
1.11      www      5346: 
                   5347: sub rolesinit {
1.1169    droeschl 5348:     my ($domain, $username) = @_;
                   5349:     my %userroles = ('user.login.time' => time);
                   5350:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5351: 
                   5352:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5353:     # also, blocking can be triggered by an activating timer
                   5354:     # it's saved in the user's %env.
                   5355:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5356:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5357:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5358:         %timerintchk, %timerintenv);
                   5359: 
1.1162    raeburn  5360:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5361:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5362:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5363:     }
1.1169    droeschl 5364: 
1.1162    raeburn  5365:     foreach my $key (keys(%timerinterval)) {
                   5366:         my ($cid,$rest) = split(/\0/,$key);
                   5367:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5368:     }
1.1169    droeschl 5369: 
1.11      www      5370:     my %allroles=();
1.1162    raeburn  5371:     my %allgroups=();
1.11      www      5372: 
1.1172.2.58  raeburn  5373:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5374:         my $role = $rolesdump{$area};
                   5375:         $area =~ s/\_\w\w$//;
                   5376: 
                   5377:         my ($trole, $tend, $tstart, $group_privs);
                   5378: 
                   5379:         if ($role =~ /^cr/) {
                   5380:         # Custom role, defined by a user 
                   5381:         # e.g., user.role.cr/msu/smith/mynewrole
                   5382:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5383:                 $trole = $1;
                   5384:                 ($tend, $tstart) = split('_', $2);
                   5385:             } else {
                   5386:                 $trole = $role;
                   5387:             }
                   5388:         } elsif ($role =~ m|^gr/|) {
                   5389:         # Role of member in a group, defined within a course/community
                   5390:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5391:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5392:             next if $tstart eq '-1';
                   5393:             ($trole, $group_privs) = split(/\//, $trole);
                   5394:             $group_privs = &unescape($group_privs);
                   5395:         } else {
                   5396:         # Just a normal role, defined in roles.tab
                   5397:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5398:         }
                   5399: 
                   5400:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5401:                  $username);
                   5402:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5403: 
                   5404:         # role expired or not available yet?
                   5405:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5406:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5407: 
                   5408:         next if $area eq '' or $trole eq '';
                   5409: 
                   5410:         my $spec = "$trole.$area";
                   5411:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5412: 
                   5413:         if ($trole =~ /^cr\//) {
                   5414:         # Custom role, defined by a user
                   5415:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5416:         } elsif ($trole eq 'gr') {
                   5417:         # Role of a member in a group, defined within a course/community
                   5418:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5419:             next;
                   5420:         } else {
                   5421:         # Normal role, defined in roles.tab
                   5422:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5423:         }
                   5424: 
                   5425:         my $cid = $tdomain.'_'.$trest;
                   5426:         unless ($firstaccchk{$cid}) {
                   5427:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5428:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5429:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5430:                         $coursetimerstarts{$cid}{$item}; 
                   5431:                 }
                   5432:             }
                   5433:             $firstaccchk{$cid} = 1;
                   5434:         }
                   5435:         unless ($timerintchk{$cid}) {
                   5436:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5437:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5438:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5439:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5440:                 }
1.12      www      5441:             }
1.1169    droeschl 5442:             $timerintchk{$cid} = 1;
1.191     harris41 5443:         }
1.11      www      5444:     }
1.1169    droeschl 5445: 
                   5446:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5447:         \%allroles, \%allgroups);
                   5448:     $env{'user.adv'} = $userroles{'user.adv'};
                   5449: 
1.1162    raeburn  5450:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5451: }
                   5452: 
1.567     raeburn  5453: sub set_arearole {
1.1172.2.19  raeburn  5454:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5455:     unless ($nolog) {
1.567     raeburn  5456: # log the associated role with the area
1.1172.2.19  raeburn  5457:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5458:     }
1.743     albertel 5459:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5460: }
                   5461: 
                   5462: sub custom_roleprivs {
                   5463:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5464:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5465:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5466:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5467:         my ($rdummy,$roledef)=
                   5468:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5469:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5470:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5471:             if (defined($syspriv)) {
1.1043    raeburn  5472:                 if ($trest =~ /^$match_community$/) {
                   5473:                     $syspriv =~ s/bre\&S//; 
                   5474:                 }
1.567     raeburn  5475:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5476:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5477:             }
                   5478:             if ($tdomain ne '') {
                   5479:                 if (defined($dompriv)) {
                   5480:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5481:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5482:                 }
                   5483:                 if (($trest ne '') && (defined($coursepriv))) {
                   5484:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5485:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5486:                 }
                   5487:             }
                   5488:         }
                   5489:     }
                   5490: }
                   5491: 
1.678     raeburn  5492: sub group_roleprivs {
                   5493:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5494:     my $access = 1;
                   5495:     my $now = time;
                   5496:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5497:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5498:     if ($access) {
1.811     albertel 5499:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5500:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5501:     }
                   5502: }
1.567     raeburn  5503: 
                   5504: sub standard_roleprivs {
                   5505:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5506:     if (defined($pr{$trole.':s'})) {
                   5507:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5508:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5509:     }
                   5510:     if ($tdomain ne '') {
                   5511:         if (defined($pr{$trole.':d'})) {
                   5512:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5513:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5514:         }
                   5515:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5516:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5517:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5518:         }
                   5519:     }
                   5520: }
                   5521: 
                   5522: sub set_userprivs {
1.1064    raeburn  5523:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5524:     my $author=0;
                   5525:     my $adv=0;
1.678     raeburn  5526:     my %grouproles = ();
                   5527:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5528:         my @groupkeys; 
1.1000    raeburn  5529:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5530:             push(@groupkeys,$role);
                   5531:         }
                   5532:         if (ref($groups_roles) eq 'HASH') {
                   5533:             foreach my $key (keys(%{$groups_roles})) {
                   5534:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5535:                     push(@groupkeys,$key);
                   5536:                 }
                   5537:             }
                   5538:         }
                   5539:         if (@groupkeys > 0) {
                   5540:             foreach my $role (@groupkeys) {
                   5541:                 my ($trole,$area,$sec,$extendedarea);
                   5542:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5543:                     $trole = $1;
                   5544:                     $area = $2;
                   5545:                     $sec = $3;
                   5546:                     $extendedarea = $area.$sec;
                   5547:                     if (exists($$allgroups{$area})) {
                   5548:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5549:                             my $spec = $trole.'.'.$extendedarea;
                   5550:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5551:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5552:                         }
1.678     raeburn  5553:                     }
                   5554:                 }
                   5555:             }
                   5556:         }
                   5557:     }
1.800     albertel 5558:     foreach my $group (keys(%grouproles)) {
                   5559:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5560:     }
1.800     albertel 5561:     foreach my $role (keys(%{$allroles})) {
                   5562:         my %thesepriv;
1.941     raeburn  5563:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5564:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5565:             if ($item ne '') {
                   5566:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5567:                 if ($restrictions eq '') {
                   5568:                     $thesepriv{$privilege}='F';
                   5569:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5570:                     $thesepriv{$privilege}.=$restrictions;
                   5571:                 }
                   5572:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5573:             }
                   5574:         }
                   5575:         my $thesestr='';
1.1104    raeburn  5576:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5577: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5578: 	}
                   5579:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5580:     }
                   5581:     return ($author,$adv);
                   5582: }
                   5583: 
1.994     raeburn  5584: sub role_status {
1.1104    raeburn  5585:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5586:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  5587:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5588:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5589:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  5590:             $$where = '/'.$two;
1.994     raeburn  5591:             $$trolecode=$$role.'.'.$$where;
                   5592:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5593:             $$tstatus='is';
1.1104    raeburn  5594:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5595:                 $$tstatus='future';
1.1034    raeburn  5596:                 if ($$tstart<$now) {
                   5597:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5598:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5599:                             my (%allroles,%allgroups,$group_privs,
                   5600:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5601:                             my %userroles = (
                   5602:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5603:                             );
1.1064    raeburn  5604:                             @rolecodes = ('cm'); 
1.1002    raeburn  5605:                             my $spec=$$role.'.'.$$where;
                   5606:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5607:                             if ($$role =~ /^cr\//) {
                   5608:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5609:                                 push(@rolecodes,'cr');
1.1002    raeburn  5610:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5611:                                 push(@rolecodes,$$role);
1.1002    raeburn  5612:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5613:                                                     $env{'user.name'});
1.1064    raeburn  5614:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5615:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5616:                                 $group_privs = &unescape($group_privs);
                   5617:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5618:                                 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  5619:                                 &get_groups_roles($tdomain,$trest,
                   5620:                                                   \%course_roles,\@rolecodes,
                   5621:                                                   \%groups_roles);
1.1002    raeburn  5622:                             } else {
1.1064    raeburn  5623:                                 push(@rolecodes,$$role);
1.1002    raeburn  5624:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5625:                             }
1.1064    raeburn  5626:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5627:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5628:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5629:                         }
                   5630:                     }
1.1034    raeburn  5631:                     $$tstatus = 'is';
1.1002    raeburn  5632:                 }
1.994     raeburn  5633:             }
                   5634:             if ($$tend) {
1.1104    raeburn  5635:                 if ($$tend<$update) {
1.994     raeburn  5636:                     $$tstatus='expired';
                   5637:                 } elsif ($$tend<$now) {
                   5638:                     $$tstatus='will_not';
                   5639:                 }
                   5640:             }
                   5641:         }
                   5642:     }
                   5643: }
                   5644: 
1.1104    raeburn  5645: sub get_groups_roles {
                   5646:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5647:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5648:                   (ref($rolecodes) eq 'ARRAY') && 
                   5649:                   (ref($groups_roles) eq 'HASH')); 
                   5650:     if (keys(%{$cdom_courseroles}) > 0) {
                   5651:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5652:         if ($cdom ne '' && $cnum ne '') {
                   5653:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5654:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5655:                     my $crsrole = $1;
                   5656:                     my $crssec = $2;
                   5657:                     if ($crsrole =~ /^cr/) {
                   5658:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5659:                             push(@{$rolecodes},'cr');
                   5660:                         }
                   5661:                     } else {
                   5662:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5663:                             push(@{$rolecodes},$crsrole);
                   5664:                         }
                   5665:                     }
                   5666:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5667:                     if ($crssec ne '') {
                   5668:                         $rolekey .= "/$crssec";
                   5669:                     }
                   5670:                     $rolekey .= './';
                   5671:                     $groups_roles->{$rolekey} = $rolecodes;
                   5672:                 }
                   5673:             }
                   5674:         }
                   5675:     }
                   5676:     return;
                   5677: }
                   5678: 
                   5679: sub delete_env_groupprivs {
                   5680:     my ($where,$courseroles,$possroles) = @_;
                   5681:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5682:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5683:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5684:         %{$courseroles->{$udom}} =
                   5685:             &get_my_roles('','','userroles',['active'],
                   5686:                           $possroles,[$udom],1);
                   5687:     }
                   5688:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5689:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5690:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5691:             my $area = '/'.$cdom.'/'.$cnum;
                   5692:             my $privkey = "user.priv.$crsrole.$area";
                   5693:             if ($crssec ne '') {
                   5694:                 $privkey .= '/'.$crssec;
                   5695:             }
                   5696:             $privkey .= ".$area/$group";
                   5697:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5698:         }
                   5699:     }
                   5700:     return;
                   5701: }
                   5702: 
1.994     raeburn  5703: sub check_adhoc_privs {
1.1104    raeburn  5704:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5705:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5706:     my $setprivs;
1.994     raeburn  5707:     if ($env{$cckey}) {
                   5708:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5709:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5710:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5711:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5712:             $setprivs = 1;
1.994     raeburn  5713:         }
                   5714:     } else {
1.1088    raeburn  5715:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5716:         $setprivs = 1;
1.994     raeburn  5717:     }
1.1172.2.9  raeburn  5718:     return $setprivs;
1.994     raeburn  5719: }
                   5720: 
                   5721: sub set_adhoc_privileges {
                   5722: # role can be cc or ca
1.1088    raeburn  5723:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5724:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5725:     my $spec = $role.'.'.$area;
                   5726:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5727:                                   $env{'user.name'},1);
1.994     raeburn  5728:     my %ccrole = ();
                   5729:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5730:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5731:     &appenv(\%userroles,[$role,'cm']);
                   5732:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5733:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5734:         &appenv( {'request.role'        => $spec,
                   5735:                   'request.role.domain' => $dcdom,
                   5736:                   'request.course.sec'  => ''
                   5737:                  }
                   5738:                );
                   5739:         my $tadv=0;
                   5740:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5741:         &appenv({'request.role.adv'    => $tadv});
                   5742:     }
1.994     raeburn  5743: }
                   5744: 
1.12      www      5745: # --------------------------------------------------------------- get interface
                   5746: 
                   5747: sub get {
1.131     albertel 5748:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5749:    my $items='';
1.800     albertel 5750:    foreach my $item (@$storearr) {
                   5751:        $items.=&escape($item).'&';
1.191     harris41 5752:    }
1.12      www      5753:    $items=~s/\&$//;
1.620     albertel 5754:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5755:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5756:    my $uhome=&homeserver($uname,$udomain);
                   5757: 
1.133     albertel 5758:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5759:    my @pairs=split(/\&/,$rep);
1.273     albertel 5760:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5761:      return @pairs;
                   5762:    }
1.15      www      5763:    my %returnhash=();
1.42      www      5764:    my $i=0;
1.800     albertel 5765:    foreach my $item (@$storearr) {
                   5766:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5767:       $i++;
1.191     harris41 5768:    }
1.15      www      5769:    return %returnhash;
1.27      www      5770: }
                   5771: 
                   5772: # --------------------------------------------------------------- del interface
                   5773: 
                   5774: sub del {
1.133     albertel 5775:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5776:    my $items='';
1.800     albertel 5777:    foreach my $item (@$storearr) {
                   5778:        $items.=&escape($item).'&';
1.191     harris41 5779:    }
1.984     neumanie 5780: 
1.27      www      5781:    $items=~s/\&$//;
1.620     albertel 5782:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5783:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5784:    my $uhome=&homeserver($uname,$udomain);
                   5785:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5786: }
                   5787: 
                   5788: # -------------------------------------------------------------- dump interface
                   5789: 
1.1172.2.22  raeburn  5790: sub unserialize {
                   5791:     my ($rep, $escapedkeys) = @_;
                   5792: 
                   5793:     return {} if $rep =~ /^error/;
                   5794: 
                   5795:     my %returnhash=();
                   5796:     foreach my $item (split(/\&/,$rep)) {
                   5797:         my ($key, $value) = split(/=/, $item, 2);
                   5798:         $key = unescape($key) unless $escapedkeys;
                   5799:         next if $key =~ /^error: 2 /;
                   5800:         $returnhash{$key} = &thaw_unescape($value);
                   5801:     }
                   5802:     return \%returnhash;
                   5803: }
                   5804: 
                   5805: # see Lond::dump_with_regexp
                   5806: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5807: sub dump {
1.1172.2.22  raeburn  5808:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5809:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5810:     if (!$uname) { $uname=$env{'user.name'}; }
                   5811:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5812: 
1.1172.2.55  raeburn  5813:     if ($regexp) {
                   5814:         $regexp=&escape($regexp);
                   5815:     } else {
                   5816:         $regexp='.';
                   5817:     }
1.1172.2.22  raeburn  5818:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   5819:         # user is hosted on this machine
1.1172.2.55  raeburn  5820:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  5821:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  5822:         return %{&unserialize($reply, $escapedkeys)};
                   5823:     }
1.1166    raeburn  5824:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5825:     my @pairs=split(/\&/,$rep);
                   5826:     my %returnhash=();
1.1098    foxr     5827:     if (!($rep =~ /^error/ )) {
                   5828: 	foreach my $item (@pairs) {
                   5829: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  5830:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5831: 	    next if ($key =~ /^error: 2 /);
                   5832: 	    $returnhash{$key}=&thaw_unescape($value);
                   5833: 	}
1.755     albertel 5834:     }
                   5835:     return %returnhash;
1.407     www      5836: }
                   5837: 
1.1098    foxr     5838: 
1.717     albertel 5839: # --------------------------------------------------------- dumpstore interface
                   5840: 
                   5841: sub dumpstore {
                   5842:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  5843:    # same as dump but keys must be escaped. They may contain colon separated
                   5844:    # lists of values that may themself contain colons (e.g. symbs).
                   5845:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5846: }
                   5847: 
1.407     www      5848: # -------------------------------------------------------------- keys interface
                   5849: 
                   5850: sub getkeys {
                   5851:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5852:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5853:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5854:    my $uhome=&homeserver($uname,$udomain);
                   5855:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5856:    my @keyarray=();
1.800     albertel 5857:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5858:       next if ($key =~ /^error: 2 /);
1.800     albertel 5859:       push(@keyarray,&unescape($key));
1.407     www      5860:    }
                   5861:    return @keyarray;
1.318     matthew  5862: }
                   5863: 
1.319     matthew  5864: # --------------------------------------------------------------- currentdump
                   5865: sub currentdump {
1.328     matthew  5866:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5867:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5868:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5869:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5870:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  5871:    my $rep;
                   5872: 
                   5873:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5874:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   5875:                    $courseid)));
                   5876:    } else {
                   5877:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5878:    }
                   5879: 
1.318     matthew  5880:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5881:    #
1.318     matthew  5882:    my %returnhash=();
1.319     matthew  5883:    #
                   5884:    if ($rep eq "unknown_cmd") { 
                   5885:        # an old lond will not know currentdump
                   5886:        # Do a dump and make it look like a currentdump
1.822     albertel 5887:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5888:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5889:        my %hash = @tmp;
                   5890:        @tmp=();
1.424     matthew  5891:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5892:    } else {
                   5893:        my @pairs=split(/\&/,$rep);
1.800     albertel 5894:        foreach my $pair (@pairs) {
                   5895:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5896:            my ($symb,$param) = split(/:/,$key);
                   5897:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5898:                                                         &thaw_unescape($value);
1.319     matthew  5899:        }
1.191     harris41 5900:    }
1.12      www      5901:    return %returnhash;
1.424     matthew  5902: }
                   5903: 
                   5904: sub convert_dump_to_currentdump{
                   5905:     my %hash = %{shift()};
                   5906:     my %returnhash;
                   5907:     # Code ripped from lond, essentially.  The only difference
                   5908:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5909:     # we might run in to problems with parameter names =~ /^v\./
                   5910:     while (my ($key,$value) = each(%hash)) {
                   5911:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5912: 	$symb  = &unescape($symb);
                   5913: 	$param = &unescape($param);
1.424     matthew  5914:         next if ($v eq 'version' || $symb eq 'keys');
                   5915:         next if (exists($returnhash{$symb}) &&
                   5916:                  exists($returnhash{$symb}->{$param}) &&
                   5917:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5918:         $returnhash{$symb}->{$param}=$value;
                   5919:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5920:     }
                   5921:     #
                   5922:     # Remove all of the keys in the hashes which keep track of
                   5923:     # the version of the parameter.
                   5924:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5925:         # use a foreach because we are going to delete from the hash.
                   5926:         foreach my $key (keys(%$param_hash)) {
                   5927:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5928:         }
                   5929:     }
                   5930:     return \%returnhash;
1.12      www      5931: }
                   5932: 
1.627     albertel 5933: # ------------------------------------------------------ critical inc interface
                   5934: 
                   5935: sub cinc {
                   5936:     return &inc(@_,'critical');
                   5937: }
                   5938: 
1.449     matthew  5939: # --------------------------------------------------------------- inc interface
                   5940: 
                   5941: sub inc {
1.627     albertel 5942:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5943:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5944:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5945:     my $uhome=&homeserver($uname,$udomain);
                   5946:     my $items='';
                   5947:     if (! ref($store)) {
                   5948:         # got a single value, so use that instead
                   5949:         $items = &escape($store).'=&';
                   5950:     } elsif (ref($store) eq 'SCALAR') {
                   5951:         $items = &escape($$store).'=&';        
                   5952:     } elsif (ref($store) eq 'ARRAY') {
                   5953:         $items = join('=&',map {&escape($_);} @{$store});
                   5954:     } elsif (ref($store) eq 'HASH') {
                   5955:         while (my($key,$value) = each(%{$store})) {
                   5956:             $items.= &escape($key).'='.&escape($value).'&';
                   5957:         }
                   5958:     }
                   5959:     $items=~s/\&$//;
1.627     albertel 5960:     if ($critical) {
                   5961: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5962:     } else {
                   5963: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5964:     }
1.449     matthew  5965: }
                   5966: 
1.12      www      5967: # --------------------------------------------------------------- put interface
                   5968: 
                   5969: sub put {
1.134     albertel 5970:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5971:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5972:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5973:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5974:    my $items='';
1.800     albertel 5975:    foreach my $item (keys(%$storehash)) {
                   5976:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5977:    }
1.12      www      5978:    $items=~s/\&$//;
1.134     albertel 5979:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5980: }
                   5981: 
1.631     albertel 5982: # ------------------------------------------------------------ newput interface
                   5983: 
                   5984: sub newput {
                   5985:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5986:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5987:    if (!$uname) { $uname=$env{'user.name'}; }
                   5988:    my $uhome=&homeserver($uname,$udomain);
                   5989:    my $items='';
                   5990:    foreach my $key (keys(%$storehash)) {
                   5991:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5992:    }
                   5993:    $items=~s/\&$//;
                   5994:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5995: }
                   5996: 
                   5997: # ---------------------------------------------------------  putstore interface
                   5998: 
1.524     raeburn  5999: sub putstore {
1.1172.2.59  raeburn  6000:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6001:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6002:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6003:    my $uhome=&homeserver($uname,$udomain);
                   6004:    my $items='';
1.715     albertel 6005:    foreach my $key (keys(%$storehash)) {
                   6006:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6007:    }
1.715     albertel 6008:    $items=~s/\&$//;
1.716     albertel 6009:    my $esc_symb=&escape($symb);
                   6010:    my $esc_v=&escape($version);
1.715     albertel 6011:    my $reply =
1.716     albertel 6012:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6013: 	      $uhome);
1.1172.2.59  raeburn  6014:    if (($tolog) && ($reply eq 'ok')) {
                   6015:        my $namevalue='';
                   6016:        foreach my $key (keys(%{$storehash})) {
                   6017:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6018:        }
                   6019:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6020:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6021:                      '&version='.$esc_v.
                   6022:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6023:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6024:    }
1.715     albertel 6025:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6026:        # gfall back to way things use to be done
1.715     albertel 6027:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6028: 			    $uname);
1.524     raeburn  6029:    }
1.715     albertel 6030:    return $reply;
                   6031: }
                   6032: 
                   6033: sub old_putstore {
1.716     albertel 6034:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6035:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6036:     if (!$uname) { $uname=$env{'user.name'}; }
                   6037:     my $uhome=&homeserver($uname,$udomain);
                   6038:     my %newstorehash;
1.800     albertel 6039:     foreach my $item (keys(%$storehash)) {
                   6040: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6041: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6042:     }
                   6043:     my $items='';
                   6044:     my %allitems = ();
1.800     albertel 6045:     foreach my $item (keys(%newstorehash)) {
                   6046: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6047: 	    my $key = $1.':keys:'.$2;
                   6048: 	    $allitems{$key} .= $3.':';
                   6049: 	}
1.800     albertel 6050: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6051:     }
1.800     albertel 6052:     foreach my $item (keys(%allitems)) {
                   6053: 	$allitems{$item} =~ s/\:$//;
                   6054: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6055:     }
                   6056:     $items=~s/\&$//;
                   6057:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6058: }
                   6059: 
1.47      www      6060: # ------------------------------------------------------ critical put interface
                   6061: 
                   6062: sub cput {
1.134     albertel 6063:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6064:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6065:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6066:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6067:    my $items='';
1.800     albertel 6068:    foreach my $item (keys(%$storehash)) {
                   6069:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6070:    }
1.47      www      6071:    $items=~s/\&$//;
1.134     albertel 6072:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6073: }
                   6074: 
                   6075: # -------------------------------------------------------------- eget interface
                   6076: 
                   6077: sub eget {
1.133     albertel 6078:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6079:    my $items='';
1.800     albertel 6080:    foreach my $item (@$storearr) {
                   6081:        $items.=&escape($item).'&';
1.191     harris41 6082:    }
1.12      www      6083:    $items=~s/\&$//;
1.620     albertel 6084:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6085:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6086:    my $uhome=&homeserver($uname,$udomain);
                   6087:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6088:    my @pairs=split(/\&/,$rep);
                   6089:    my %returnhash=();
1.42      www      6090:    my $i=0;
1.800     albertel 6091:    foreach my $item (@$storearr) {
                   6092:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6093:       $i++;
1.191     harris41 6094:    }
1.12      www      6095:    return %returnhash;
                   6096: }
                   6097: 
1.667     albertel 6098: # ------------------------------------------------------------ tmpput interface
                   6099: sub tmpput {
1.802     raeburn  6100:     my ($storehash,$server,$context)=@_;
1.667     albertel 6101:     my $items='';
1.800     albertel 6102:     foreach my $item (keys(%$storehash)) {
                   6103: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6104:     }
                   6105:     $items=~s/\&$//;
1.802     raeburn  6106:     if (defined($context)) {
                   6107:         $items .= ':'.&escape($context);
                   6108:     }
1.667     albertel 6109:     return &reply("tmpput:$items",$server);
                   6110: }
                   6111: 
                   6112: # ------------------------------------------------------------ tmpget interface
                   6113: sub tmpget {
1.688     albertel 6114:     my ($token,$server)=@_;
                   6115:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6116:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6117:     my %returnhash;
                   6118:     foreach my $item (split(/\&/,$rep)) {
                   6119: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6120:         next if ($key =~ /^error: 2 /);
1.667     albertel 6121: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6122:     }
                   6123:     return %returnhash;
                   6124: }
                   6125: 
1.1113    raeburn  6126: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6127: sub tmpdel {
                   6128:     my ($token,$server)=@_;
                   6129:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6130:     return &reply("tmpdel:$token",$server);
                   6131: }
                   6132: 
1.1172.2.13  raeburn  6133: # ------------------------------------------------------------ get_timebased_id
                   6134: 
                   6135: sub get_timebased_id {
                   6136:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6137:         $maxtries) = @_;
                   6138:     my ($newid,$error,$dellock);
                   6139:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6140:         return ('','ok','invalid call to get suffix');
                   6141:     }
                   6142: 
                   6143: # set defaults for any optional args for which values were not supplied
                   6144:     if ($who eq '') {
                   6145:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6146:     }
                   6147:     if (!$locktries) {
                   6148:         $locktries = 3;
                   6149:     }
                   6150:     if (!$maxtries) {
                   6151:         $maxtries = 10;
                   6152:     }
                   6153: 
                   6154:     if (($cdom eq '') || ($cnum eq '')) {
                   6155:         if ($env{'request.course.id'}) {
                   6156:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6157:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6158:         }
                   6159:         if (($cdom eq '') || ($cnum eq '')) {
                   6160:             return ('','ok','call to get suffix not in course context');
                   6161:         }
                   6162:     }
                   6163: 
                   6164: # construct locking item
                   6165:     my $lockhash = {
                   6166:                       $prefix."\0".'locked_'.$keyid => $who,
                   6167:                    };
                   6168:     my $tries = 0;
                   6169: 
                   6170: # attempt to get lock on nohist_$namespace file
                   6171:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6172:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6173:         $tries ++;
                   6174:         sleep 1;
                   6175:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6176:     }
                   6177: 
                   6178: # attempt to get unique identifier, based on current timestamp
                   6179:     if ($gotlock eq 'ok') {
                   6180:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6181:         my $id = time;
                   6182:         $newid = $id;
1.1172.2.56  raeburn  6183:         if ($idtype eq 'addcode') {
                   6184:             $newid .= &sixnum_code();
                   6185:         }
1.1172.2.13  raeburn  6186:         my $idtries = 0;
                   6187:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6188:             if ($idtype eq 'concat') {
                   6189:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6190:             } elsif ($idtype eq 'addcode') {
                   6191:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6192:             } else {
                   6193:                 $newid ++;
                   6194:             }
                   6195:             $idtries ++;
                   6196:         }
                   6197:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6198:             my %new_item =  (
                   6199:                               $prefix."\0".$newid => $who,
                   6200:                             );
                   6201:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6202:                                                  $cdom,$cnum);
                   6203:             if ($putresult ne 'ok') {
                   6204:                 undef($newid);
                   6205:                 $error = 'error saving new item: '.$putresult;
                   6206:             }
                   6207:         } else {
1.1172.2.56  raeburn  6208:              undef($newid);
1.1172.2.13  raeburn  6209:              $error = ('error: no unique suffix available for the new item ');
                   6210:         }
                   6211: #  remove lock
                   6212:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6213:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6214:     } else {
                   6215:         $error = "error: could not obtain lockfile\n";
                   6216:         $dellock = 'ok';
1.1172.2.58  raeburn  6217:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6218:             $dellock = 'nolock';
                   6219:         }
1.1172.2.13  raeburn  6220:     }
                   6221:     return ($newid,$dellock,$error);
                   6222: }
                   6223: 
1.1172.2.56  raeburn  6224: sub sixnum_code {
                   6225:     my $code;
                   6226:     for (0..6) {
                   6227:         $code .= int( rand(9) );
                   6228:     }
                   6229:     return $code;
                   6230: }
                   6231: 
1.765     albertel 6232: # -------------------------------------------------- portfolio access checking
                   6233: 
                   6234: sub portfolio_access {
1.766     albertel 6235:     my ($requrl) = @_;
1.765     albertel 6236:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   6237:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  6238:     if ($result) {
                   6239:         my %setters;
                   6240:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6241:             my ($startblock,$endblock) =
                   6242:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6243:             if ($startblock && $endblock) {
                   6244:                 return 'B';
                   6245:             }
                   6246:         } else {
                   6247:             my ($startblock,$endblock) =
                   6248:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6249:             if ($startblock && $endblock) {
                   6250:                 return 'B';
                   6251:             }
                   6252:         }
                   6253:     }
1.765     albertel 6254:     if ($result eq 'ok') {
1.766     albertel 6255:        return 'F';
1.765     albertel 6256:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6257:        return 'A';
1.765     albertel 6258:     }
1.766     albertel 6259:     return '';
1.765     albertel 6260: }
                   6261: 
                   6262: sub get_portfolio_access {
1.767     albertel 6263:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   6264: 
                   6265:     if (!ref($access_hash)) {
                   6266: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6267: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6268: 						   $file_name);
                   6269: 	$access_hash = $access_controls{$file_name};
                   6270:     }
                   6271: 
1.765     albertel 6272:     my ($public,$guest,@domains,@users,@courses,@groups);
                   6273:     my $now = time;
                   6274:     if (ref($access_hash) eq 'HASH') {
                   6275:         foreach my $key (keys(%{$access_hash})) {
                   6276:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6277:             if ($start > $now) {
                   6278:                 next;
                   6279:             }
                   6280:             if ($end && $end<$now) {
                   6281:                 next;
                   6282:             }
                   6283:             if ($scope eq 'public') {
                   6284:                 $public = $key;
                   6285:                 last;
                   6286:             } elsif ($scope eq 'guest') {
                   6287:                 $guest = $key;
                   6288:             } elsif ($scope eq 'domains') {
                   6289:                 push(@domains,$key);
                   6290:             } elsif ($scope eq 'users') {
                   6291:                 push(@users,$key);
                   6292:             } elsif ($scope eq 'course') {
                   6293:                 push(@courses,$key);
                   6294:             } elsif ($scope eq 'group') {
                   6295:                 push(@groups,$key);
                   6296:             }
                   6297:         }
                   6298:         if ($public) {
                   6299:             return 'ok';
                   6300:         }
                   6301:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6302:             if ($guest) {
                   6303:                 return $guest;
                   6304:             }
                   6305:         } else {
                   6306:             if (@domains > 0) {
                   6307:                 foreach my $domkey (@domains) {
                   6308:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6309:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6310:                             return 'ok';
                   6311:                         }
                   6312:                     }
                   6313:                 }
                   6314:             }
                   6315:             if (@users > 0) {
                   6316:                 foreach my $userkey (@users) {
1.865     raeburn  6317:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6318:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6319:                             if (ref($item) eq 'HASH') {
                   6320:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6321:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6322:                                     return 'ok';
                   6323:                                 }
                   6324:                             }
                   6325:                         }
                   6326:                     } 
1.765     albertel 6327:                 }
                   6328:             }
                   6329:             my %roleshash;
                   6330:             my @courses_and_groups = @courses;
                   6331:             push(@courses_and_groups,@groups); 
                   6332:             if (@courses_and_groups > 0) {
                   6333:                 my (%allgroups,%allroles); 
                   6334:                 my ($start,$end,$role,$sec,$group);
                   6335:                 foreach my $envkey (%env) {
1.1060    raeburn  6336:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6337:                         my $cid = $2.'_'.$3; 
                   6338:                         if ($1 eq 'gr') {
                   6339:                             $group = $4;
                   6340:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6341:                         } else {
                   6342:                             if ($4 eq '') {
                   6343:                                 $sec = 'none';
                   6344:                             } else {
                   6345:                                 $sec = $4;
                   6346:                             }
                   6347:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6348:                         }
1.811     albertel 6349:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6350:                         my $cid = $2.'_'.$3;
                   6351:                         if ($4 eq '') {
                   6352:                             $sec = 'none';
                   6353:                         } else {
                   6354:                             $sec = $4;
                   6355:                         }
                   6356:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6357:                     }
                   6358:                 }
                   6359:                 if (keys(%allroles) == 0) {
                   6360:                     return;
                   6361:                 }
                   6362:                 foreach my $key (@courses_and_groups) {
                   6363:                     my %content = %{$$access_hash{$key}};
                   6364:                     my $cnum = $content{'number'};
                   6365:                     my $cdom = $content{'domain'};
                   6366:                     my $cid = $cdom.'_'.$cnum;
                   6367:                     if (!exists($allroles{$cid})) {
                   6368:                         next;
                   6369:                     }    
                   6370:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6371:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6372:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6373:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6374:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6375:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6376:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6377:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6378:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6379:                                         if (grep/^all$/,@sections) {
                   6380:                                             return 'ok';
                   6381:                                         } else {
                   6382:                                             if (grep/^$sec$/,@sections) {
                   6383:                                                 return 'ok';
                   6384:                                             }
                   6385:                                         }
                   6386:                                     }
                   6387:                                 }
                   6388:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6389:                                     if (grep/^none$/,@groups) {
                   6390:                                         return 'ok';
                   6391:                                     }
                   6392:                                 } else {
                   6393:                                     if (grep/^all$/,@groups) {
                   6394:                                         return 'ok';
                   6395:                                     } 
                   6396:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6397:                                         if (grep/^$group$/,@groups) {
                   6398:                                             return 'ok';
                   6399:                                         }
                   6400:                                     }
                   6401:                                 } 
                   6402:                             }
                   6403:                         }
                   6404:                     }
                   6405:                 }
                   6406:             }
                   6407:             if ($guest) {
                   6408:                 return $guest;
                   6409:             }
                   6410:         }
                   6411:     }
                   6412:     return;
                   6413: }
                   6414: 
                   6415: sub course_group_datechecker {
                   6416:     my ($dates,$now,$status) = @_;
                   6417:     my ($start,$end) = split(/\./,$dates);
                   6418:     if (!$start && !$end) {
                   6419:         return 'ok';
                   6420:     }
                   6421:     if (grep/^active$/,@{$status}) {
                   6422:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6423:             return 'ok';
                   6424:         }
                   6425:     }
                   6426:     if (grep/^previous$/,@{$status}) {
                   6427:         if ($end > $now ) {
                   6428:             return 'ok';
                   6429:         }
                   6430:     }
                   6431:     if (grep/^future$/,@{$status}) {
                   6432:         if ($start > $now) {
                   6433:             return 'ok';
                   6434:         }
                   6435:     }
                   6436:     return; 
                   6437: }
                   6438: 
                   6439: sub parse_portfolio_url {
                   6440:     my ($url) = @_;
                   6441: 
                   6442:     my ($type,$udom,$unum,$group,$file_name);
                   6443:     
1.823     albertel 6444:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6445: 	$type = 1;
                   6446:         $udom = $1;
                   6447:         $unum = $2;
                   6448:         $file_name = $3;
1.823     albertel 6449:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6450: 	$type = 2;
                   6451:         $udom = $1;
                   6452:         $unum = $2;
                   6453:         $group = $3;
                   6454:         $file_name = $3.'/'.$4;
                   6455:     }
                   6456:     if (wantarray) {
                   6457: 	return ($type,$udom,$unum,$file_name,$group);
                   6458:     }
                   6459:     return $type;
                   6460: }
                   6461: 
                   6462: sub is_portfolio_url {
                   6463:     my ($url) = @_;
                   6464:     return scalar(&parse_portfolio_url($url));
                   6465: }
                   6466: 
1.798     raeburn  6467: sub is_portfolio_file {
                   6468:     my ($file) = @_;
1.820     raeburn  6469:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6470:         return 1;
                   6471:     }
                   6472:     return;
                   6473: }
                   6474: 
1.976     raeburn  6475: sub usertools_access {
1.1084    raeburn  6476:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6477:     my ($access,%tools);
                   6478:     if ($context eq '') {
                   6479:         $context = 'tools';
                   6480:     }
                   6481:     if ($context eq 'requestcourses') {
                   6482:         %tools = (
                   6483:                       official   => 1,
                   6484:                       unofficial => 1,
1.1006    raeburn  6485:                       community  => 1,
1.1172.2.37  raeburn  6486:                       textbook   => 1,
1.985     raeburn  6487:                  );
1.1172.2.9  raeburn  6488:     } elsif ($context eq 'requestauthor') {
                   6489:         %tools = (
                   6490:                       requestauthor => 1,
                   6491:                  );
1.985     raeburn  6492:     } else {
                   6493:         %tools = (
                   6494:                       aboutme   => 1,
                   6495:                       blog      => 1,
1.1172.2.6  raeburn  6496:                       webdav    => 1,
1.985     raeburn  6497:                       portfolio => 1,
                   6498:                  );
                   6499:     }
1.976     raeburn  6500:     return if (!defined($tools{$tool}));
                   6501: 
1.1172.2.35  raeburn  6502:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6503:         $udom = $env{'user.domain'};
                   6504:         $uname = $env{'user.name'};
                   6505:     }
                   6506: 
1.978     raeburn  6507:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6508:         if ($action ne 'reload') {
1.985     raeburn  6509:             if ($context eq 'requestcourses') {
                   6510:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6511:             } elsif ($context eq 'requestauthor') {
                   6512:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6513:             } else {
                   6514:                 return $env{'environment.availabletools.'.$tool};
                   6515:             }
                   6516:         }
1.976     raeburn  6517:     }
                   6518: 
1.1172.2.9  raeburn  6519:     my ($toolstatus,$inststatus,$envkey);
                   6520:     if ($context eq 'requestauthor') {
                   6521:         $envkey = $context;
                   6522:     } else {
                   6523:         $envkey = $context.'.'.$tool;
                   6524:     }
1.976     raeburn  6525: 
1.985     raeburn  6526:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6527:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6528:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6529:         $inststatus = $env{'environment.inststatus'};
                   6530:     } else {
1.1084    raeburn  6531:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6532:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6533:             $inststatus = $userenvref->{'inststatus'};
                   6534:         } else {
1.1172.2.9  raeburn  6535:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6536:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6537:             $inststatus = $userenv{'inststatus'};
                   6538:         }
1.976     raeburn  6539:     }
                   6540: 
                   6541:     if ($toolstatus ne '') {
                   6542:         if ($toolstatus) {
                   6543:             $access = 1;
                   6544:         } else {
                   6545:             $access = 0;
                   6546:         }
                   6547:         return $access;
                   6548:     }
                   6549: 
1.1084    raeburn  6550:     my ($is_adv,%domdef);
                   6551:     if (ref($is_advref) eq 'HASH') {
                   6552:         $is_adv = $is_advref->{'is_adv'};
                   6553:     } else {
                   6554:         $is_adv = &is_advanced_user($udom,$uname);
                   6555:     }
                   6556:     if (ref($domdefref) eq 'HASH') {
                   6557:         %domdef = %{$domdefref};
                   6558:     } else {
                   6559:         %domdef = &get_domain_defaults($udom);
                   6560:     }
1.976     raeburn  6561:     if (ref($domdef{$tool}) eq 'HASH') {
                   6562:         if ($is_adv) {
                   6563:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6564:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6565:                     $access = 1;
                   6566:                 } else {
                   6567:                     $access = 0;
                   6568:                 }
                   6569:                 return $access;
                   6570:             }
                   6571:         }
                   6572:         if ($inststatus ne '') {
                   6573:             my ($hasaccess,$hasnoaccess);
                   6574:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6575:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6576:                     if ($domdef{$tool}{$affiliation}) {
                   6577:                         $hasaccess = 1;
                   6578:                     } else {
                   6579:                         $hasnoaccess = 1;
                   6580:                     }
                   6581:                 }
                   6582:             }
                   6583:             if ($hasaccess || $hasnoaccess) {
                   6584:                 if ($hasaccess) {
                   6585:                     $access = 1;
                   6586:                 } elsif ($hasnoaccess) {
                   6587:                     $access = 0; 
                   6588:                 }
                   6589:                 return $access;
                   6590:             }
                   6591:         } else {
                   6592:             if ($domdef{$tool}{'default'} ne '') {
                   6593:                 if ($domdef{$tool}{'default'}) {
                   6594:                     $access = 1;
                   6595:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6596:                     $access = 0;
                   6597:                 }
                   6598:                 return $access;
                   6599:             }
                   6600:         }
                   6601:     } else {
1.1172.2.6  raeburn  6602:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6603:             $access = 1;
                   6604:         } else {
                   6605:             $access = 0;
                   6606:         }
1.976     raeburn  6607:         return $access;
                   6608:     }
                   6609: }
                   6610: 
1.1050    raeburn  6611: sub is_course_owner {
                   6612:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6613:     if (($udom eq '') || ($uname eq '')) {
                   6614:         $udom = $env{'user.domain'};
                   6615:         $uname = $env{'user.name'};
                   6616:     }
                   6617:     unless (($udom eq '') || ($uname eq '')) {
                   6618:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6619:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6620:                 return 1;
                   6621:             } else {
                   6622:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6623:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6624:                     return 1;
                   6625:                 }
                   6626:             }
                   6627:         }
                   6628:     }
                   6629:     return;
                   6630: }
                   6631: 
1.976     raeburn  6632: sub is_advanced_user {
                   6633:     my ($udom,$uname) = @_;
1.1085    raeburn  6634:     if ($udom ne '' && $uname ne '') {
                   6635:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6636:             if (wantarray) {
                   6637:                 return ($env{'user.adv'},$env{'user.author'});
                   6638:             } else {
                   6639:                 return $env{'user.adv'};
                   6640:             }
1.1085    raeburn  6641:         }
                   6642:     }
1.976     raeburn  6643:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6644:     my %allroles;
1.1128    raeburn  6645:     my ($is_adv,$is_author);
1.976     raeburn  6646:     foreach my $role (keys(%roleshash)) {
                   6647:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6648:         my $area = '/'.$tdomain.'/'.$trest;
                   6649:         if ($sec ne '') {
                   6650:             $area .= '/'.$sec;
                   6651:         }
                   6652:         if (($area ne '') && ($trole ne '')) {
                   6653:             my $spec=$trole.'.'.$area;
                   6654:             if ($trole =~ /^cr\//) {
                   6655:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6656:             } elsif ($trole ne 'gr') {
                   6657:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6658:             }
1.1128    raeburn  6659:             if ($trole eq 'au') {
                   6660:                 $is_author = 1;
                   6661:             }
1.976     raeburn  6662:         }
                   6663:     }
                   6664:     foreach my $role (keys(%allroles)) {
                   6665:         last if ($is_adv);
                   6666:         foreach my $item (split(/:/,$allroles{$role})) {
                   6667:             if ($item ne '') {
                   6668:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6669:                 if ($privilege eq 'adv') {
                   6670:                     $is_adv = 1;
                   6671:                     last;
                   6672:                 }
                   6673:             }
                   6674:         }
                   6675:     }
1.1128    raeburn  6676:     if (wantarray) {
                   6677:         return ($is_adv,$is_author);
                   6678:     }
1.976     raeburn  6679:     return $is_adv;
                   6680: }
1.798     raeburn  6681: 
1.1035    raeburn  6682: sub check_can_request {
1.1036    raeburn  6683:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6684:     my $canreq = 0;
                   6685:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6686:     my @options = ('approval','validate','autolimit');
                   6687:     my $optregex = join('|',@options);
                   6688:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6689:         foreach my $type (@{$types}) {
                   6690:             if (&usertools_access($env{'user.name'},
                   6691:                                   $env{'user.domain'},
                   6692:                                   $type,undef,'requestcourses')) {
                   6693:                 $canreq ++;
1.1036    raeburn  6694:                 if (ref($request_domains) eq 'HASH') {
                   6695:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6696:                 }
1.1035    raeburn  6697:                 if ($dom eq $env{'user.domain'}) {
                   6698:                     $can_request->{$type} = 1;
                   6699:                 }
                   6700:             }
                   6701:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6702:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6703:                 if (@curr > 0) {
1.1036    raeburn  6704:                     foreach my $item (@curr) {
                   6705:                         if (ref($request_domains) eq 'HASH') {
                   6706:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6707:                             if ($otherdom ne '') {
                   6708:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6709:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6710:                                         push(@{$request_domains->{$type}},$otherdom);
                   6711:                                     }
                   6712:                                 } else {
                   6713:                                     push(@{$request_domains->{$type}},$otherdom);
                   6714:                                 }
                   6715:                             }
                   6716:                         }
                   6717:                     }
                   6718:                     unless($dom eq $env{'user.domain'}) {
                   6719:                         $canreq ++;
1.1035    raeburn  6720:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6721:                             $can_request->{$type} = 1;
                   6722:                         }
                   6723:                     }
                   6724:                 }
                   6725:             }
                   6726:         }
                   6727:     }
                   6728:     return $canreq;
                   6729: }
                   6730: 
1.341     www      6731: # ---------------------------------------------- Custom access rule evaluation
                   6732: 
                   6733: sub customaccess {
                   6734:     my ($priv,$uri)=@_;
1.807     albertel 6735:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6736:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6737:     $udom = &LONCAPA::clean_domain($udom);
                   6738:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6739:     my $access=0;
1.800     albertel 6740:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6741: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6742: 	if ($type eq 'user') {
                   6743: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6744: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6745: 		if ($tdom) {
                   6746: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6747: 		}
1.896     albertel 6748: 		if ($tuname) {
                   6749: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6750: 		}
                   6751: 		$access=($effect eq 'allow');
                   6752: 		last;
                   6753: 	    }
                   6754: 	} else {
                   6755: 	    if ($role) {
                   6756: 		if ($role ne $urole) { next; }
                   6757: 	    }
                   6758: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6759: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6760: 		if ($tdom) {
                   6761: 		    if ($tdom ne $udom) { next; }
                   6762: 		}
                   6763: 		if ($tcrs) {
                   6764: 		    if ($tcrs ne $ucrs) { next; }
                   6765: 		}
                   6766: 		if ($tsec) {
                   6767: 		    if ($tsec ne $usec) { next; }
                   6768: 		}
                   6769: 		$access=($effect eq 'allow');
                   6770: 		last;
                   6771: 	    }
                   6772: 	    if ($realm eq '' && $role eq '') {
                   6773: 		$access=($effect eq 'allow');
                   6774: 	    }
1.402     bowersj2 6775: 	}
1.341     www      6776:     }
                   6777:     return $access;
                   6778: }
                   6779: 
1.103     harris41 6780: # ------------------------------------------------- Check for a user privilege
1.12      www      6781: 
                   6782: sub allowed {
1.1172.2.65  raeburn  6783:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6784:     my $ver_orguri=$uri;
1.439     www      6785:     $uri=&deversion($uri);
1.152     www      6786:     my $orguri=$uri;
1.52      www      6787:     $uri=&declutter($uri);
1.809     raeburn  6788: 
1.810     raeburn  6789:     if ($priv eq 'evb') {
                   6790: # Evade communication block restrictions for specified role in a course
                   6791:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6792:             return $1;
                   6793:         } else {
                   6794:             return;
                   6795:         }
                   6796:     }
                   6797: 
1.620     albertel 6798:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6799: # Free bre access to adm and meta resources
1.775     albertel 6800:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6801: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6802: 	&& ($priv eq 'bre')) {
1.14      www      6803: 	return 'F';
1.159     www      6804:     }
                   6805: 
1.545     banghart 6806: # Free bre access to user's own portfolio contents
1.714     raeburn  6807:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6808:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6809: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6810:         my %setters;
                   6811:         my ($startblock,$endblock) = 
                   6812:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6813:         if ($startblock && $endblock) {
                   6814:             return 'B';
                   6815:         } else {
                   6816:             return 'F';
                   6817:         }
1.545     banghart 6818:     }
                   6819: 
1.762     raeburn  6820: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6821:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6822:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6823:         if (exists($env{'request.course.id'})) {
                   6824:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6825:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6826:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6827:                 my $courseprivid=$env{'request.course.id'};
                   6828:                 $courseprivid=~s/\_/\//;
                   6829:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6830:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6831:                     return $1; 
1.762     raeburn  6832:                 } else {
                   6833:                     if ($env{'request.course.sec'}) {
                   6834:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6835:                     }
                   6836:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6837:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6838:                         return $2;
                   6839:                     }
1.714     raeburn  6840:                 }
                   6841:             }
                   6842:         }
                   6843:     }
                   6844: 
1.159     www      6845: # Free bre to public access
                   6846: 
                   6847:     if ($priv eq 'bre') {
1.238     www      6848:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6849: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6850:            return 'F'; 
                   6851:         }
1.238     www      6852:         if ($copyright eq 'priv') {
                   6853:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6854: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6855: 		return '';
                   6856:             }
                   6857:         }
                   6858:         if ($copyright eq 'domain') {
                   6859:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6860: 	    unless (($env{'user.domain'} eq $1) ||
                   6861:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6862: 		return '';
                   6863:             }
1.262     matthew  6864:         }
1.620     albertel 6865:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6866:             # Library role, so allow browsing of resources in this domain.
                   6867:             return 'F';
1.238     www      6868:         }
1.341     www      6869:         if ($copyright eq 'custom') {
                   6870: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6871:         }
1.14      www      6872:     }
1.264     matthew  6873:     # Domain coordinator is trying to create a course
1.620     albertel 6874:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6875:         # uri is the requested domain in this case.
                   6876:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6877:         # a role of dc for the domain in question.
1.620     albertel 6878:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6879:     }
1.29      www      6880: 
1.52      www      6881:     my $thisallowed='';
                   6882:     my $statecond=0;
                   6883:     my $courseprivid='';
                   6884: 
1.1039    raeburn  6885:     my $ownaccess;
1.1043    raeburn  6886:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6887:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6888:         if ($uri eq '') {
                   6889:             $ownaccess = 1;
                   6890:         } else {
                   6891:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6892:                 my $udom = $env{'user.domain'};
                   6893:                 my $uname = $env{'user.name'};
                   6894:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6895:                     $ownaccess = 1;
1.1040    raeburn  6896:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6897:                     unless ($uri =~ m{\.\./}) {
                   6898:                         $ownaccess = 1;
                   6899:                     }
                   6900:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6901:                     my $now = time;
                   6902:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6903:                         my $adom = $1;
                   6904:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6905:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6906:                                 my ($start,$end) = split('.',$env{$key});
                   6907:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6908:                                     $ownaccess = 1;
                   6909:                                     last;
                   6910:                                 }
                   6911:                             }
                   6912:                         }
                   6913:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6914:                         my $adom = $1;
                   6915:                         my $aname = $2;
1.1042    raeburn  6916:                         foreach my $role ('ca','aa') { 
                   6917:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6918:                                 my ($start,$end) =
                   6919:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6920:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6921:                                     $ownaccess = 1;
                   6922:                                     last;
                   6923:                                 }
1.1039    raeburn  6924:                             }
                   6925:                         }
                   6926:                     }
                   6927:                 }
                   6928:             }
                   6929:         }
                   6930:     }
                   6931: 
1.52      www      6932: # Course
                   6933: 
1.620     albertel 6934:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6935:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6936:             $thisallowed.=$1;
                   6937:         }
1.52      www      6938:     }
1.29      www      6939: 
1.52      www      6940: # Domain
                   6941: 
1.620     albertel 6942:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6943:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6944:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6945:             $thisallowed.=$1;
                   6946:         }
1.12      www      6947:     }
1.52      www      6948: 
1.1141    raeburn  6949: # User who is not author or co-author might still be able to edit
                   6950: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6951:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6952:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6953:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6954:             $thisallowed.=$1;
                   6955:         }
                   6956:     }
                   6957: 
1.52      www      6958: # Course: uri itself is a course
1.66      www      6959:     my $courseuri=$uri;
                   6960:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6961:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6962: 
1.620     albertel 6963:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6964:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6965:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6966:             $thisallowed.=$1;
                   6967:         }
1.12      www      6968:     }
1.29      www      6969: 
1.665     albertel 6970: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6971: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6972:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6973: 	$thisallowed='';
1.671     raeburn  6974:         my ($match)=&is_on_map($uri);
                   6975:         if ($match) {
                   6976:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6977:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  6978:                 my $value = $1;
                   6979:                 if ($noblockcheck) {
                   6980:                     $thisallowed.=$value;
1.1162    raeburn  6981:                 } else {
1.1172.2.65  raeburn  6982:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6983:                     if (@blockers > 0) {
                   6984:                         $thisallowed = 'B';
                   6985:                     } else {
                   6986:                         $thisallowed.=$value;
                   6987:                     }
1.1162    raeburn  6988:                 }
1.671     raeburn  6989:             }
                   6990:         } else {
1.705     albertel 6991:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6992:             if ($refuri) {
                   6993:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6994:                     $thisallowed='F';
1.671     raeburn  6995:                 } else {
                   6996:                     $refuri=&declutter($refuri);
                   6997:                     my ($match) = &is_on_map($refuri);
                   6998:                     if ($match) {
1.1172.2.65  raeburn  6999:                         if ($noblockcheck) {
1.1162    raeburn  7000:                             $thisallowed='F';
1.1172.2.65  raeburn  7001:                         } else {
                   7002:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7003:                             if (@blockers > 0) {
                   7004:                                 $thisallowed = 'B';
                   7005:                             } else {
                   7006:                                 $thisallowed='F';
                   7007:                             }
1.1162    raeburn  7008:                         }
1.671     raeburn  7009:                     }
1.669     raeburn  7010:                 }
1.671     raeburn  7011:             }
                   7012:         }
1.314     www      7013:     }
1.492     albertel 7014: 
1.766     albertel 7015:     if ($priv eq 'bre'
                   7016: 	&& $thisallowed ne 'F' 
                   7017: 	&& $thisallowed ne '2'
                   7018: 	&& &is_portfolio_url($uri)) {
                   7019: 	$thisallowed = &portfolio_access($uri);
                   7020:     }
                   7021:     
1.52      www      7022: # Full access at system, domain or course-wide level? Exit.
1.29      www      7023:     if ($thisallowed=~/F/) {
                   7024: 	return 'F';
                   7025:     }
                   7026: 
1.52      www      7027: # If this is generating or modifying users, exit with special codes
1.29      www      7028: 
1.643     www      7029:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7030: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7031: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7032: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7033: 	    unless ($auname) { return $thisallowed; }
                   7034: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7035: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7036: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7037: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7038: 	}
1.52      www      7039: 	return $thisallowed;
                   7040:     }
                   7041: #
1.103     harris41 7042: # Gathered so far: system, domain and course wide privileges
1.52      www      7043: #
                   7044: # Course: See if uri or referer is an individual resource that is part of 
                   7045: # the course
                   7046: 
1.620     albertel 7047:     if ($env{'request.course.id'}) {
1.232     www      7048: 
1.620     albertel 7049:        $courseprivid=$env{'request.course.id'};
                   7050:        if ($env{'request.course.sec'}) {
                   7051:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7052:        }
                   7053:        $courseprivid=~s/\_/\//;
                   7054:        my $checkreferer=1;
1.232     www      7055:        my ($match,$cond)=&is_on_map($uri);
                   7056:        if ($match) {
                   7057:            $statecond=$cond;
1.620     albertel 7058:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7059:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7060:                my $value = $1;
                   7061:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7062:                    if ($noblockcheck) {
1.1162    raeburn  7063:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7064:                    } else {
                   7065:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7066:                        if (@blockers > 0) {
                   7067:                            $thisallowed = 'B';
                   7068:                        } else {
                   7069:                            $thisallowed.=$value;
                   7070:                        }
1.1162    raeburn  7071:                    }
                   7072:                } else {
                   7073:                    $thisallowed.=$value;
                   7074:                }
1.52      www      7075:                $checkreferer=0;
                   7076:            }
1.29      www      7077:        }
1.83      www      7078:        
1.148     www      7079:        if ($checkreferer) {
1.620     albertel 7080: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7081:             unless ($refuri) {
1.800     albertel 7082:                 foreach my $key (keys(%env)) {
                   7083: 		    if ($key=~/^httpref\..*\*/) {
                   7084: 			my $pattern=$key;
1.156     www      7085:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7086:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7087:                         $pattern=~s/\//\\\//g;
1.152     www      7088:                         if ($orguri=~/$pattern/) {
1.800     albertel 7089: 			    $refuri=$env{$key};
1.148     www      7090:                         }
                   7091:                     }
1.191     harris41 7092:                 }
1.148     www      7093:             }
1.232     www      7094: 
1.148     www      7095:          if ($refuri) { 
1.152     www      7096: 	  $refuri=&declutter($refuri);
1.232     www      7097:           my ($match,$cond)=&is_on_map($refuri);
                   7098:             if ($match) {
                   7099:               my $refstatecond=$cond;
1.620     albertel 7100:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7101:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7102:                   my $value = $1;
                   7103:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7104:                       if ($noblockcheck) {
1.1162    raeburn  7105:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7106:                       } else {
                   7107:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7108:                           if (@blockers > 0) {
                   7109:                               $thisallowed = 'B';
                   7110:                           } else {
                   7111:                               $thisallowed.=$value;
                   7112:                           }
1.1162    raeburn  7113:                       }
                   7114:                   } else {
                   7115:                       $thisallowed.=$value;
                   7116:                   }
1.53      www      7117:                   $uri=$refuri;
                   7118:                   $statecond=$refstatecond;
1.52      www      7119:               }
                   7120:           }
1.148     www      7121:         }
1.29      www      7122:        }
1.52      www      7123:    }
1.29      www      7124: 
1.52      www      7125: #
1.103     harris41 7126: # Gathered now: all privileges that could apply, and condition number
1.52      www      7127: # 
                   7128: #
                   7129: # Full or no access?
                   7130: #
1.29      www      7131: 
1.52      www      7132:     if ($thisallowed=~/F/) {
                   7133: 	return 'F';
                   7134:     }
1.29      www      7135: 
1.52      www      7136:     unless ($thisallowed) {
                   7137:         return '';
                   7138:     }
1.29      www      7139: 
1.52      www      7140: # Restrictions exist, deal with them
                   7141: #
                   7142: #   C:according to course preferences
                   7143: #   R:according to resource settings
                   7144: #   L:unless locked
                   7145: #   X:according to user session state
                   7146: #
                   7147: 
                   7148: # Possibly locked functionality, check all courses
1.54      www      7149: # Locks might take effect only after 10 minutes cache expiration for other
                   7150: # courses, and 2 minutes for current course
1.52      www      7151: 
                   7152:     my $envkey;
                   7153:     if ($thisallowed=~/L/) {
1.1000    raeburn  7154:         foreach $envkey (keys(%env)) {
1.54      www      7155:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7156:                my $courseid=$2;
                   7157:                my $roleid=$1.'.'.$2;
1.92      www      7158:                $courseid=~s/^\///;
1.54      www      7159:                my $expiretime=600;
1.620     albertel 7160:                if ($env{'request.role'} eq $roleid) {
1.54      www      7161: 		  $expiretime=120;
                   7162:                }
                   7163: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7164:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7165:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7166: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7167:                }
1.620     albertel 7168:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7169:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7170: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7171:                        &log($env{'user.domain'},$env{'user.name'},
                   7172:                             $env{'user.home'},
1.57      www      7173:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7174:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7175:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7176: 		       return '';
                   7177:                    }
                   7178:                }
1.620     albertel 7179:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7180:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7181: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7182:                        &log($env{'user.domain'},$env{'user.name'},
                   7183:                             $env{'user.home'},
1.57      www      7184:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7185:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7186:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7187: 		       return '';
                   7188:                    }
                   7189:                }
                   7190: 	   }
1.29      www      7191:        }
1.52      www      7192:     }
                   7193:    
                   7194: #
                   7195: # Rest of the restrictions depend on selected course
                   7196: #
                   7197: 
1.620     albertel 7198:     unless ($env{'request.course.id'}) {
1.766     albertel 7199: 	if ($thisallowed eq 'A') {
                   7200: 	    return 'A';
1.814     raeburn  7201:         } elsif ($thisallowed eq 'B') {
                   7202:             return 'B';
1.766     albertel 7203: 	} else {
                   7204: 	    return '1';
                   7205: 	}
1.52      www      7206:     }
1.29      www      7207: 
1.52      www      7208: #
                   7209: # Now user is definitely in a course
                   7210: #
1.53      www      7211: 
                   7212: 
                   7213: # Course preferences
                   7214: 
                   7215:    if ($thisallowed=~/C/) {
1.620     albertel 7216:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7217:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7218:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7219: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7220: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7221: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7222: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7223: 			$env{'request.course.id'});
                   7224: 	   }
1.237     www      7225:            return '';
                   7226:        }
                   7227: 
1.620     albertel 7228:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7229: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7230: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7231: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7232: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7233: 			$env{'request.course.id'});
                   7234: 	   }
1.54      www      7235:            return '';
                   7236:        }
1.53      www      7237:    }
                   7238: 
                   7239: # Resource preferences
                   7240: 
                   7241:    if ($thisallowed=~/R/) {
1.620     albertel 7242:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7243:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7244: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7245: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7246: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7247: 	   }
                   7248: 	   return '';
1.54      www      7249:        }
1.53      www      7250:    }
1.30      www      7251: 
1.246     www      7252: # Restricted by state or randomout?
1.30      www      7253: 
1.52      www      7254:    if ($thisallowed=~/X/) {
1.620     albertel 7255:       if ($env{'acc.randomout'}) {
1.579     albertel 7256: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7257:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7258:             return ''; 
                   7259:          }
1.247     www      7260:       }
                   7261:       if (&condval($statecond)) {
1.52      www      7262: 	 return '2';
                   7263:       } else {
                   7264:          return '';
                   7265:       }
                   7266:    }
1.30      www      7267: 
1.766     albertel 7268:     if ($thisallowed eq 'A') {
                   7269: 	return 'A';
1.814     raeburn  7270:     } elsif ($thisallowed eq 'B') {
                   7271:         return 'B';
1.766     albertel 7272:     }
1.52      www      7273:    return 'F';
1.232     www      7274: }
1.1162    raeburn  7275: 
1.1172.2.13  raeburn  7276: # ------------------------------------------- Check construction space access
                   7277: 
                   7278: sub constructaccess {
                   7279:     my ($url,$setpriv)=@_;
                   7280: 
                   7281: # We do not allow editing of previous versions of files
                   7282:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7283: 
                   7284: # Get username and domain from URL
                   7285:     my ($ownername,$ownerdomain,$ownerhome);
                   7286: 
                   7287:     ($ownerdomain,$ownername) =
                   7288:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7289: 
                   7290: # The URL does not really point to any authorspace, forget it
                   7291:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7292: 
                   7293: # Now we need to see if the user has access to the authorspace of
                   7294: # $ownername at $ownerdomain
                   7295: 
                   7296:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7297: # Real author for this?
                   7298:        $ownerhome = $env{'user.home'};
                   7299:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7300:           return ($ownername,$ownerdomain,$ownerhome);
                   7301:        }
                   7302:     } else {
                   7303: # Co-author for this?
                   7304:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7305:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7306:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7307:             return ($ownername,$ownerdomain,$ownerhome);
                   7308:         }
                   7309:     }
                   7310: 
                   7311: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7312: # we might as well leave
                   7313:    unless ($setpriv) { return ''; }
                   7314: 
                   7315: # Backdoor access?
                   7316:     my $allowed=&allowed('eco',$ownerdomain);
                   7317: # Nope
                   7318:     unless ($allowed) { return ''; }
                   7319: # Looks like we may have access, but could be locked by the owner of the construction space
                   7320:     if ($allowed eq 'U') {
                   7321:         my %blocked=&get('environment',['domcoord.author'],
                   7322:                          $ownerdomain,$ownername);
                   7323: # Is blocked by owner
                   7324:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7325:     }
                   7326:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7327: # Grant temporary access
                   7328:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7329:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7330:         if (!$update) { $update = $then; }
                   7331:         my $refresh=$env{'user.refresh.time'};
                   7332:         if (!$refresh) { $refresh = $update; }
                   7333:         my $now = time;
                   7334:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7335:                            $now,'ca','constructaccess');
                   7336:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7337:         return($ownername,$ownerdomain,$ownerhome);
                   7338:     }
                   7339: # No business here
                   7340:     return '';
                   7341: }
                   7342: 
1.1172.2.66  raeburn  7343: # ----------------------------------------------------------- Content Blocking
                   7344: 
                   7345: {
                   7346: # Caches for faster Course Contents display where content blocking
                   7347: # is in operation (i.e., interval param set) for timed quiz.
                   7348: #
                   7349: # User for whom data are being temporarily cached.
                   7350: my $cacheduser='';
                   7351: # Cached blockers for this user (a hash of blocking items).
                   7352: my %cachedblockers=();
                   7353: # When the data were last cached.
                   7354: my $cachedlast='';
                   7355: 
                   7356: sub load_all_blockers {
                   7357:     my ($uname,$udom,$blocks)=@_;
                   7358:     if (($uname ne '') && ($udom ne '')) {
                   7359:         if (($cacheduser eq $uname.':'.$udom) &&
                   7360:             (abs($cachedlast-time)<5)) {
                   7361:             return;
                   7362:         }
                   7363:     }
                   7364:     $cachedlast=time;
                   7365:     $cacheduser=$uname.':'.$udom;
                   7366:     %cachedblockers = &get_commblock_resources($blocks);
                   7367: }
                   7368: 
1.1162    raeburn  7369: sub get_comm_blocks {
                   7370:     my ($cdom,$cnum) = @_;
                   7371:     if ($cdom eq '' || $cnum eq '') {
                   7372:         return unless ($env{'request.course.id'});
                   7373:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7374:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7375:     }
                   7376:     my %commblocks;
                   7377:     my $hashid=$cdom.'_'.$cnum;
                   7378:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7379:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7380:         %commblocks = %{$blocksref};
                   7381:     } else {
                   7382:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7383:         my $cachetime = 600;
                   7384:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7385:     }
                   7386:     return %commblocks;
                   7387: }
                   7388: 
1.1172.2.66  raeburn  7389: sub get_commblock_resources {
                   7390:     my ($blocks) = @_;
                   7391:     my %blockers = ();
                   7392:     return %blockers unless ($env{'request.course.id'});
                   7393:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7394:     my %commblocks;
                   7395:     if (ref($blocks) eq 'HASH') {
                   7396:         %commblocks = %{$blocks};
                   7397:     } else {
                   7398:         %commblocks = &get_comm_blocks();
                   7399:     }
1.1172.2.66  raeburn  7400:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  7401:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  7402:     return %blockers unless (ref($navmap));
                   7403:     my $now = time;
1.1162    raeburn  7404:     foreach my $block (keys(%commblocks)) {
                   7405:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7406:             my ($start,$end) = ($1,$2);
                   7407:             if ($start <= $now && $end >= $now) {
                   7408:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7409:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7410:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  7411:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7412:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  7413:                             }
                   7414:                         }
                   7415:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  7416:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7417:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7418:                             }
                   7419:                         }
                   7420:                     }
                   7421:                 }
                   7422:             }
                   7423:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7424:             my $item = $1;
1.1163    raeburn  7425:             my @to_test;
1.1162    raeburn  7426:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7427:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  7428:                     my @interval;
                   7429:                     my $type = 'map';
                   7430:                     if ($item eq 'course') {
                   7431:                         $type = 'course';
                   7432:                         @interval=&EXT("resource.0.interval");
                   7433:                     } else {
                   7434:                         if ($item =~ /___\d+___/) {
                   7435:                             $type = 'resource';
                   7436:                             @interval=&EXT("resource.0.interval",$item);
                   7437:                             if (ref($navmap)) {
                   7438:                                 my $res = $navmap->getBySymb($item);
                   7439:                                 push(@to_test,$res);
                   7440:                             }
1.1162    raeburn  7441:                         } else {
1.1172.2.66  raeburn  7442:                             my $mapsymb = &symbread($item,1);
                   7443:                             if ($mapsymb) {
                   7444:                                 if (ref($navmap)) {
                   7445:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7446:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7447:                                     foreach my $res (@to_test) {
                   7448:                                         my $symb = $res->symb();
                   7449:                                         next if ($symb eq $mapsymb);
                   7450:                                         if ($symb ne '') {
                   7451:                                             @interval=&EXT("resource.0.interval",$symb);
                   7452:                                             if ($interval[1] eq 'map') {
                   7453:                                                 last;
1.1162    raeburn  7454:                                             }
                   7455:                                         }
                   7456:                                     }
                   7457:                                 }
                   7458:                             }
                   7459:                         }
1.1172.2.66  raeburn  7460:                     }
                   7461:                     if ($interval[0] =~ /^\d+$/) {
                   7462:                         my $first_access;
                   7463:                         if ($type eq 'resource') {
                   7464:                             $first_access=&get_first_access($interval[1],$item);
                   7465:                         } elsif ($type eq 'map') {
                   7466:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7467:                         } else {
                   7468:                             $first_access=&get_first_access($interval[1]);
                   7469:                         }
                   7470:                         if ($first_access) {
                   7471:                             my $timesup = $first_access+$interval[0];
                   7472:                             if ($timesup > $now) {
                   7473:                                 my $activeblock;
                   7474:                                 foreach my $res (@to_test) {
                   7475:                                     if ($res->answerable()) {
                   7476:                                         $activeblock = 1;
                   7477:                                         last;
                   7478:                                     }
                   7479:                                 }
                   7480:                                 if ($activeblock) {
                   7481:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7482:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7483:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7484:                                          }
                   7485:                                     }
                   7486:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7487:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7488:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7489:                                         }
1.1162    raeburn  7490:                                     }
                   7491:                                 }
                   7492:                             }
                   7493:                         }
                   7494:                     }
                   7495:                 }
                   7496:             }
                   7497:         }
                   7498:     }
1.1172.2.66  raeburn  7499:     return %blockers;
1.1162    raeburn  7500: }
                   7501: 
1.1172.2.66  raeburn  7502: sub has_comm_blocking {
                   7503:     my ($priv,$symb,$uri,$blocks) = @_;
                   7504:     my @blockers;
                   7505:     return unless ($env{'request.course.id'});
                   7506:     return unless ($priv eq 'bre');
                   7507:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7508:     return if ($env{'request.state'} eq 'construct');
                   7509:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7510:     return unless (keys(%cachedblockers) > 0);
                   7511:     my (%possibles,@symbs);
                   7512:     if (!$symb) {
                   7513:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7514:     }
1.1172.2.66  raeburn  7515:     if ($symb) {
                   7516:         @symbs = ($symb);
                   7517:     } elsif (keys(%possibles)) {
                   7518:         @symbs = keys(%possibles);
                   7519:     }
                   7520:     my $noblock;
                   7521:     foreach my $symb (@symbs) {
                   7522:         last if ($noblock);
                   7523:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7524:         foreach my $block (keys(%cachedblockers)) {
                   7525:             if ($block =~ /^firstaccess____(.+)$/) {
                   7526:                 my $item = $1;
                   7527:                 if (($item eq $map) || ($item eq $symb)) {
                   7528:                     $noblock = 1;
                   7529:                     last;
                   7530:                 }
1.1162    raeburn  7531:             }
1.1172.2.66  raeburn  7532:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7533:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7534:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7535:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7536:                             push(@blockers,$block);
                   7537:                         }
                   7538:                     }
                   7539:                 }
                   7540:             }
                   7541:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7542:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7543:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7544:                         push(@blockers,$block);
                   7545:                     }
                   7546:                 }
1.1162    raeburn  7547:             }
                   7548:         }
                   7549:     }
1.1172.2.66  raeburn  7550:     return if ($noblock);
                   7551:     return @blockers;
                   7552: }
1.1162    raeburn  7553: }
                   7554: 
1.1172.2.66  raeburn  7555: # -------------------------------- Deversion and split uri into path an filename
                   7556: 
1.1133    foxr     7557: #
1.1172.2.66  raeburn  7558: #   Removes the version from a URI and
1.1133    foxr     7559: #   splits it in to its filename and path to the filename.
                   7560: #   Seems like File::Basename could have done this more clearly.
                   7561: #   Parameters:
                   7562: #      $uri   - input URI
                   7563: #   Returns:
                   7564: #     Two element list consisting of 
                   7565: #     $pathname  - the URI up to and excluding the trailing /
                   7566: #     $filename  - The part of the URI following the last /
                   7567: #  NOTE:
                   7568: #    Another realization of this is simply:
                   7569: #    use File::Basename;
                   7570: #    ...
                   7571: #    $uri = shift;
                   7572: #    $filename = basename($uri);
                   7573: #    $path     = dirname($uri);
                   7574: #    return ($filename, $path);
                   7575: #
                   7576: #     The implementation below is probably faster however.
                   7577: #
1.710     albertel 7578: sub split_uri_for_cond {
                   7579:     my $uri=&deversion(&declutter(shift));
                   7580:     my @uriparts=split(/\//,$uri);
                   7581:     my $filename=pop(@uriparts);
                   7582:     my $pathname=join('/',@uriparts);
                   7583:     return ($pathname,$filename);
                   7584: }
1.232     www      7585: # --------------------------------------------------- Is a resource on the map?
                   7586: 
                   7587: sub is_on_map {
1.710     albertel 7588:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7589:     #Trying to find the conditional for the file
1.620     albertel 7590:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7591: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7592:     if ($match) {
1.289     bowersj2 7593: 	return (1,$1);
                   7594:     } else {
1.434     www      7595: 	return (0,0);
1.289     bowersj2 7596:     }
1.12      www      7597: }
                   7598: 
1.427     www      7599: # --------------------------------------------------------- Get symb from alias
                   7600: 
                   7601: sub get_symb_from_alias {
                   7602:     my $symb=shift;
                   7603:     my ($map,$resid,$url)=&decode_symb($symb);
                   7604: # Already is a symb
                   7605:     if ($url) { return $symb; }
                   7606: # Must be an alias
                   7607:     my $aliassymb='';
                   7608:     my %bighash;
1.620     albertel 7609:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7610:                             &GDBM_READER(),0640)) {
                   7611:         my $rid=$bighash{'mapalias_'.$symb};
                   7612: 	if ($rid) {
                   7613: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7614: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7615: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7616: 	}
                   7617:         untie %bighash;
                   7618:     }
                   7619:     return $aliassymb;
                   7620: }
                   7621: 
1.12      www      7622: # ----------------------------------------------------------------- Define Role
                   7623: 
                   7624: sub definerole {
                   7625:   if (allowed('mcr','/')) {
                   7626:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7627:     foreach my $role (split(':',$sysrole)) {
                   7628: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7629:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7630:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7631: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7632:                return "refused:s:$crole&$cqual"; 
                   7633:             }
                   7634:         }
1.191     harris41 7635:     }
1.800     albertel 7636:     foreach my $role (split(':',$domrole)) {
                   7637: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7638:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7639:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7640: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7641:                return "refused:d:$crole&$cqual"; 
                   7642:             }
                   7643:         }
1.191     harris41 7644:     }
1.800     albertel 7645:     foreach my $role (split(':',$courole)) {
                   7646: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7647:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7648:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7649: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7650:                return "refused:c:$crole&$cqual"; 
                   7651:             }
                   7652:         }
1.191     harris41 7653:     }
1.620     albertel 7654:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7655:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7656: 	        "rolesdef_$rolename=".
                   7657:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7658:     return reply($command,$env{'user.home'});
1.12      www      7659:   } else {
                   7660:     return 'refused';
                   7661:   }
1.105     harris41 7662: }
                   7663: 
                   7664: # ---------------- Make a metadata query against the network of library servers
                   7665: 
                   7666: sub metadata_query {
1.1172.2.33  raeburn  7667:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7668:     my %rhash;
1.845     albertel 7669:     my %libserv = &all_library();
1.244     matthew  7670:     my @server_list = (defined($server_array) ? @$server_array
                   7671:                                               : keys(%libserv) );
                   7672:     for my $server (@server_list) {
1.1172.2.33  raeburn  7673:         my $domains = '';
                   7674:         if (ref($domains_hash) eq 'HASH') {
                   7675:             $domains = $domains_hash->{$server};    
                   7676:         }
1.118     harris41 7677: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  7678: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7679: 	    $rhash{$server}=$reply;
                   7680: 	}
                   7681: 	else {
                   7682: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  7683: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7684: 			     $server);
                   7685: 	    $rhash{$server}=$reply;
                   7686: 	}
1.112     harris41 7687:     }
1.118     harris41 7688:     return \%rhash;
1.240     www      7689: }
                   7690: 
                   7691: # ----------------------------------------- Send log queries and wait for reply
                   7692: 
                   7693: sub log_query {
                   7694:     my ($uname,$udom,$query,%filters)=@_;
                   7695:     my $uhome=&homeserver($uname,$udom);
                   7696:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7697:     my $uhost=&hostname($uhome);
1.800     albertel 7698:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7699:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7700:                        $uhome);
1.479     albertel 7701:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7702:     return get_query_reply($queryid);
                   7703: }
                   7704: 
1.818     raeburn  7705: # -------------------------- Update MySQL table for portfolio file
                   7706: 
                   7707: sub update_portfolio_table {
1.821     raeburn  7708:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7709:     if ($group ne '') {
                   7710:         $file_name =~s /^\Q$group\E//;
                   7711:     }
1.818     raeburn  7712:     my $homeserver = &homeserver($uname,$udom);
                   7713:     my $queryid=
1.821     raeburn  7714:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7715:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7716:     my $reply = &get_query_reply($queryid);
                   7717:     return $reply;
                   7718: }
                   7719: 
1.899     raeburn  7720: # -------------------------- Update MySQL allusers table
                   7721: 
                   7722: sub update_allusers_table {
                   7723:     my ($uname,$udom,$names) = @_;
                   7724:     my $homeserver = &homeserver($uname,$udom);
                   7725:     my $queryid=
                   7726:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7727:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7728:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7729:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7730:                'generation='.&escape($names->{'generation'}).'%%'.
                   7731:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7732:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7733:     return;
1.899     raeburn  7734: }
                   7735: 
1.508     raeburn  7736: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7737: 
                   7738: sub fetch_enrollment_query {
1.511     raeburn  7739:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7740:     my $homeserver;
1.547     raeburn  7741:     my $maxtries = 1;
1.508     raeburn  7742:     if ($context eq 'automated') {
                   7743:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7744:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7745:     } else {
                   7746:         $homeserver = &homeserver($cnum,$dom);
                   7747:     }
1.838     albertel 7748:     my $host=&hostname($homeserver);
1.506     raeburn  7749:     my $cmd = '';
1.1000    raeburn  7750:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7751:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7752:     }
                   7753:     $cmd =~ s/%%$//;
                   7754:     $cmd = &escape($cmd);
                   7755:     my $query = 'fetchenrollment';
1.620     albertel 7756:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7757:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7758:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7759:         return 'error: '.$queryid;
                   7760:     }
1.506     raeburn  7761:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7762:     my $tries = 1;
                   7763:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7764:         $reply = &get_query_reply($queryid);
                   7765:         $tries ++;
                   7766:     }
1.526     raeburn  7767:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7768:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7769:     } else {
1.901     albertel 7770:         my @responses = split(/:/,$reply);
1.515     raeburn  7771:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7772:             foreach my $line (@responses) {
                   7773:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7774:                 $$replyref{$key} = $value;
                   7775:             }
                   7776:         } else {
1.1117    foxr     7777:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7778:             foreach my $line (@responses) {
                   7779:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7780:                 $$replyref{$key} = $value;
                   7781:                 if ($value > 0) {
1.800     albertel 7782:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7783:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7784:                         my $destname = $pathname.'/'.$filename;
                   7785:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7786:                         if ($xml_classlist =~ /^error/) {
                   7787:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7788:                         } else {
1.506     raeburn  7789:                             if ( open(FILE,">$destname") ) {
                   7790:                                 print FILE &unescape($xml_classlist);
                   7791:                                 close(FILE);
1.526     raeburn  7792:                             } else {
                   7793:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7794:                             }
                   7795:                         }
                   7796:                     }
                   7797:                 }
                   7798:             }
                   7799:         }
                   7800:         return 'ok';
                   7801:     }
                   7802:     return 'error';
                   7803: }
                   7804: 
1.242     www      7805: sub get_query_reply {
                   7806:     my $queryid=shift;
1.1117    foxr     7807:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7808:     my $reply='';
                   7809:     for (1..100) {
                   7810: 	sleep 2;
                   7811:         if (-e $replyfile.'.end') {
1.448     albertel 7812: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7813: 		$reply = join('',<$fh>);
                   7814: 		close($fh);
1.240     www      7815: 	   } else { return 'error: reply_file_error'; }
1.242     www      7816:            return &unescape($reply);
                   7817: 	}
1.240     www      7818:     }
1.242     www      7819:     return 'timeout:'.$queryid;
1.240     www      7820: }
                   7821: 
                   7822: sub courselog_query {
1.241     www      7823: #
                   7824: # possible filters:
                   7825: # url: url or symb
                   7826: # username
                   7827: # domain
                   7828: # action: view, submit, grade
                   7829: # start: timestamp
                   7830: # end: timestamp
                   7831: #
1.240     www      7832:     my (%filters)=@_;
1.620     albertel 7833:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7834:     if ($filters{'url'}) {
                   7835: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7836:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7837:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7838:     }
1.620     albertel 7839:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7840:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7841:     return &log_query($cname,$cdom,'courselog',%filters);
                   7842: }
                   7843: 
                   7844: sub userlog_query {
1.858     raeburn  7845: #
                   7846: # possible filters:
                   7847: # action: log check role
                   7848: # start: timestamp
                   7849: # end: timestamp
                   7850: #
1.240     www      7851:     my ($uname,$udom,%filters)=@_;
                   7852:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7853: }
                   7854: 
1.506     raeburn  7855: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7856: 
                   7857: sub auto_run {
1.508     raeburn  7858:     my ($cnum,$cdom) = @_;
1.876     raeburn  7859:     my $response = 0;
                   7860:     my $settings;
                   7861:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7862:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7863:         $settings = $domconfig{'autoenroll'};
                   7864:         if ($settings->{'run'} eq '1') {
                   7865:             $response = 1;
                   7866:         }
                   7867:     } else {
1.934     raeburn  7868:         my $homeserver;
                   7869:         if (&is_course($cdom,$cnum)) {
                   7870:             $homeserver = &homeserver($cnum,$cdom);
                   7871:         } else {
                   7872:             $homeserver = &domain($cdom,'primary');
                   7873:         }
                   7874:         if ($homeserver ne 'no_host') {
                   7875:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7876:         }
1.876     raeburn  7877:     }
1.506     raeburn  7878:     return $response;
                   7879: }
1.776     albertel 7880: 
1.506     raeburn  7881: sub auto_get_sections {
1.508     raeburn  7882:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7883:     my $homeserver;
                   7884:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7885:         $homeserver = &homeserver($cnum,$cdom);
                   7886:     }
                   7887:     if (!defined($homeserver)) { 
                   7888:         if ($cdom =~ /^$match_domain$/) {
                   7889:             $homeserver = &domain($cdom,'primary');
                   7890:         }
                   7891:     }
                   7892:     my @secs;
                   7893:     if (defined($homeserver)) {
                   7894:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7895:         unless ($response eq 'refused') {
                   7896:             @secs = split(/:/,$response);
                   7897:         }
1.506     raeburn  7898:     }
                   7899:     return @secs;
                   7900: }
1.776     albertel 7901: 
1.506     raeburn  7902: sub auto_new_course {
1.1099    raeburn  7903:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7904:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7905:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7906:     return $response;
                   7907: }
1.776     albertel 7908: 
1.506     raeburn  7909: sub auto_validate_courseID {
1.508     raeburn  7910:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7911:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7912:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7913:     return $response;
                   7914: }
1.776     albertel 7915: 
1.1007    raeburn  7916: sub auto_validate_instcode {
1.1020    raeburn  7917:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7918:     my ($homeserver,$response);
                   7919:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7920:         $homeserver = &homeserver($cnum,$cdom);
                   7921:     }
                   7922:     if (!defined($homeserver)) {
                   7923:         if ($cdom =~ /^$match_domain$/) {
                   7924:             $homeserver = &domain($cdom,'primary');
                   7925:         }
                   7926:     }
1.1065    raeburn  7927:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7928:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7929:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7930:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7931: }
                   7932: 
1.506     raeburn  7933: sub auto_create_password {
1.873     raeburn  7934:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7935:     my ($homeserver,$response);
1.506     raeburn  7936:     my $create_passwd = 0;
                   7937:     my $authchk = '';
1.873     raeburn  7938:     if ($udom =~ /^$match_domain$/) {
                   7939:         $homeserver = &domain($udom,'primary');
                   7940:     }
                   7941:     if ($homeserver eq '') {
                   7942:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7943:             $homeserver = &homeserver($cnum,$cdom);
                   7944:         }
                   7945:     }
                   7946:     if ($homeserver eq '') {
                   7947:         $authchk = 'nodomain';
1.506     raeburn  7948:     } else {
1.873     raeburn  7949:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7950:         if ($response eq 'refused') {
                   7951:             $authchk = 'refused';
                   7952:         } else {
1.901     albertel 7953:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7954:         }
1.506     raeburn  7955:     }
                   7956:     return ($authparam,$create_passwd,$authchk);
                   7957: }
                   7958: 
1.706     raeburn  7959: sub auto_photo_permission {
                   7960:     my ($cnum,$cdom,$students) = @_;
                   7961:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7962:     my ($outcome,$perm_reqd,$conditions) = 
                   7963: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7964:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7965: 	return (undef,undef);
                   7966:     }
1.706     raeburn  7967:     return ($outcome,$perm_reqd,$conditions);
                   7968: }
                   7969: 
                   7970: sub auto_checkphotos {
                   7971:     my ($uname,$udom,$pid) = @_;
                   7972:     my $homeserver = &homeserver($uname,$udom);
                   7973:     my ($result,$resulttype);
                   7974:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7975: 				   &escape($uname).':'.&escape($pid),
                   7976: 				   $homeserver));
1.709     albertel 7977:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7978: 	return (undef,undef);
                   7979:     }
1.706     raeburn  7980:     if ($outcome) {
                   7981:         ($result,$resulttype) = split(/:/,$outcome);
                   7982:     } 
                   7983:     return ($result,$resulttype);
                   7984: }
                   7985: 
                   7986: sub auto_photochoice {
                   7987:     my ($cnum,$cdom) = @_;
                   7988:     my $homeserver = &homeserver($cnum,$cdom);
                   7989:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7990: 						       &escape($cdom),
                   7991: 						       $homeserver)));
1.709     albertel 7992:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7993: 	return (undef,undef);
                   7994:     }
1.706     raeburn  7995:     return ($update,$comment);
                   7996: }
                   7997: 
                   7998: sub auto_photoupdate {
                   7999:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8000:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8001:     my $host=&hostname($homeserver);
1.706     raeburn  8002:     my $cmd = '';
                   8003:     my $maxtries = 1;
1.800     albertel 8004:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8005:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8006:     }
                   8007:     $cmd =~ s/%%$//;
                   8008:     $cmd = &escape($cmd);
                   8009:     my $query = 'institutionalphotos';
                   8010:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8011:     unless ($queryid=~/^\Q$host\E\_/) {
                   8012:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8013:         return 'error: '.$queryid;
                   8014:     }
                   8015:     my $reply = &get_query_reply($queryid);
                   8016:     my $tries = 1;
                   8017:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8018:         $reply = &get_query_reply($queryid);
                   8019:         $tries ++;
                   8020:     }
                   8021:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8022:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8023:     } else {
                   8024:         my @responses = split(/:/,$reply);
                   8025:         my $outcome = shift(@responses); 
                   8026:         foreach my $item (@responses) {
                   8027:             my ($key,$value) = split(/=/,$item);
                   8028:             $$photo{$key} = $value;
                   8029:         }
                   8030:         return $outcome;
                   8031:     }
                   8032:     return 'error';
                   8033: }
                   8034: 
1.521     raeburn  8035: sub auto_instcode_format {
1.793     albertel 8036:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8037: 	$cat_order) = @_;
1.521     raeburn  8038:     my $courses = '';
1.772     raeburn  8039:     my @homeservers;
1.521     raeburn  8040:     if ($caller eq 'global') {
1.841     albertel 8041: 	my %servers = &get_servers($codedom,'library');
                   8042: 	foreach my $tryserver (keys(%servers)) {
                   8043: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8044: 		push(@homeservers,$tryserver);
                   8045: 	    }
1.584     raeburn  8046:         }
1.1022    raeburn  8047:     } elsif ($caller eq 'requests') {
                   8048:         if ($codedom =~ /^$match_domain$/) {
                   8049:             my $chome = &domain($codedom,'primary');
                   8050:             unless ($chome eq 'no_host') {
                   8051:                 push(@homeservers,$chome);
                   8052:             }
                   8053:         }
1.521     raeburn  8054:     } else {
1.772     raeburn  8055:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8056:     }
1.793     albertel 8057:     foreach my $code (keys(%{$instcodes})) {
                   8058:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8059:     }
                   8060:     chop($courses);
1.772     raeburn  8061:     my $ok_response = 0;
                   8062:     my $response;
                   8063:     while (@homeservers > 0 && $ok_response == 0) {
                   8064:         my $server = shift(@homeservers); 
                   8065:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8066:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8067:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8068: 		split(/:/,$response);
1.772     raeburn  8069:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8070:             push(@{$codetitles},&str2array($codetitles_str));
                   8071:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8072:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8073:             $ok_response = 1;
                   8074:         }
                   8075:     }
                   8076:     if ($ok_response) {
1.521     raeburn  8077:         return 'ok';
1.772     raeburn  8078:     } else {
                   8079:         return $response;
1.521     raeburn  8080:     }
                   8081: }
                   8082: 
1.792     raeburn  8083: sub auto_instcode_defaults {
                   8084:     my ($domain,$returnhash,$code_order) = @_;
                   8085:     my @homeservers;
1.841     albertel 8086: 
                   8087:     my %servers = &get_servers($domain,'library');
                   8088:     foreach my $tryserver (keys(%servers)) {
                   8089: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8090: 	    push(@homeservers,$tryserver);
                   8091: 	}
1.792     raeburn  8092:     }
1.841     albertel 8093: 
1.792     raeburn  8094:     my $response;
1.841     albertel 8095:     foreach my $server (@homeservers) {
1.792     raeburn  8096:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8097:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8098: 	
                   8099: 	foreach my $pair (split(/\&/,$response)) {
                   8100: 	    my ($name,$value)=split(/\=/,$pair);
                   8101: 	    if ($name eq 'code_order') {
                   8102: 		@{$code_order} = split(/\&/,&unescape($value));
                   8103: 	    } else {
                   8104: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8105: 	    }
                   8106: 	}
                   8107: 	return 'ok';
1.792     raeburn  8108:     }
1.841     albertel 8109: 
                   8110:     return $response;
1.1003    raeburn  8111: }
                   8112: 
                   8113: sub auto_possible_instcodes {
1.1007    raeburn  8114:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8115:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8116:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8117:         return;
                   8118:     }
1.1003    raeburn  8119:     my (@homeservers,$uhome);
                   8120:     if (defined(&domain($domain,'primary'))) {
                   8121:         $uhome=&domain($domain,'primary');
                   8122:         push(@homeservers,&domain($domain,'primary'));
                   8123:     } else {
                   8124:         my %servers = &get_servers($domain,'library');
                   8125:         foreach my $tryserver (keys(%servers)) {
                   8126:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8127:                 push(@homeservers,$tryserver);
                   8128:             }
                   8129:         }
                   8130:     }
                   8131:     my $response;
                   8132:     foreach my $server (@homeservers) {
                   8133:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8134:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8135:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8136:             split(':',$response);
                   8137:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8138:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8139:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8140:             my ($name,$value)=split('=',$item);
                   8141:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8142:         }
                   8143:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8144:             my ($name,$value)=split('=',$item);
                   8145:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8146:         }
                   8147:         return 'ok';
                   8148:     }
                   8149:     return $response;
                   8150: }
1.792     raeburn  8151: 
1.1010    raeburn  8152: sub auto_courserequest_checks {
                   8153:     my ($dom) = @_;
1.1020    raeburn  8154:     my ($homeserver,%validations);
                   8155:     if ($dom =~ /^$match_domain$/) {
                   8156:         $homeserver = &domain($dom,'primary');
                   8157:     }
                   8158:     unless ($homeserver eq 'no_host') {
                   8159:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8160:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8161:             my @items = split(/&/,$response);
                   8162:             foreach my $item (@items) {
                   8163:                 my ($key,$value) = split('=',$item);
                   8164:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8165:             }
                   8166:         }
                   8167:     }
1.1010    raeburn  8168:     return %validations; 
                   8169: }
                   8170: 
1.1020    raeburn  8171: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8172:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8173:     my ($homeserver,$response);
                   8174:     if ($dom =~ /^$match_domain$/) {
                   8175:         $homeserver = &domain($dom,'primary');
                   8176:     }
1.1172.2.43  raeburn  8177:     unless ($homeserver eq 'no_host') {
                   8178:         my $customdata;
                   8179:         if (ref($custominfo) eq 'HASH') {
                   8180:             $customdata = &freeze_escape($custominfo);
                   8181:         }
1.1020    raeburn  8182:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8183:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8184:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8185:                                     $customdata,$homeserver));
1.1020    raeburn  8186:     }
                   8187:     return $response;
                   8188: }
                   8189: 
1.777     albertel 8190: sub auto_validate_class_sec {
1.918     raeburn  8191:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8192:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8193:     my $ownerlist;
                   8194:     if (ref($owners) eq 'ARRAY') {
                   8195:         $ownerlist = join(',',@{$owners});
                   8196:     } else {
                   8197:         $ownerlist = $owners;
                   8198:     }
1.773     raeburn  8199:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8200:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8201:     return $response;
                   8202: }
                   8203: 
1.1172.2.38  raeburn  8204: sub auto_crsreq_update {
                   8205:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8206:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8207:     my ($homeserver,%crsreqresponse);
                   8208:     if ($cdom =~ /^$match_domain$/) {
                   8209:         $homeserver = &domain($cdom,'primary');
                   8210:     }
                   8211:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8212:         my $info;
                   8213:         if (ref($inbound) eq 'HASH') {
                   8214:             $info = &freeze_escape($inbound);
                   8215:         }
                   8216:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8217:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8218:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8219:                             &escape($title).':'.&escape($code).':'.
                   8220:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8221:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8222:             my @items = split(/&/,$response);
                   8223:             foreach my $item (@items) {
                   8224:                 my ($key,$value) = split('=',$item);
                   8225:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8226:             }
                   8227:         }
                   8228:     }
                   8229:     return \%crsreqresponse;
                   8230: }
                   8231: 
1.1172.2.68  raeburn  8232: sub check_instcode_cloning {
                   8233:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8234:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8235:         return;
                   8236:     }
                   8237:     my $canclone;
                   8238:     if (@{$code_order} > 0) {
                   8239:         my $instcoderegexp ='^';
                   8240:         my @clonecodes = split(/\&/,$cloner);
                   8241:         foreach my $item (@{$code_order}) {
                   8242:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8243:                 foreach my $pair (@clonecodes) {
                   8244:                     my ($key,$val) = split(/\=/,$pair,2);
                   8245:                     $val = &unescape($val);
                   8246:                     if ($key eq $item) {
                   8247:                         $instcoderegexp .= '('.$val.')';
                   8248:                         last;
                   8249:                     }
                   8250:                 }
                   8251:             } else {
                   8252:                 $instcoderegexp .= $codedefaults->{$item};
                   8253:             }
                   8254:         }
                   8255:         $instcoderegexp .= '$';
                   8256:         my (@from,@to);
                   8257:         eval {
                   8258:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8259:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8260:         };
                   8261:         if ((@from > 0) && (@to > 0)) {
                   8262:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8263:             if (!@diffs) {
                   8264:                 $canclone = 1;
                   8265:             }
                   8266:         }
                   8267:     }
                   8268:     return $canclone;
                   8269: }
                   8270: 
                   8271: sub default_instcode_cloning {
                   8272:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8273:     my (%codedefaults,@code_order,$canclone);
                   8274:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8275:         %codedefaults = %{$codedefaultsref};
                   8276:         @code_order = @{$codeorderref};
                   8277:     } elsif ($clonedom) {
                   8278:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8279:     }
                   8280:     if (($domdefclone) && (@code_order)) {
                   8281:         my @clonecodes = split(/\+/,$domdefclone);
                   8282:         my $instcoderegexp ='^';
                   8283:         foreach my $item (@code_order) {
                   8284:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8285:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8286:             } else {
                   8287:                 $instcoderegexp .= $codedefaults{$item};
                   8288:             }
                   8289:         }
                   8290:         $instcoderegexp .= '$';
                   8291:         my (@from,@to);
                   8292:         eval {
                   8293:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8294:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8295:         };
                   8296:         if ((@from > 0) && (@to > 0)) {
                   8297:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8298:             if (!@diffs) {
                   8299:                 $canclone = 1;
                   8300:             }
                   8301:         }
                   8302:     }
                   8303:     return $canclone;
                   8304: }
                   8305: 
1.679     raeburn  8306: # ------------------------------------------------------- Course Group routines
                   8307: 
                   8308: sub get_coursegroups {
1.809     raeburn  8309:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8310:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8311: }
                   8312: 
1.679     raeburn  8313: sub modify_coursegroup {
                   8314:     my ($cdom,$cnum,$groupsettings) = @_;
                   8315:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8316: }
                   8317: 
1.809     raeburn  8318: sub toggle_coursegroup_status {
                   8319:     my ($cdom,$cnum,$group,$action) = @_;
                   8320:     my ($from_namespace,$to_namespace);
                   8321:     if ($action eq 'delete') {
                   8322:         $from_namespace = 'coursegroups';
                   8323:         $to_namespace = 'deleted_groups';
                   8324:     } else {
                   8325:         $from_namespace = 'deleted_groups';
                   8326:         $to_namespace = 'coursegroups';
                   8327:     }
                   8328:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8329:     if (my $tmp = &error(%curr_group)) {
                   8330:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8331:         return ('read error',$tmp);
                   8332:     } else {
                   8333:         my %savedsettings = %curr_group; 
1.809     raeburn  8334:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8335:         my $deloutcome;
                   8336:         if ($result eq 'ok') {
1.809     raeburn  8337:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8338:         } else {
                   8339:             return ('write error',$result);
                   8340:         }
                   8341:         if ($deloutcome eq 'ok') {
                   8342:             return 'ok';
                   8343:         } else {
                   8344:             return ('delete error',$deloutcome);
                   8345:         }
                   8346:     }
                   8347: }
                   8348: 
1.679     raeburn  8349: sub modify_group_roles {
1.957     raeburn  8350:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8351:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8352:     my $role = 'gr/'.&escape($userprivs);
                   8353:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8354:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8355:     if ($result eq 'ok') {
                   8356:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8357:     }
1.679     raeburn  8358:     return $result;
                   8359: }
                   8360: 
                   8361: sub modify_coursegroup_membership {
                   8362:     my ($cdom,$cnum,$membership) = @_;
                   8363:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8364:     return $result;
                   8365: }
                   8366: 
1.682     raeburn  8367: sub get_active_groups {
                   8368:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8369:     my $now = time;
                   8370:     my %groups = ();
                   8371:     foreach my $key (keys(%env)) {
1.811     albertel 8372:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8373:             my ($start,$end) = split(/\./,$env{$key});
                   8374:             if (($end!=0) && ($end<$now)) { next; }
                   8375:             if (($start!=0) && ($start>$now)) { next; }
                   8376:             if ($1 eq $cdom && $2 eq $cnum) {
                   8377:                 $groups{$3} = $env{$key} ;
                   8378:             }
                   8379:         }
                   8380:     }
                   8381:     return %groups;
                   8382: }
                   8383: 
1.683     raeburn  8384: sub get_group_membership {
                   8385:     my ($cdom,$cnum,$group) = @_;
                   8386:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8387: }
                   8388: 
                   8389: sub get_users_groups {
                   8390:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8391:     my @usersgroups;
1.683     raeburn  8392:     my $cachetime=1800;
                   8393: 
                   8394:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8395:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8396:     if (defined($cached)) {
1.734     albertel 8397:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8398:     } else {  
                   8399:         $grouplist = '';
1.816     raeburn  8400:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8401:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8402:         my $access_end = $env{'course.'.$courseid.
                   8403:                               '.default_enrollment_end_date'};
                   8404:         my $now = time;
                   8405:         foreach my $key (keys(%roleshash)) {
                   8406:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8407:                 my $group = $1;
                   8408:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8409:                     my $start = $2;
                   8410:                     my $end = $1;
                   8411:                     if ($start == -1) { next; } # deleted from group
                   8412:                     if (($start!=0) && ($start>$now)) { next; }
                   8413:                     if (($end!=0) && ($end<$now)) {
                   8414:                         if ($access_end && $access_end < $now) {
                   8415:                             if ($access_end - $end < 86400) {
                   8416:                                 push(@usersgroups,$group);
1.733     raeburn  8417:                             }
                   8418:                         }
1.817     raeburn  8419:                         next;
1.733     raeburn  8420:                     }
1.817     raeburn  8421:                     push(@usersgroups,$group);
1.683     raeburn  8422:                 }
                   8423:             }
                   8424:         }
1.817     raeburn  8425:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8426:         $grouplist = join(':',@usersgroups);
                   8427:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8428:     }
1.733     raeburn  8429:     return @usersgroups;
1.683     raeburn  8430: }
                   8431: 
                   8432: sub devalidate_getgroups_cache {
                   8433:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8434:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8435: 
1.683     raeburn  8436:     my $hashid="$udom:$uname:$courseid";
                   8437:     &devalidate_cache_new('getgroups',$hashid);
                   8438: }
                   8439: 
1.12      www      8440: # ------------------------------------------------------------------ Plain Text
                   8441: 
                   8442: sub plaintext {
1.988     raeburn  8443:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8444:     if ($short =~ m{^cr/}) {
1.758     albertel 8445: 	return (split('/',$short))[-1];
                   8446:     }
1.742     raeburn  8447:     if (!defined($cid)) {
                   8448:         $cid = $env{'request.course.id'};
                   8449:     }
                   8450:     my %rolenames = (
1.1008    raeburn  8451:                       Course    => 'std',
                   8452:                       Community => 'alt1',
1.742     raeburn  8453:                     );
1.1037    raeburn  8454:     if ($cid ne '') {
                   8455:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8456:             unless ($forcedefault) {
                   8457:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8458:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8459:                 return &Apache::lonlocal::mt($roletext);
                   8460:             }
                   8461:         }
                   8462:     }
                   8463:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8464:         (defined($rolenames{$type})) && 
                   8465:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8466:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8467:     } elsif ($cid ne '') {
                   8468:         my $crstype = $env{'course.'.$cid.'.type'};
                   8469:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8470:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8471:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8472:         }
1.742     raeburn  8473:     }
1.1037    raeburn  8474:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8475: }
                   8476: 
                   8477: # ----------------------------------------------------------------- Assign Role
                   8478: 
                   8479: sub assignrole {
1.957     raeburn  8480:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8481:         $context)=@_;
1.21      www      8482:     my $mrole;
                   8483:     if ($role =~ /^cr\//) {
1.393     www      8484:         my $cwosec=$url;
1.811     albertel 8485:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8486: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8487:            my $refused = 1;
                   8488:            if ($context eq 'requestcourses') {
                   8489:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8490:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8491:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8492:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8493:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8494:                            if ($crsenv{'internal.courseowner'} eq
                   8495:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8496:                                $refused = '';
                   8497:                            }
                   8498:                        }
                   8499:                    }
                   8500:                }
                   8501:            }
                   8502:            if ($refused) {
                   8503:                &logthis('Refused custom assignrole: '.
                   8504:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8505:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8506:                return 'refused';
                   8507:            }
1.104     www      8508:         }
1.21      www      8509:         $mrole='cr';
1.678     raeburn  8510:     } elsif ($role =~ /^gr\//) {
                   8511:         my $cwogrp=$url;
1.811     albertel 8512:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8513:         unless (&allowed('mdg',$cwogrp)) {
                   8514:             &logthis('Refused group assignrole: '.
                   8515:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8516:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8517:             return 'refused';
                   8518:         }
                   8519:         $mrole='gr';
1.21      www      8520:     } else {
1.82      www      8521:         my $cwosec=$url;
1.811     albertel 8522:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8523:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8524:             my $refused;
                   8525:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8526:                 if (!(&allowed('c'.$role,$url))) {
                   8527:                     $refused = 1;
                   8528:                 }
                   8529:             } else {
                   8530:                 $refused = 1;
                   8531:             }
1.947     raeburn  8532:             if ($refused) {
1.1045    raeburn  8533:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8534:                 if (!$selfenroll && $context eq 'course') {
                   8535:                     my %crsenv;
                   8536:                     if ($role eq 'cc' || $role eq 'co') {
                   8537:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8538:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8539:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8540:                                 if ($crsenv{'internal.courseowner'} eq 
                   8541:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8542:                                     $refused = '';
                   8543:                                 }
                   8544:                             }
                   8545:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8546:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8547:                                 if ($crsenv{'internal.courseowner'} eq 
                   8548:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8549:                                     $refused = '';
                   8550:                                 }
                   8551:                             }
                   8552:                         }
                   8553:                     }
                   8554:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8555:                     $refused = '';
1.1017    raeburn  8556:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8557:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8558:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8559:                         my $wrongcc;
                   8560:                         if ($cnum =~ /^$match_community$/) {
                   8561:                             $wrongcc = 1 if ($role eq 'cc');
                   8562:                         } else {
                   8563:                             $wrongcc = 1 if ($role eq 'co');
                   8564:                         }
                   8565:                         unless ($wrongcc) {
                   8566:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8567:                             if ($crsenv{'internal.courseowner'} eq 
                   8568:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8569:                                 $refused = '';
                   8570:                             }
1.1017    raeburn  8571:                         }
                   8572:                     }
1.1172.2.9  raeburn  8573:                 } elsif ($context eq 'requestauthor') {
                   8574:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8575:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8576:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8577:                             $refused = '';
                   8578:                         } else {
                   8579:                             my %domdefaults = &get_domain_defaults($udom);
                   8580:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8581:                                 my $checkbystatus;
                   8582:                                 if ($env{'user.adv'}) {
                   8583:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8584:                                     if ($disposition eq 'automatic') {
                   8585:                                         $refused = '';
                   8586:                                     } elsif ($disposition eq '') {
                   8587:                                         $checkbystatus = 1;
                   8588:                                     }
                   8589:                                 } else {
                   8590:                                     $checkbystatus = 1;
                   8591:                                 }
                   8592:                                 if ($checkbystatus) {
                   8593:                                     if ($env{'environment.inststatus'}) {
                   8594:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8595:                                         foreach my $type (@inststatuses) {
                   8596:                                             if (($type ne '') &&
                   8597:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8598:                                                 $refused = '';
                   8599:                                             }
                   8600:                                         }
                   8601:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8602:                                         $refused = '';
                   8603:                                     }
                   8604:                                 }
                   8605:                             }
                   8606:                         }
                   8607:                     }
1.1017    raeburn  8608:                 }
                   8609:                 if ($refused) {
1.947     raeburn  8610:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8611:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8612: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8613:                     return 'refused';
                   8614:                 }
1.932     raeburn  8615:             }
1.1131    raeburn  8616:         } elsif ($role eq 'au') {
                   8617:             if ($url ne '/'.$udom.'/') {
                   8618:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8619:                          ' to assign author role for '.$uname.':'.$udom.
                   8620:                          ' in domain: '.$url.' refused (wrong domain).');
                   8621:                 return 'refused';
                   8622:             }
1.104     www      8623:         }
1.21      www      8624:         $mrole=$role;
                   8625:     }
1.620     albertel 8626:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8627:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8628:     if ($end) { $command.='_'.$end; }
1.21      www      8629:     if ($start) {
                   8630: 	if ($end) { 
1.81      www      8631:            $command.='_'.$start; 
1.21      www      8632:         } else {
1.81      www      8633:            $command.='_0_'.$start;
1.21      www      8634:         }
                   8635:     }
1.739     raeburn  8636:     my $origstart = $start;
                   8637:     my $origend = $end;
1.957     raeburn  8638:     my $delflag;
1.357     www      8639: # actually delete
                   8640:     if ($deleteflag) {
1.373     www      8641: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8642: # modify command to delete the role
1.620     albertel 8643:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8644:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8645: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8646: # set start and finish to negative values for userrolelog
                   8647:            $start=-1;
                   8648:            $end=-1;
1.957     raeburn  8649:            $delflag = 1;
1.357     www      8650:         }
                   8651:     }
                   8652: # send command
1.349     www      8653:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8654: # log new user role if status is ok
1.349     www      8655:     if ($answer eq 'ok') {
1.663     raeburn  8656: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8657:         if (($role eq 'cc') || ($role eq 'in') ||
                   8658:             ($role eq 'ep') || ($role eq 'ad') ||
                   8659:             ($role eq 'ta') || ($role eq 'st') ||
                   8660:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8661:             ($role eq 'co')) {
1.1172.2.13  raeburn  8662: # for course roles, perform group memberships changes triggered by role change.
                   8663:             unless ($role =~ /^gr/) {
                   8664:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8665:                                                  $origstart,$selfenroll,$context);
                   8666:             }
1.1172.2.9  raeburn  8667:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8668:                            $selfenroll,$context);
                   8669:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8670:                  ($role eq 'au') || ($role eq 'dc')) {
                   8671:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8672:                            $context);
                   8673:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8674:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8675:                              $context);
                   8676:         }
1.1053    raeburn  8677:         if ($role eq 'cc') {
                   8678:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8679:         }
1.349     www      8680:     }
                   8681:     return $answer;
1.169     harris41 8682: }
                   8683: 
1.1053    raeburn  8684: sub autoupdate_coowners {
                   8685:     my ($url,$end,$start,$uname,$udom) = @_;
                   8686:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8687:     if (($cdom ne '') && ($cnum ne '')) {
                   8688:         my $now = time;
                   8689:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8690:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8691:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8692:             my $instcode = $coursehash{'internal.coursecode'};
                   8693:             if ($instcode ne '') {
1.1056    raeburn  8694:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8695:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8696:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8697:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8698:                         if ($result eq 'valid') {
                   8699:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8700:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8701:                                     push(@newcoowners,$coowner);
                   8702:                                 }
                   8703:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8704:                                     push(@newcoowners,$uname.':'.$udom);
                   8705:                                 }
                   8706:                                 @newcoowners = sort(@newcoowners);
                   8707:                             } else {
                   8708:                                 push(@newcoowners,$uname.':'.$udom);
                   8709:                             }
                   8710:                         } else {
                   8711:                             if ($coursehash{'internal.co-owners'}) {
                   8712:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8713:                                     unless ($coowner eq $uname.':'.$udom) {
                   8714:                                         push(@newcoowners,$coowner);
                   8715:                                     }
                   8716:                                 }
                   8717:                                 unless (@newcoowners > 0) {
                   8718:                                     $delcoowners = 1;
                   8719:                                     $coowners = '';
                   8720:                                 }
                   8721:                             }
                   8722:                         }
                   8723:                         if (@newcoowners || $delcoowners) {
                   8724:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8725:                                             $delcoowners,@newcoowners);
                   8726:                         }
                   8727:                     }
                   8728:                 }
                   8729:             }
                   8730:         }
                   8731:     }
                   8732: }
                   8733: 
                   8734: sub store_coowners {
                   8735:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8736:     my $cid = $cdom.'_'.$cnum;
                   8737:     my ($coowners,$delresult,$putresult);
                   8738:     if (@newcoowners) {
                   8739:         $coowners = join(',',@newcoowners);
                   8740:         my %coownershash = (
                   8741:                             'internal.co-owners' => $coowners,
                   8742:                            );
                   8743:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8744:         if ($putresult eq 'ok') {
                   8745:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8746:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8747:             }
                   8748:         }
                   8749:     }
                   8750:     if ($delcoowners) {
                   8751:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8752:         if ($delresult eq 'ok') {
                   8753:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8754:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8755:             }
                   8756:         }
                   8757:     }
                   8758:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8759:         my %crsinfo =
                   8760:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8761:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8762:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8763:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8764:         }
                   8765:     }
                   8766: }
                   8767: 
1.169     harris41 8768: # -------------------------------------------------- Modify user authentication
1.197     www      8769: # Overrides without validation
                   8770: 
1.169     harris41 8771: sub modifyuserauth {
                   8772:     my ($udom,$uname,$umode,$upass)=@_;
                   8773:     my $uhome=&homeserver($uname,$udom);
1.197     www      8774:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8775:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8776:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8777:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8778:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8779: 		     &escape($upass),$uhome);
1.620     albertel 8780:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8781:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8782:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8783:     &log($udom,,$uname,$uhome,
1.620     albertel 8784:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8785:                                      $env{'user.name'}.', '.$umode.
1.197     www      8786:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8787:     unless ($reply eq 'ok') {
1.197     www      8788:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8789: 	return 'error: '.$reply;
                   8790:     }   
1.170     harris41 8791:     return 'ok';
1.80      www      8792: }
                   8793: 
1.81      www      8794: # --------------------------------------------------------------- Modify a user
1.80      www      8795: 
1.81      www      8796: sub modifyuser {
1.206     matthew  8797:     my ($udom,    $uname, $uid,
                   8798:         $umode,   $upass, $first,
                   8799:         $middle,  $last,  $gene,
1.1058    raeburn  8800:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8801:     $udom= &LONCAPA::clean_domain($udom);
                   8802:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8803:     my $showcandelete = 'none';
                   8804:     if (ref($candelete) eq 'ARRAY') {
                   8805:         if (@{$candelete} > 0) {
                   8806:             $showcandelete = join(', ',@{$candelete});
                   8807:         }
                   8808:     }
1.81      www      8809:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8810:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8811: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8812:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8813:                                      ' desiredhome not specified'). 
1.620     albertel 8814:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8815:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8816:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8817:     my $newuser;
                   8818:     if ($uhome eq 'no_host') {
                   8819:         $newuser = 1;
                   8820:     }
1.80      www      8821: # ----------------------------------------------------------------- Create User
1.406     albertel 8822:     if (($uhome eq 'no_host') && 
                   8823: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8824:         my $unhome='';
1.844     albertel 8825:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8826:             $unhome = $desiredhome;
1.620     albertel 8827: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8828: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8829:         } else { # load balancing routine for determining $unhome
1.81      www      8830:             my $loadm=10000000;
1.841     albertel 8831: 	    my %servers = &get_servers($udom,'library');
                   8832: 	    foreach my $tryserver (keys(%servers)) {
                   8833: 		my $answer=reply('load',$tryserver);
                   8834: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8835: 		    $loadm=$answer;
                   8836: 		    $unhome=$tryserver;
                   8837: 		}
1.80      www      8838: 	    }
                   8839:         }
                   8840:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8841: 	    return 'error: unable to find a home server for '.$uname.
                   8842:                    ' in domain '.$udom;
1.80      www      8843:         }
                   8844:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8845:                          &escape($upass),$unhome);
                   8846: 	unless ($reply eq 'ok') {
                   8847:             return 'error: '.$reply;
                   8848:         }   
1.230     stredwic 8849:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8850:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8851: 	    return 'error: unable verify users home machine.';
1.80      www      8852:         }
1.209     matthew  8853:     }   # End of creation of new user
1.80      www      8854: # ---------------------------------------------------------------------- Add ID
                   8855:     if ($uid) {
                   8856:        $uid=~tr/A-Z/a-z/;
                   8857:        my %uidhash=&idrget($udom,$uname);
1.196     www      8858:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8859:          && (!$forceid)) {
1.80      www      8860: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8861: 	      return 'error: user id "'.$uid.'" does not match '.
                   8862:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8863:           }
                   8864:        } else {
                   8865: 	  &idput($udom,($uname => $uid));
                   8866:        }
                   8867:     }
                   8868: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8869:     my @tmp=&get('environment',
1.899     raeburn  8870: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8871:                     'permanentemail','inststatus'],
1.134     albertel 8872: 		   $udom,$uname);
1.1075    raeburn  8873:     my (%names,%oldnames);
1.313     matthew  8874:     if ($tmp[0] =~ m/^error:.*/) { 
                   8875:         %names=(); 
                   8876:     } else {
                   8877:         %names = @tmp;
1.1075    raeburn  8878:         %oldnames = %names;
1.313     matthew  8879:     }
1.388     www      8880: #
1.1058    raeburn  8881: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8882: # of users did not contain them), do not overwrite existing values
                   8883: # unless field is in $candelete array ref.  
                   8884: #
                   8885: 
                   8886:     my @fields = ('firstname','middlename','lastname','generation',
                   8887:                   'permanentemail','id');
                   8888:     my %newvalues;
                   8889:     if (ref($candelete) eq 'ARRAY') {
                   8890:         foreach my $field (@fields) {
                   8891:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8892:                 if ($field eq 'firstname') {
                   8893:                     $names{$field} = $first;
                   8894:                 } elsif ($field eq 'middlename') {
                   8895:                     $names{$field} = $middle;
                   8896:                 } elsif ($field eq 'lastname') {
                   8897:                     $names{$field} = $last;
                   8898:                 } elsif ($field eq 'generation') { 
                   8899:                     $names{$field} = $gene;
                   8900:                 } elsif ($field eq 'permanentemail') {
                   8901:                     $names{$field} = $email;
                   8902:                 } elsif ($field eq 'id') {
                   8903:                     $names{$field}  = $uid;
                   8904:                 }
                   8905:             }
                   8906:         }
                   8907:     }
1.388     www      8908:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8909:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8910:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8911:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8912:     if ($email) {
                   8913:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8914:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8915:     }
1.899     raeburn  8916:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8917:     if (defined($inststatus)) {
                   8918:         $names{'inststatus'} = '';
                   8919:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8920:         if (ref($usertypes) eq 'HASH') {
                   8921:             my @okstatuses; 
                   8922:             foreach my $item (split(/:/,$inststatus)) {
                   8923:                 if (defined($usertypes->{$item})) {
                   8924:                     push(@okstatuses,$item);  
                   8925:                 }
                   8926:             }
                   8927:             if (@okstatuses) {
                   8928:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8929:             }
                   8930:         }
                   8931:     }
1.1075    raeburn  8932:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8933:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8934:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8935:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8936:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8937:     } else {
                   8938:         $logmsg .= ' during self creation';
                   8939:     }
1.1075    raeburn  8940:     my $changed;
                   8941:     if ($newuser) {
                   8942:         $changed = 1;
                   8943:     } else {
                   8944:         foreach my $field (@fields) {
                   8945:             if ($names{$field} ne $oldnames{$field}) {
                   8946:                 $changed = 1;
                   8947:                 last;
                   8948:             }
                   8949:         }
                   8950:     }
                   8951:     unless ($changed) {
                   8952:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8953:         &logthis($logmsg);
                   8954:         return 'ok';
                   8955:     }
                   8956:     my $reply = &put('environment', \%names, $udom,$uname);
                   8957:     if ($reply ne 'ok') { 
                   8958:         return 'error: '.$reply;
                   8959:     }
1.1087    raeburn  8960:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8961:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8962:     }
1.1075    raeburn  8963:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8964:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8965:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8966:     &logthis($logmsg);
1.134     albertel 8967:     return 'ok';
1.80      www      8968: }
                   8969: 
1.81      www      8970: # -------------------------------------------------------------- Modify student
1.80      www      8971: 
1.81      www      8972: sub modifystudent {
                   8973:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8974:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.19  raeburn  8975:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8976:     if (!$cid) {
1.620     albertel 8977: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8978: 	    return 'not_in_class';
                   8979: 	}
1.80      www      8980:     }
                   8981: # --------------------------------------------------------------- Make the user
1.81      www      8982:     my $reply=&modifyuser
1.209     matthew  8983: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8984:          $desiredhome,$email,$inststatus);
1.80      www      8985:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8986:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  8987:     # student's environment
1.297     matthew  8988:     $uid = undef if (!$forceid);
1.455     albertel 8989:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  8990: 					$gene,$usec,$end,$start,$type,$locktype,
                   8991:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8992:     return $reply;
                   8993: }
                   8994: 
                   8995: sub modify_student_enrollment {
1.1172.2.23  raeburn  8996:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8997:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8998:     my ($cdom,$cnum,$chome);
                   8999:     if (!$cid) {
1.620     albertel 9000: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9001: 	    return 'not_in_class';
                   9002: 	}
1.620     albertel 9003: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9004: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9005:     } else {
                   9006: 	($cdom,$cnum)=split(/_/,$cid);
                   9007:     }
1.620     albertel 9008:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9009:     if (!$chome) {
1.457     raeburn  9010: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9011:     }
1.455     albertel 9012:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9013:     # Make sure the user exists
1.81      www      9014:     my $uhome=&homeserver($uname,$udom);
                   9015:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9016: 	return 'error: no such user';
                   9017:     }
1.297     matthew  9018:     # Get student data if we were not given enough information
                   9019:     if (!defined($first)  || $first  eq '' || 
                   9020:         !defined($last)   || $last   eq '' || 
                   9021:         !defined($uid)    || $uid    eq '' || 
                   9022:         !defined($middle) || $middle eq '' || 
                   9023:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9024:         # They did not supply us with enough data to enroll the student, so
                   9025:         # we need to pick up more information.
1.297     matthew  9026:         my %tmp = &get('environment',
1.294     matthew  9027:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9028:                        ,$udom,$uname);
                   9029: 
1.800     albertel 9030:         #foreach my $key (keys(%tmp)) {
                   9031:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9032:         #}
1.294     matthew  9033:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9034:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9035:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9036:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9037:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9038:     }
1.556     albertel 9039:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9040:     my $user = "$uname:$udom";
                   9041:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9042:     my $reply=cput('classlist',
1.1148    raeburn  9043: 		   {$user => 
1.1172.2.19  raeburn  9044: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 9045: 		   $cdom,$cnum);
1.1148    raeburn  9046:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9047:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9048:     } else { 
1.81      www      9049: 	return 'error: '.$reply;
                   9050:     }
1.297     matthew  9051:     # Add student role to user
1.83      www      9052:     my $uurl='/'.$cid;
1.81      www      9053:     $uurl=~s/\_/\//g;
                   9054:     if ($usec) {
                   9055: 	$uurl.='/'.$usec;
                   9056:     }
1.1148    raeburn  9057:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9058:                              $selfenroll,$context);
                   9059:     if ($result ne 'ok') {
                   9060:         if ($old_entry{$user} ne '') {
                   9061:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9062:         } else {
                   9063:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9064:         }
                   9065:     }
                   9066:     return $result; 
1.21      www      9067: }
                   9068: 
1.556     albertel 9069: sub format_name {
                   9070:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9071:     my $name;
                   9072:     if ($first ne 'lastname') {
                   9073: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9074:     } else {
                   9075: 	if ($lastname=~/\S/) {
                   9076: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9077: 	    $name=~s/\s+,/,/;
                   9078: 	} else {
                   9079: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9080: 	}
                   9081:     }
                   9082:     $name=~s/^\s+//;
                   9083:     $name=~s/\s+$//;
                   9084:     $name=~s/\s+/ /g;
                   9085:     return $name;
                   9086: }
                   9087: 
1.84      www      9088: # ------------------------------------------------- Write to course preferences
                   9089: 
                   9090: sub writecoursepref {
                   9091:     my ($courseid,%prefs)=@_;
                   9092:     $courseid=~s/^\///;
                   9093:     $courseid=~s/\_/\//g;
                   9094:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9095:     my $chome=homeserver($cnum,$cdomain);
                   9096:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9097: 	return 'error: no such course';
                   9098:     }
                   9099:     my $cstring='';
1.800     albertel 9100:     foreach my $pref (keys(%prefs)) {
                   9101: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9102:     }
1.84      www      9103:     $cstring=~s/\&$//;
                   9104:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9105: }
                   9106: 
                   9107: # ---------------------------------------------------------- Make/modify course
                   9108: 
                   9109: sub createcourse {
1.741     raeburn  9110:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9111:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9112:     $url=&declutter($url);
                   9113:     my $cid='';
1.1028    raeburn  9114:     if ($context eq 'requestcourses') {
                   9115:         my $can_create = 0;
                   9116:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9117:         if ($udom eq $ownerdom) {
                   9118:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9119:                                   $context)) {
                   9120:                 $can_create = 1;
                   9121:             }
                   9122:         } else {
                   9123:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9124:                                            $category);
                   9125:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9126:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9127:                 if (@curr > 0) {
                   9128:                     my @options = qw(approval validate autolimit);
                   9129:                     my $optregex = join('|',@options);
                   9130:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9131:                         $can_create = 1;
                   9132:                     }
                   9133:                 }
                   9134:             }
                   9135:         }
                   9136:         if ($can_create) {
                   9137:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9138:                 unless (&allowed('ccc',$udom)) {
                   9139:                     return 'refused'; 
                   9140:                 }
1.1017    raeburn  9141:             }
                   9142:         } else {
                   9143:             return 'refused';
                   9144:         }
1.1028    raeburn  9145:     } elsif (!&allowed('ccc',$udom)) {
                   9146:         return 'refused';
1.84      www      9147:     }
1.1011    raeburn  9148: # --------------------------------------------------------------- Get Unique ID
                   9149:     my $uname;
                   9150:     if ($cnum =~ /^$match_courseid$/) {
                   9151:         my $chome=&homeserver($cnum,$udom,'true');
                   9152:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9153:             $uname = $cnum;
                   9154:         } else {
1.1038    raeburn  9155:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9156:         }
                   9157:     } else {
1.1038    raeburn  9158:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9159:     }
                   9160:     return $uname if ($uname =~ /^error/);
                   9161: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9162:     if (!defined($course_server)) {
                   9163:         if (defined(&domain($udom,'primary'))) {
                   9164:             $course_server = &domain($udom,'primary');
                   9165:         } else {
                   9166:             $course_server = $env{'user.home'}; 
                   9167:         }
                   9168:     }
                   9169:     my %host_servers =
                   9170:         &Apache::lonnet::get_servers($udom,'library');
                   9171:     unless ($host_servers{$course_server}) {
                   9172:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9173:     }
1.84      www      9174: # ------------------------------------------------------------- Make the course
                   9175:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9176:                       $course_server);
1.84      www      9177:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9178:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9179:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9180: 	return 'error: no such course';
                   9181:     }
1.271     www      9182: # ----------------------------------------------------------------- Course made
1.516     raeburn  9183: # log existence
1.1029    raeburn  9184:     my $now = time;
1.918     raeburn  9185:     my $newcourse = {
                   9186:                     $udom.'_'.$uname => {
1.921     raeburn  9187:                                      description => $description,
                   9188:                                      inst_code   => $inst_code,
                   9189:                                      owner       => $course_owner,
                   9190:                                      type        => $crstype,
1.1029    raeburn  9191:                                      creator     => $env{'user.name'}.':'.
                   9192:                                                     $env{'user.domain'},
                   9193:                                      created     => $now,
                   9194:                                      context     => $context,
1.918     raeburn  9195:                                                 },
                   9196:                     };
1.921     raeburn  9197:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9198: # set toplevel url
1.271     www      9199:     my $topurl=$url;
                   9200:     unless ($nonstandard) {
                   9201: # ------------------------------------------ For standard courses, make top url
                   9202:         my $mapurl=&clutter($url);
1.278     www      9203:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9204:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9205: <map>
                   9206: <resource id="1" type="start"></resource>
                   9207: <resource id="2" src="$mapurl"></resource>
                   9208: <resource id="3" type="finish"></resource>
                   9209: <link index="1" from="1" to="2"></link>
                   9210: <link index="2" from="2" to="3"></link>
                   9211: </map>
                   9212: ENDINITMAP
                   9213:         $topurl=&declutter(
1.638     albertel 9214:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9215:                           );
                   9216:     }
                   9217: # ----------------------------------------------------------- Write preferences
1.84      www      9218:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9219:                      ('description'              => $description,
                   9220:                       'url'                      => $topurl,
                   9221:                       'internal.creator'         => $env{'user.name'}.':'.
                   9222:                                                     $env{'user.domain'},
                   9223:                       'internal.created'         => $now,
                   9224:                       'internal.creationcontext' => $context)
                   9225:                     );
1.84      www      9226:     return '/'.$udom.'/'.$uname;
                   9227: }
                   9228: 
1.1011    raeburn  9229: # ------------------------------------------------------------------- Create ID
                   9230: sub generate_coursenum {
1.1038    raeburn  9231:     my ($udom,$crstype) = @_;
1.1011    raeburn  9232:     my $domdesc = &domain($udom);
                   9233:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9234:     my $first;
                   9235:     if ($crstype eq 'Community') {
                   9236:         $first = '0';
                   9237:     } else {
                   9238:         $first = int(1+rand(9)); 
                   9239:     } 
                   9240:     my $uname=$first.
1.1011    raeburn  9241:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9242:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9243:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9244: # ----------------------------------------------- Make sure that does not exist
                   9245:     my $uhome=&homeserver($uname,$udom,'true');
                   9246:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9247:         if ($crstype eq 'Community') {
                   9248:             $first = '0';
                   9249:         } else {
                   9250:             $first = int(1+rand(9));
                   9251:         }
                   9252:         $uname=$first.
1.1011    raeburn  9253:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9254:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9255:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9256:         $uhome=&homeserver($uname,$udom,'true');
                   9257:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9258:             return 'error: unable to generate unique course-ID';
                   9259:         }
                   9260:     }
                   9261:     return $uname;
                   9262: }
                   9263: 
1.813     albertel 9264: sub is_course {
1.1167    droeschl 9265:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9266:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9267: 
                   9268:     return unless $cdom and $cnum;
                   9269: 
                   9270:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9271:         '.');
                   9272: 
1.1172.2.23  raeburn  9273:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9274:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9275: }
                   9276: 
1.1015    raeburn  9277: sub store_userdata {
                   9278:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9279:     my $result;
1.1016    raeburn  9280:     if ($datakey ne '') {
1.1013    raeburn  9281:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9282:             if ($udom eq '' || $uname eq '') {
                   9283:                 $udom = $env{'user.domain'};
                   9284:                 $uname = $env{'user.name'};
                   9285:             }
                   9286:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9287:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9288:                 $result = 'error: no_host';
                   9289:             } else {
                   9290:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9291:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9292: 
                   9293:                 my $namevalue='';
                   9294:                 foreach my $key (keys(%{$storehash})) {
                   9295:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9296:                 }
                   9297:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9298:                 unless ($namespace eq 'courserequests') {
                   9299:                     $datakey = &escape($datakey);
                   9300:                 }
1.1105    raeburn  9301:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9302:                                   $namevalue,$uhome);
1.1013    raeburn  9303:             }
                   9304:         } else {
                   9305:             $result = 'error: data to store was not a hash reference'; 
                   9306:         }
                   9307:     } else {
                   9308:         $result= 'error: invalid requestkey'; 
                   9309:     }
                   9310:     return $result;
                   9311: }
                   9312: 
1.21      www      9313: # ---------------------------------------------------------- Assign Custom Role
                   9314: 
                   9315: sub assigncustomrole {
1.957     raeburn  9316:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9317:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9318:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9319: }
                   9320: 
                   9321: # ----------------------------------------------------------------- Revoke Role
                   9322: 
                   9323: sub revokerole {
1.957     raeburn  9324:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9325:     my $now=time;
1.965     raeburn  9326:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9327: }
                   9328: 
                   9329: # ---------------------------------------------------------- Revoke Custom Role
                   9330: 
                   9331: sub revokecustomrole {
1.957     raeburn  9332:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9333:     my $now=time;
1.357     www      9334:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9335:            $deleteflag,$selfenroll,$context);
1.17      www      9336: }
                   9337: 
1.533     banghart 9338: # ------------------------------------------------------------ Disk usage
1.535     albertel 9339: sub diskusage {
1.955     raeburn  9340:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9341:     $directorypath =~ s/\/$//;
                   9342:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9343:                        .&escape($getpropath).':'.&escape($uname).':'
                   9344:                        .&escape($udom),homeserver($uname,$udom));
                   9345:     if ($listing eq 'unknown_cmd') {
                   9346:         if ($getpropath) {
                   9347:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9348:         }
                   9349:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9350:     }
1.514     albertel 9351:     return $listing;
1.512     banghart 9352: }
                   9353: 
1.566     banghart 9354: sub is_locked {
1.1096    raeburn  9355:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9356:     my @check;
                   9357:     my $is_locked;
1.1093    raeburn  9358:     push (@check,$file_name);
1.613     albertel 9359:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9360: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9361:     my ($tmp)=keys(%locked);
                   9362:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9363:     
1.566     banghart 9364:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9365:         $is_locked = 'false';
                   9366:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9367:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9368:                $is_locked = 'true';
1.1096    raeburn  9369:                if (ref($which) eq 'ARRAY') {
                   9370:                    push(@{$which},$entry);
                   9371:                } else {
                   9372:                    last;
                   9373:                }
1.745     raeburn  9374:            }
                   9375:        }
1.566     banghart 9376:     } else {
                   9377:         $is_locked = 'false';
                   9378:     }
1.1093    raeburn  9379:     return $is_locked;
1.566     banghart 9380: }
                   9381: 
1.759     albertel 9382: sub declutter_portfile {
                   9383:     my ($file) = @_;
1.833     albertel 9384:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9385:     return $file;
                   9386: }
                   9387: 
1.559     banghart 9388: # ------------------------------------------------------------- Mark as Read Only
                   9389: 
                   9390: sub mark_as_readonly {
                   9391:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9392:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9393:     my ($tmp)=keys(%current_permissions);
                   9394:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9395:     foreach my $file (@{$files}) {
1.759     albertel 9396: 	$file = &declutter_portfile($file);
1.561     banghart 9397:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9398:     }
1.613     albertel 9399:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9400:     return;
                   9401: }
                   9402: 
1.572     banghart 9403: # ------------------------------------------------------------Save Selected Files
                   9404: 
                   9405: sub save_selected_files {
                   9406:     my ($user, $path, @files) = @_;
                   9407:     my $filename = $user."savedfiles";
1.573     banghart 9408:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9409:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9410:     foreach my $file (@files) {
1.620     albertel 9411:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9412:     }
                   9413:     foreach my $file (@other_files) {
1.574     banghart 9414:         print (OUT $file."\n");
1.572     banghart 9415:     }
1.574     banghart 9416:     close (OUT);
1.572     banghart 9417:     return 'ok';
                   9418: }
                   9419: 
1.574     banghart 9420: sub clear_selected_files {
                   9421:     my ($user) = @_;
                   9422:     my $filename = $user."savedfiles";
1.1117    foxr     9423:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9424:     print (OUT undef);
                   9425:     close (OUT);
                   9426:     return ("ok");    
                   9427: }
                   9428: 
1.572     banghart 9429: sub files_in_path {
                   9430:     my ($user, $path) = @_;
                   9431:     my $filename = $user."savedfiles";
                   9432:     my %return_files;
1.1117    foxr     9433:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9434:     while (my $line_in = <IN>) {
1.574     banghart 9435:         chomp ($line_in);
                   9436:         my @paths_and_file = split (m!/!, $line_in);
                   9437:         my $file_part = pop (@paths_and_file);
                   9438:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9439:         $path_part.='/';
                   9440:         my $path_and_file = $path_part.$file_part;
                   9441:         if ($path_part eq $path) {
                   9442:             $return_files{$file_part}= 'selected';
                   9443:         }
                   9444:     }
1.574     banghart 9445:     close (IN);
                   9446:     return (\%return_files);
1.572     banghart 9447: }
                   9448: 
                   9449: # called in portfolio select mode, to show files selected NOT in current directory
                   9450: sub files_not_in_path {
                   9451:     my ($user, $path) = @_;
                   9452:     my $filename = $user."savedfiles";
                   9453:     my @return_files;
                   9454:     my $path_part;
1.1117    foxr     9455:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9456:     while (my $line = <IN>) {
1.572     banghart 9457:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9458:         my @paths_and_file = split(m|/|, $line);
                   9459:         my $file_part = pop(@paths_and_file);
                   9460:         chomp($file_part);
                   9461:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9462:         $path_part .= '/';
                   9463:         my $path_and_file = $path_part.$file_part;
                   9464:         if ($path_part ne $path) {
1.800     albertel 9465:             push(@return_files, ($path_and_file));
1.572     banghart 9466:         }
                   9467:     }
1.800     albertel 9468:     close(OUT);
1.574     banghart 9469:     return (@return_files);
1.572     banghart 9470: }
                   9471: 
1.745     raeburn  9472: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9473: 
1.745     raeburn  9474: sub get_portfile_permissions {
                   9475:     my ($domain,$user) = @_;
1.613     albertel 9476:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9477:     my ($tmp)=keys(%current_permissions);
                   9478:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9479:     return \%current_permissions;
                   9480: }
                   9481: 
                   9482: #---------------------------------------------Get portfolio file access controls
                   9483: 
1.749     raeburn  9484: sub get_access_controls {
1.745     raeburn  9485:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9486:     my %access;
                   9487:     my $real_file = $file;
                   9488:     $file =~ s/\.meta$//;
1.745     raeburn  9489:     if (defined($file)) {
1.749     raeburn  9490:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9491:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9492:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9493:             }
                   9494:         }
1.745     raeburn  9495:     } else {
1.749     raeburn  9496:         foreach my $key (keys(%{$current_permissions})) {
                   9497:             if ($key =~ /\0accesscontrol$/) {
                   9498:                 if (defined($group)) {
                   9499:                     if ($key !~ m-^\Q$group\E/-) {
                   9500:                         next;
                   9501:                     }
                   9502:                 }
                   9503:                 my ($fullpath) = split(/\0/,$key);
                   9504:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9505:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9506:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9507:                     }
                   9508:                 }
                   9509:             }
                   9510:         }
                   9511:     }
                   9512:     return %access;
                   9513: }
                   9514: 
                   9515: sub modify_access_controls {
                   9516:     my ($file_name,$changes,$domain,$user)=@_;
                   9517:     my ($outcome,$deloutcome);
                   9518:     my %store_permissions;
                   9519:     my %new_values;
                   9520:     my %new_control;
                   9521:     my %translation;
                   9522:     my @deletions = ();
                   9523:     my $now = time;
                   9524:     if (exists($$changes{'activate'})) {
                   9525:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9526:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9527:             my $numnew = scalar(@newitems);
                   9528:             for (my $i=0; $i<$numnew; $i++) {
                   9529:                 my $newkey = $newitems[$i];
                   9530:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9531:                 if ($newkey =~ /^\d+:/) { 
                   9532:                     $newkey =~ s/^(\d+)/$newid/;
                   9533:                     $translation{$1} = $newid;
                   9534:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9535:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9536:                     $translation{$1} = $newid;
                   9537:                 }
1.749     raeburn  9538:                 $new_values{$file_name."\0".$newkey} = 
                   9539:                                           $$changes{'activate'}{$newitems[$i]};
                   9540:                 $new_control{$newkey} = $now;
                   9541:             }
                   9542:         }
                   9543:     }
                   9544:     my %todelete;
                   9545:     my %changed_items;
                   9546:     foreach my $action ('delete','update') {
                   9547:         if (exists($$changes{$action})) {
                   9548:             if (ref($$changes{$action}) eq 'HASH') {
                   9549:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9550:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9551:                     if ($action eq 'delete') { 
                   9552:                         $todelete{$itemnum} = 1;
                   9553:                     } else {
                   9554:                         $changed_items{$itemnum} = $key;
                   9555:                     }
                   9556:                 }
1.745     raeburn  9557:             }
                   9558:         }
1.749     raeburn  9559:     }
                   9560:     # get lock on access controls for file.
                   9561:     my $lockhash = {
                   9562:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9563:                                                        ':'.$env{'user.domain'},
                   9564:                    }; 
                   9565:     my $tries = 0;
                   9566:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9567:    
                   9568:     while (($gotlock ne 'ok') && $tries <3) {
                   9569:         $tries ++;
                   9570:         sleep 1;
                   9571:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9572:     }
                   9573:     if ($gotlock eq 'ok') {
                   9574:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9575:         my ($tmp)=keys(%curr_permissions);
                   9576:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9577:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9578:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9579:             if (ref($curr_controls) eq 'HASH') {
                   9580:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9581:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9582:                     if (defined($todelete{$itemnum})) {
                   9583:                         push(@deletions,$file_name."\0".$control_item);
                   9584:                     } else {
                   9585:                         if (defined($changed_items{$itemnum})) {
                   9586:                             $new_control{$changed_items{$itemnum}} = $now;
                   9587:                             push(@deletions,$file_name."\0".$control_item);
                   9588:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9589:                         } else {
                   9590:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9591:                         }
                   9592:                     }
1.745     raeburn  9593:                 }
                   9594:             }
                   9595:         }
1.970     raeburn  9596:         my ($group);
                   9597:         if (&is_course($domain,$user)) {
                   9598:             ($group,my $file) = split(/\//,$file_name,2);
                   9599:         }
1.749     raeburn  9600:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9601:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9602:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9603:         #  remove lock
                   9604:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9605:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9606:         my $sqlresult =
1.970     raeburn  9607:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9608:                                     $group);
1.749     raeburn  9609:     } else {
                   9610:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9611:     }
1.749     raeburn  9612:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9613: }
                   9614: 
1.827     raeburn  9615: sub make_public_indefinitely {
                   9616:     my ($requrl) = @_;
                   9617:     my $now = time;
                   9618:     my $action = 'activate';
                   9619:     my $aclnum = 0;
                   9620:     if (&is_portfolio_url($requrl)) {
                   9621:         my (undef,$udom,$unum,$file_name,$group) =
                   9622:             &parse_portfolio_url($requrl);
                   9623:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9624:         my %access_controls = &get_access_controls($current_perms,
                   9625:                                                    $group,$file_name);
                   9626:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9627:             my ($num,$scope,$end,$start) = 
                   9628:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9629:             if ($scope eq 'public') {
                   9630:                 if ($start <= $now && $end == 0) {
                   9631:                     $action = 'none';
                   9632:                 } else {
                   9633:                     $action = 'update';
                   9634:                     $aclnum = $num;
                   9635:                 }
                   9636:                 last;
                   9637:             }
                   9638:         }
                   9639:         if ($action eq 'none') {
                   9640:              return 'ok';
                   9641:         } else {
                   9642:             my %changes;
                   9643:             my $newend = 0;
                   9644:             my $newstart = $now;
                   9645:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9646:             $changes{$action}{$newkey} = {
                   9647:                 type => 'public',
                   9648:                 time => {
                   9649:                     start => $newstart,
                   9650:                     end   => $newend,
                   9651:                 },
                   9652:             };
                   9653:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9654:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9655:             return $outcome;
                   9656:         }
                   9657:     } else {
                   9658:         return 'invalid';
                   9659:     }
                   9660: }
                   9661: 
1.745     raeburn  9662: #------------------------------------------------------Get Marked as Read Only
                   9663: 
                   9664: sub get_marked_as_readonly {
                   9665:     my ($domain,$user,$what,$group) = @_;
                   9666:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9667:     my @readonly_files;
1.629     banghart 9668:     my $cmp1=$what;
                   9669:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9670:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9671:         if (defined($group)) {
                   9672:             if ($file_name !~ m-^\Q$group\E/-) {
                   9673:                 next;
                   9674:             }
                   9675:         }
1.561     banghart 9676:         if (ref($value) eq "ARRAY"){
                   9677:             foreach my $stored_what (@{$value}) {
1.629     banghart 9678:                 my $cmp2=$stored_what;
1.759     albertel 9679:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9680:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9681:                 }
1.629     banghart 9682:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9683:                     push(@readonly_files, $file_name);
1.745     raeburn  9684:                     last;
1.563     banghart 9685:                 } elsif (!defined($what)) {
                   9686:                     push(@readonly_files, $file_name);
1.745     raeburn  9687:                     last;
1.561     banghart 9688:                 }
                   9689:             }
1.745     raeburn  9690:         }
1.561     banghart 9691:     }
                   9692:     return @readonly_files;
                   9693: }
1.577     banghart 9694: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9695: 
1.577     banghart 9696: sub get_marked_as_readonly_hash {
1.745     raeburn  9697:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9698:     my %readonly_files;
1.745     raeburn  9699:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9700:         if (defined($group)) {
                   9701:             if ($file_name !~ m-^\Q$group\E/-) {
                   9702:                 next;
                   9703:             }
                   9704:         }
1.577     banghart 9705:         if (ref($value) eq "ARRAY"){
                   9706:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9707:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9708:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9709:                         if ($lock_descriptor eq 'graded') {
                   9710:                             $readonly_files{$file_name} = 'graded';
                   9711:                         } elsif ($lock_descriptor eq 'handback') {
                   9712:                             $readonly_files{$file_name} = 'handback';
                   9713:                         } else {
                   9714:                             if (!exists($readonly_files{$file_name})) {
                   9715:                                 $readonly_files{$file_name} = 'locked';
                   9716:                             }
                   9717:                         }
1.745     raeburn  9718:                     }
1.750     banghart 9719:                 } 
1.577     banghart 9720:             }
                   9721:         } 
                   9722:     }
                   9723:     return %readonly_files;
                   9724: }
1.559     banghart 9725: # ------------------------------------------------------------ Unmark as Read Only
                   9726: 
                   9727: sub unmark_as_readonly {
1.629     banghart 9728:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9729:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9730:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9731:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9732:     my $symb_crs = $what;
                   9733:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9734:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9735:     my ($tmp)=keys(%current_permissions);
                   9736:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9737:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9738:     foreach my $file (@readonly_files) {
1.759     albertel 9739: 	my $clean_file = &declutter_portfile($file);
                   9740: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9741: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9742:         my @new_locks;
                   9743:         my @del_keys;
                   9744:         if (ref($current_locks) eq "ARRAY"){
                   9745:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9746:                 my $compare=$locker;
1.749     raeburn  9747:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9748:                     $compare=join('',@{$locker});
1.746     raeburn  9749:                     if ($compare ne $symb_crs) {
                   9750:                         push(@new_locks, $locker);
                   9751:                     }
1.563     banghart 9752:                 }
                   9753:             }
1.650     albertel 9754:             if (scalar(@new_locks) > 0) {
1.563     banghart 9755:                 $current_permissions{$file} = \@new_locks;
                   9756:             } else {
                   9757:                 push(@del_keys, $file);
1.613     albertel 9758:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9759:                 delete($current_permissions{$file});
1.563     banghart 9760:             }
                   9761:         }
1.561     banghart 9762:     }
1.613     albertel 9763:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9764:     return;
                   9765: }
1.512     banghart 9766: 
1.17      www      9767: # ------------------------------------------------------------ Directory lister
                   9768: 
                   9769: sub dirlist {
1.955     raeburn  9770:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9771:     $uri=~s/^\///;
                   9772:     $uri=~s/\/$//;
1.253     stredwic 9773:     my ($udom, $uname);
1.955     raeburn  9774:     if ($getuserdir) {
1.253     stredwic 9775:         $udom = $userdomain;
                   9776:         $uname = $username;
1.955     raeburn  9777:     } else {
                   9778:         (undef,$udom,$uname)=split(/\//,$uri);
                   9779:         if(defined($userdomain)) {
                   9780:             $udom = $userdomain;
                   9781:         }
                   9782:         if(defined($username)) {
                   9783:             $uname = $username;
                   9784:         }
1.253     stredwic 9785:     }
1.955     raeburn  9786:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9787: 
1.955     raeburn  9788:     $dirRoot = $perlvar{'lonDocRoot'};
                   9789:     if (defined($getpropath)) {
                   9790:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9791:         $dirRoot =~ s/\/$//;
1.955     raeburn  9792:     } elsif (defined($getuserdir)) {
                   9793:         my $subdir=$uname.'__';
                   9794:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9795:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9796:                    ."/$udom/$subdir/$uname";
                   9797:     } elsif (defined($alternateRoot)) {
                   9798:         $dirRoot = $alternateRoot;
1.751     banghart 9799:     }
1.253     stredwic 9800: 
                   9801:     if($udom) {
                   9802:         if($uname) {
1.1135    raeburn  9803:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9804:             if ($uhome eq 'no_host') {
                   9805:                 return ([],'no_host');
                   9806:             }
1.955     raeburn  9807:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9808:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9809:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9810:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9811:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9812:             } else {
                   9813:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9814:             }
1.605     matthew  9815:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9816:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9817:                 @listing_results = split(/:/,$listing);
                   9818:             } else {
                   9819:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9820:             }
1.1135    raeburn  9821:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9822:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9823:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9824:                 return ([],$listing);
                   9825:             } else {
                   9826:                 return (\@listing_results);
1.1135    raeburn  9827:             }
1.955     raeburn  9828:         } elsif(!$alternateRoot) {
1.1136    raeburn  9829:             my (%allusers,%listerror);
1.841     albertel 9830: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9831:  	    foreach my $tryserver (keys(%servers)) {
                   9832:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9833:                                   &escape($udom),$tryserver);
                   9834:                 if ($listing eq 'unknown_cmd') {
                   9835: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9836: 				      $udom, $tryserver);
                   9837:                 } else {
                   9838:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9839:                 }
1.841     albertel 9840: 		if ($listing eq 'unknown_cmd') {
                   9841: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9842: 				      $udom, $tryserver);
                   9843: 		    @listing_results = split(/:/,$listing);
                   9844: 		} else {
                   9845: 		    @listing_results =
                   9846: 			map { &unescape($_); } split(/:/,$listing);
                   9847: 		}
1.1136    raeburn  9848:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9849:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9850:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9851:                     $listerror{$tryserver} = $listing;
                   9852:                 } else {
1.841     albertel 9853: 		    foreach my $line (@listing_results) {
                   9854: 			my ($entry) = split(/&/,$line,2);
                   9855: 			$allusers{$entry} = 1;
                   9856: 		    }
                   9857: 		}
1.253     stredwic 9858:             }
1.1136    raeburn  9859:             my @alluserslist=();
1.800     albertel 9860:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9861:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9862:             }
1.1136    raeburn  9863:             return (\@alluserslist);
1.253     stredwic 9864:         } else {
1.1136    raeburn  9865:             return ([],'missing username');
1.253     stredwic 9866:         }
1.955     raeburn  9867:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9868:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9869:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9870:         return (\@all_domains);
1.955     raeburn  9871:     } else {
1.1136    raeburn  9872:         return ([],'missing domain');
1.275     stredwic 9873:     }
                   9874: }
                   9875: 
                   9876: # --------------------------------------------- GetFileTimestamp
                   9877: # This function utilizes dirlist and returns the date stamp for
                   9878: # when it was last modified.  It will also return an error of -1
                   9879: # if an error occurs
                   9880: 
                   9881: sub GetFileTimestamp {
1.955     raeburn  9882:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9883:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9884:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9885:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9886:                                     undef,$getuserdir);
                   9887:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9888:         return -1;
                   9889:     }
                   9890:     if (ref($fileref) eq 'ARRAY') {
                   9891:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9892:         # @stats contains first the filename, then the stat output
                   9893:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9894:     } else {
                   9895:         return -1;
1.253     stredwic 9896:     }
1.26      www      9897: }
                   9898: 
1.712     albertel 9899: sub stat_file {
                   9900:     my ($uri) = @_;
1.787     albertel 9901:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9902: 
1.955     raeburn  9903:     my ($udom,$uname,$file);
1.712     albertel 9904:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9905: 	($udom,$uname,$file) =
1.811     albertel 9906: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9907: 	$file = 'userfiles/'.$file;
                   9908:     }
                   9909:     if ($uri =~ m-^/res/-) {
                   9910: 	($udom,$uname) = 
1.807     albertel 9911: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9912: 	$file = $uri;
                   9913:     }
                   9914: 
                   9915:     if (!$udom || !$uname || !$file) {
                   9916: 	# unable to handle the uri
                   9917: 	return ();
                   9918:     }
1.956     raeburn  9919:     my $getpropath;
                   9920:     if ($file =~ /^userfiles\//) {
                   9921:         $getpropath = 1;
                   9922:     }
1.1136    raeburn  9923:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9924:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9925:         return ();
                   9926:     } else {
                   9927:         if (ref($listref) eq 'ARRAY') {
                   9928:             my @stats = split('&',$listref->[0]);
                   9929: 	    shift(@stats); #filename is first
                   9930: 	    return @stats;
                   9931:         }
1.712     albertel 9932:     }
                   9933:     return ();
                   9934: }
                   9935: 
1.26      www      9936: # -------------------------------------------------------- Value of a Condition
                   9937: 
1.713     albertel 9938: # gets the value of a specific preevaluated condition
                   9939: #    stored in the string  $env{user.state.<cid>}
                   9940: # or looks up a condition reference in the bighash and if if hasn't
                   9941: # already been evaluated recurses into docondval to get the value of
                   9942: # the condition, then memoizing it to 
                   9943: #   $env{user.state.<cid>.<condition>}
1.40      www      9944: sub directcondval {
                   9945:     my $number=shift;
1.620     albertel 9946:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 9947: 	&Apache::lonuserstate::evalstate();
                   9948:     }
1.713     albertel 9949:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   9950: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   9951:     } elsif ($number =~ /^_/) {
                   9952: 	my $sub_condition;
                   9953: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9954: 		&GDBM_READER(),0640)) {
                   9955: 	    $sub_condition=$bighash{'conditions'.$number};
                   9956: 	    untie(%bighash);
                   9957: 	}
                   9958: 	my $value = &docondval($sub_condition);
1.949     raeburn  9959: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 9960: 	return $value;
                   9961:     }
1.620     albertel 9962:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   9963:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      9964:     } else {
                   9965:        return 2;
                   9966:     }
                   9967: }
                   9968: 
1.713     albertel 9969: # get the collection of conditions for this resource
1.26      www      9970: sub condval {
                   9971:     my $condidx=shift;
1.54      www      9972:     my $allpathcond='';
1.713     albertel 9973:     foreach my $cond (split(/\|/,$condidx)) {
                   9974: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   9975: 	    $allpathcond.=
                   9976: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   9977: 	}
1.191     harris41 9978:     }
1.54      www      9979:     $allpathcond=~s/\|$//;
1.713     albertel 9980:     return &docondval($allpathcond);
                   9981: }
                   9982: 
                   9983: #evaluates an expression of conditions
                   9984: sub docondval {
                   9985:     my ($allpathcond) = @_;
                   9986:     my $result=0;
                   9987:     if ($env{'request.course.id'}
                   9988: 	&& defined($allpathcond)) {
                   9989: 	my $operand='|';
                   9990: 	my @stack;
                   9991: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   9992: 	    if ($chunk eq '(') {
                   9993: 		push @stack,($operand,$result);
                   9994: 	    } elsif ($chunk eq ')') {
                   9995: 		my $before=pop @stack;
                   9996: 		if (pop @stack eq '&') {
                   9997: 		    $result=$result>$before?$before:$result;
                   9998: 		} else {
                   9999: 		    $result=$result>$before?$result:$before;
                   10000: 		}
                   10001: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10002: 		$operand=$chunk;
                   10003: 	    } else {
                   10004: 		my $new=directcondval($chunk);
                   10005: 		if ($operand eq '&') {
                   10006: 		    $result=$result>$new?$new:$result;
                   10007: 		} else {
                   10008: 		    $result=$result>$new?$result:$new;
                   10009: 		}
                   10010: 	    }
                   10011: 	}
1.26      www      10012:     }
                   10013:     return $result;
1.421     albertel 10014: }
                   10015: 
                   10016: # ---------------------------------------------------- Devalidate courseresdata
                   10017: 
                   10018: sub devalidatecourseresdata {
                   10019:     my ($coursenum,$coursedomain)=@_;
                   10020:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10021:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10022: }
                   10023: 
1.763     www      10024: 
1.200     www      10025: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10026: #
                   10027: #  Parameters:
                   10028: #      $coursenum    - Number of the course.
                   10029: #      $coursedomain - Domain at which the course was created.
                   10030: #  Returns:
                   10031: #     A hash of the course parameters along (I think) with timestamps
                   10032: #     and version info.
1.877     foxr     10033: 
1.624     albertel 10034: sub get_courseresdata {
                   10035:     my ($coursenum,$coursedomain)=@_;
1.200     www      10036:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10037:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10038:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10039:     my %dumpreply;
1.417     albertel 10040:     unless (defined($cached)) {
1.624     albertel 10041: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10042: 	$result=\%dumpreply;
1.251     albertel 10043: 	my ($tmp) = keys(%dumpreply);
                   10044: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10045: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10046: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10047: 	    return $tmp;
1.416     albertel 10048: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10049: 	    $result=undef;
1.599     albertel 10050: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10051: 	}
                   10052:     }
1.624     albertel 10053:     return $result;
                   10054: }
                   10055: 
1.633     albertel 10056: sub devalidateuserresdata {
                   10057:     my ($uname,$udom)=@_;
                   10058:     my $hashid="$udom:$uname";
                   10059:     &devalidate_cache_new('userres',$hashid);
                   10060: }
                   10061: 
1.624     albertel 10062: sub get_userresdata {
                   10063:     my ($uname,$udom)=@_;
                   10064:     #most student don\'t have any data set, check if there is some data
                   10065:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10066: 
                   10067:     my $hashid="$udom:$uname";
                   10068:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10069:     if (!defined($cached)) {
                   10070: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10071: 	$result=\%resourcedata;
                   10072: 	&do_cache_new('userres',$hashid,$result,600);
                   10073:     }
                   10074:     my ($tmp)=keys(%$result);
                   10075:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10076: 	return $result;
                   10077:     }
                   10078:     #error 2 occurs when the .db doesn't exist
                   10079:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  10080:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10081: 	    &logthis("<font color=\"blue\">WARNING:".
                   10082: 		     " Trying to get resource data for ".
                   10083: 		     $uname." at ".$udom.": ".
                   10084: 		     $tmp."</font>");
                   10085:         }
1.624     albertel 10086:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10087: 	#&EXT_cache_set($udom,$uname);
                   10088: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10089: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10090:     }
                   10091:     return $tmp;
                   10092: }
1.879     foxr     10093: #----------------------------------------------- resdata - return resource data
                   10094: #  Purpose:
                   10095: #    Return resource data for either users or for a course.
                   10096: #  Parameters:
                   10097: #     $name      - Course/user name.
                   10098: #     $domain    - Name of the domain the user/course is registered on.
                   10099: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   10100: #     @which     - Array of names of resources desired.
                   10101: #  Returns:
                   10102: #     The value of the first reasource in @which that is found in the
                   10103: #     resource hash.
                   10104: #  Exceptional Conditions:
                   10105: #     If the $type passed in is not valid (not the string 'course' or 
                   10106: #     'user', an undefined  reference is returned.
                   10107: #     If none of the resources are found, an undef is returned
1.624     albertel 10108: sub resdata {
                   10109:     my ($name,$domain,$type,@which)=@_;
                   10110:     my $result;
                   10111:     if ($type eq 'course') {
                   10112: 	$result=&get_courseresdata($name,$domain);
                   10113:     } elsif ($type eq 'user') {
                   10114: 	$result=&get_userresdata($name,$domain);
                   10115:     }
                   10116:     if (!ref($result)) { return $result; }    
1.251     albertel 10117:     foreach my $item (@which) {
1.927     albertel 10118: 	if (defined($result->{$item->[0]})) {
                   10119: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10120: 	}
1.250     albertel 10121:     }
1.291     albertel 10122:     return undef;
1.200     www      10123: }
                   10124: 
1.1172.2.31  raeburn  10125: sub get_numsuppfiles {
                   10126:     my ($cnum,$cdom,$ignorecache)=@_;
                   10127:     my $hashid=$cnum.':'.$cdom;
                   10128:     my ($suppcount,$cached);
                   10129:     unless ($ignorecache) {
                   10130:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10131:     }
                   10132:     unless (defined($cached)) {
                   10133:         my $chome=&homeserver($cnum,$cdom);
                   10134:         unless ($chome eq 'no_host') {
                   10135:             ($suppcount,my $errors) = (0,0);
                   10136:             my $suppmap = 'supplemental.sequence';
                   10137:             ($suppcount,$errors) =
                   10138:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10139:         }
                   10140:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10141:     }
                   10142:     return $suppcount;
                   10143: }
                   10144: 
1.379     matthew  10145: #
                   10146: # EXT resource caching routines
                   10147: #
                   10148: 
                   10149: sub clear_EXT_cache_status {
1.383     albertel 10150:     &delenv('cache.EXT.');
1.379     matthew  10151: }
                   10152: 
                   10153: sub EXT_cache_status {
                   10154:     my ($target_domain,$target_user) = @_;
1.383     albertel 10155:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10156:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10157:         # We know already the user has no data
                   10158:         return 1;
                   10159:     } else {
                   10160:         return 0;
                   10161:     }
                   10162: }
                   10163: 
                   10164: sub EXT_cache_set {
                   10165:     my ($target_domain,$target_user) = @_;
1.383     albertel 10166:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10167:     #&appenv({$cachename => time});
1.379     matthew  10168: }
                   10169: 
1.28      www      10170: # --------------------------------------------------------- Value of a Variable
1.58      www      10171: sub EXT {
1.715     albertel 10172: 
1.1172.2.28  raeburn  10173:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10174:     unless ($varname) { return ''; }
1.218     albertel 10175:     #get real user name/domain, courseid and symb
                   10176:     my $courseid;
1.359     albertel 10177:     my $publicuser;
1.427     www      10178:     if ($symbparm) {
                   10179: 	$symbparm=&get_symb_from_alias($symbparm);
                   10180:     }
1.218     albertel 10181:     if (!($uname && $udom)) {
1.790     albertel 10182:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10183:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10184:     } else {
1.620     albertel 10185: 	$courseid=$env{'request.course.id'};
1.218     albertel 10186:     }
1.48      www      10187:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10188:     my $rest;
1.320     albertel 10189:     if (defined($therest[0])) {
1.48      www      10190:        $rest=join('.',@therest);
                   10191:     } else {
                   10192:        $rest='';
                   10193:     }
1.320     albertel 10194: 
1.57      www      10195:     my $qualifierrest=$qualifier;
                   10196:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10197:     my $spacequalifierrest=$space;
                   10198:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10199:     if ($realm eq 'user') {
1.48      www      10200: # --------------------------------------------------------------- user.resource
                   10201: 	if ($space eq 'resource') {
1.651     albertel 10202: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10203: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10204: 		 &&
1.744     albertel 10205: 		 ($symbparm eq &symbread()) ) {	
                   10206: 		# if we are in the middle of processing the resource the
                   10207: 		# get the value we are planning on committing
                   10208:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10209:                     return $Apache::lonhomework::results{$qualifierrest};
                   10210:                 } else {
                   10211:                     return $Apache::lonhomework::history{$qualifierrest};
                   10212:                 }
1.335     albertel 10213: 	    } else {
1.359     albertel 10214: 		my %restored;
1.620     albertel 10215: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10216: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10217: 		} else {
                   10218: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10219: 		}
1.335     albertel 10220: 		return $restored{$qualifierrest};
                   10221: 	    }
1.48      www      10222: # ----------------------------------------------------------------- user.access
                   10223:         } elsif ($space eq 'access') {
1.218     albertel 10224: 	    # FIXME - not supporting calls for a specific user
1.48      www      10225:             return &allowed($qualifier,$rest);
                   10226: # ------------------------------------------ user.preferences, user.environment
                   10227:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10228: 	    if (($uname eq $env{'user.name'}) &&
                   10229: 		($udom eq $env{'user.domain'})) {
                   10230: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10231: 	    } else {
1.359     albertel 10232: 		my %returnhash;
                   10233: 		if (!$publicuser) {
                   10234: 		    %returnhash=&userenvironment($udom,$uname,
                   10235: 						 $qualifierrest);
                   10236: 		}
1.218     albertel 10237: 		return $returnhash{$qualifierrest};
                   10238: 	    }
1.48      www      10239: # ----------------------------------------------------------------- user.course
                   10240:         } elsif ($space eq 'course') {
1.218     albertel 10241: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10242:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10243: # ------------------------------------------------------------------- user.role
                   10244:         } elsif ($space eq 'role') {
1.218     albertel 10245: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10246:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10247:             if ($qualifier eq 'value') {
                   10248: 		return $role;
                   10249:             } elsif ($qualifier eq 'extent') {
                   10250:                 return $where;
                   10251:             }
                   10252: # ----------------------------------------------------------------- user.domain
                   10253:         } elsif ($space eq 'domain') {
1.218     albertel 10254:             return $udom;
1.48      www      10255: # ------------------------------------------------------------------- user.name
                   10256:         } elsif ($space eq 'name') {
1.218     albertel 10257:             return $uname;
1.48      www      10258: # ---------------------------------------------------- Any other user namespace
1.29      www      10259:         } else {
1.359     albertel 10260: 	    my %reply;
                   10261: 	    if (!$publicuser) {
                   10262: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10263: 	    }
                   10264: 	    return $reply{$qualifierrest};
1.48      www      10265:         }
1.236     www      10266:     } elsif ($realm eq 'query') {
                   10267: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10268:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10269: 						[$spacequalifierrest]);
1.620     albertel 10270: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10271:    } elsif ($realm eq 'request') {
1.48      www      10272: # ------------------------------------------------------------- request.browser
                   10273:         if ($space eq 'browser') {
1.1145    bisitz   10274:             return $env{'browser.'.$qualifier};
1.57      www      10275: # ------------------------------------------------------------ request.filename
                   10276:         } else {
1.620     albertel 10277:             return $env{'request.'.$spacequalifierrest};
1.29      www      10278:         }
1.28      www      10279:     } elsif ($realm eq 'course') {
1.48      www      10280: # ---------------------------------------------------------- course.description
1.620     albertel 10281:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10282:     } elsif ($realm eq 'resource') {
1.165     www      10283: 
1.620     albertel 10284: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10285: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10286: 	}
1.693     albertel 10287: 
1.1172.2.30  raeburn  10288:         if ($qualifier eq '') {
                   10289: 	    if ($space eq 'title') {
                   10290: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10291: 	        return &gettitle($symbparm);
                   10292: 	    }
1.693     albertel 10293: 	
1.1172.2.30  raeburn  10294: 	    if ($space eq 'map') {
                   10295: 	        my ($map) = &decode_symb($symbparm);
                   10296: 	        return &symbread($map);
                   10297: 	    }
                   10298:             if ($space eq 'maptitle') {
                   10299:                 my ($map) = &decode_symb($symbparm);
                   10300:                 return &gettitle($map);
                   10301:             }
                   10302: 	    if ($space eq 'filename') {
                   10303: 	        if ($symbparm) {
                   10304: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10305: 	        }
                   10306: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10307: 	    }
1.1172.2.30  raeburn  10308: 
                   10309:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10310:                 if ($space eq 'visibleparts') {
                   10311:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10312:                     my $item;
                   10313:                     if (ref($navmap)) {
                   10314:                         my $res = $navmap->getBySymb($symbparm);
                   10315:                         my $parts = $res->parts();
                   10316:                         if (ref($parts) eq 'ARRAY') {
                   10317:                             $item = join(',',@{$parts});
                   10318:                         }
                   10319:                         undef($navmap);
                   10320:                     }
                   10321:                     return $item;
                   10322:                 }
                   10323:             }
                   10324:         }
1.693     albertel 10325: 
                   10326: 	my ($section, $group, @groups);
1.593     albertel 10327: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10328:         if (($courseid eq '') && ($cid)) {
                   10329:             $courseid = $cid;
                   10330:         }
                   10331: 	if (($symbparm && $courseid) && 
                   10332: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10333: 
1.218     albertel 10334: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10335: 
1.60      www      10336: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10337: 	    my $symbp=$symbparm;
1.735     albertel 10338: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10339: 
                   10340: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10341: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10342: 
1.620     albertel 10343: 	    if (($env{'user.name'} eq $uname) &&
                   10344: 		($env{'user.domain'} eq $udom)) {
                   10345: 		$section=$env{'request.course.sec'};
1.733     raeburn  10346:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10347:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10348: 	    } else {
1.539     albertel 10349: 		if (! defined($usection)) {
1.551     albertel 10350: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10351: 		} else {
                   10352: 		    $section = $usection;
                   10353: 		}
1.733     raeburn  10354:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10355: 	    }
                   10356: 
                   10357: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10358: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10359: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10360: 
1.593     albertel 10361: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10362: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10363: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10364: 
1.60      www      10365: # ----------------------------------------------------------- first, check user
1.624     albertel 10366: 
                   10367: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10368: 				       ([$courselevelr,'resource'],
                   10369: 					[$courselevelm,'map'     ],
                   10370: 					[$courselevel, 'course'  ]));
1.931     albertel 10371: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10372: 
1.594     albertel 10373: # ------------------------------------------------ second, check some of course
1.684     raeburn  10374:             my $coursereply;
1.691     raeburn  10375:             if (@groups > 0) {
                   10376:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10377:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10378:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10379:             }
1.96      www      10380: 
1.684     raeburn  10381: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10382: 				  $env{'course.'.$courseid.'.domain'},
                   10383: 				  'course',
                   10384: 				  ([$seclevelr,   'resource'],
                   10385: 				   [$seclevelm,   'map'     ],
                   10386: 				   [$seclevel,    'course'  ],
                   10387: 				   [$courselevelr,'resource']));
                   10388: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10389: 
1.60      www      10390: # ------------------------------------------------------ third, check map parms
1.218     albertel 10391: 	    my %parmhash=();
                   10392: 	    my $thisparm='';
                   10393: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10394: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10395: 		    &GDBM_READER(),0640)) {
1.218     albertel 10396: 		$thisparm=$parmhash{$symbparm};
                   10397: 		untie(%parmhash);
                   10398: 	    }
1.927     albertel 10399: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10400: 	}
1.594     albertel 10401: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10402: 
1.218     albertel 10403: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10404: 	my $filename;
                   10405: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10406: 	if ($symbparm) {
1.409     www      10407: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10408: 	} else {
1.620     albertel 10409: 	    $filename=$env{'request.filename'};
1.282     albertel 10410: 	}
                   10411: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10412: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10413: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10414: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10415: 
1.927     albertel 10416: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10417: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10418: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10419: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10420: 				     $env{'course.'.$courseid.'.domain'},
                   10421: 				     'course',
1.927     albertel 10422: 				     ([$courselevelm,'map'   ],
                   10423: 				      [$courselevel, 'course']));
                   10424: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10425: 	}
1.145     www      10426: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10427: 	unless ($space eq '0') {
1.336     albertel 10428: 	    my @parts=split(/_/,$space);
                   10429: 	    my $id=pop(@parts);
                   10430: 	    my $part=join('_',@parts);
                   10431: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10432: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10433: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10434: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10435: 	}
1.395     albertel 10436: 	if ($recurse) { return undef; }
                   10437: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10438: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10439: # ---------------------------------------------------- Any other user namespace
                   10440:     } elsif ($realm eq 'environment') {
                   10441: # ----------------------------------------------------------------- environment
1.620     albertel 10442: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10443: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10444: 	} else {
1.770     albertel 10445: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10446: 		return '';
                   10447: 	    }
1.219     albertel 10448: 	    my %returnhash=&userenvironment($udom,$uname,
                   10449: 					    $spacequalifierrest);
                   10450: 	    return $returnhash{$spacequalifierrest};
                   10451: 	}
1.28      www      10452:     } elsif ($realm eq 'system') {
1.48      www      10453: # ----------------------------------------------------------------- system.time
                   10454: 	if ($space eq 'time') {
                   10455: 	    return time;
                   10456:         }
1.696     albertel 10457:     } elsif ($realm eq 'server') {
                   10458: # ----------------------------------------------------------------- system.time
                   10459: 	if ($space eq 'name') {
                   10460: 	    return $ENV{'SERVER_NAME'};
                   10461:         }
1.28      www      10462:     }
1.48      www      10463:     return '';
1.61      www      10464: }
                   10465: 
1.927     albertel 10466: sub get_reply {
                   10467:     my ($reply_value) = @_;
1.940     raeburn  10468:     if (ref($reply_value) eq 'ARRAY') {
                   10469:         if (wantarray) {
                   10470: 	    return @$reply_value;
                   10471:         }
                   10472:         return $reply_value->[0];
                   10473:     } else {
                   10474:         return $reply_value;
1.927     albertel 10475:     }
                   10476: }
                   10477: 
1.691     raeburn  10478: sub check_group_parms {
                   10479:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10480:     my @groupitems = ();
                   10481:     my $resultitem;
1.927     albertel 10482:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10483:     foreach my $group (@{$groups}) {
                   10484:         foreach my $level (@levels) {
1.927     albertel 10485:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10486:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10487:         }
                   10488:     }
                   10489:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10490:                             $env{'course.'.$courseid.'.domain'},
                   10491:                                      'course',@groupitems);
                   10492:     return $coursereply;
                   10493: }
                   10494: 
                   10495: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10496:     my ($courseid,@groups) = @_;
                   10497:     @groups = sort(@groups);
1.691     raeburn  10498:     return @groups;
                   10499: }
                   10500: 
1.395     albertel 10501: sub packages_tab_default {
                   10502:     my ($uri,$varname)=@_;
                   10503:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10504: 
                   10505:     my (@extension,@specifics,$do_default);
                   10506:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10507: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10508: 	if ($pack_type eq 'default') {
                   10509: 	    $do_default=1;
                   10510: 	} elsif ($pack_type eq 'extension') {
                   10511: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10512: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10513: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10514: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10515: 	}
                   10516:     }
                   10517:     # first look for a package that matches the requested part id
                   10518:     foreach my $package (@specifics) {
                   10519: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10520: 	next if ($pack_part ne $part);
                   10521: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10522: 	    return $packagetab{"$pack_type&$name&default"};
                   10523: 	}
                   10524:     }
                   10525:     # look for any possible matching non extension_ package
                   10526:     foreach my $package (@specifics) {
                   10527: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10528: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10529: 	    return $packagetab{"$pack_type&$name&default"};
                   10530: 	}
1.585     albertel 10531: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10532: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10533: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10534: 	}
                   10535:     }
1.738     albertel 10536:     # look for any posible extension_ match
                   10537:     foreach my $package (@extension) {
                   10538: 	my ($package,$pack_type)=@{$package};
                   10539: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10540: 	    return $packagetab{"$pack_type&$name&default"};
                   10541: 	}
                   10542: 	if (defined($packagetab{$package."&$name&default"})) {
                   10543: 	    return $packagetab{$package."&$name&default"};
                   10544: 	}
                   10545:     }
                   10546:     # look for a global default setting
                   10547:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10548: 	return $packagetab{"default&$name&default"};
                   10549:     }
1.395     albertel 10550:     return undef;
                   10551: }
                   10552: 
1.334     albertel 10553: sub add_prefix_and_part {
                   10554:     my ($prefix,$part)=@_;
                   10555:     my $keyroot;
                   10556:     if (defined($prefix) && $prefix !~ /^__/) {
                   10557: 	# prefix that has a part already
                   10558: 	$keyroot=$prefix;
                   10559:     } elsif (defined($prefix)) {
                   10560: 	# prefix that is missing a part
                   10561: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10562:     } else {
                   10563: 	# no prefix at all
                   10564: 	if (defined($part)) { $keyroot='_'.$part; }
                   10565:     }
                   10566:     return $keyroot;
                   10567: }
                   10568: 
1.71      www      10569: # ---------------------------------------------------------------- Get metadata
                   10570: 
1.599     albertel 10571: my %metaentry;
1.1070    www      10572: my %importedpartids;
1.71      www      10573: sub metadata {
1.176     www      10574:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10575:     $uri=&declutter($uri);
1.288     albertel 10576:     # if it is a non metadata possible uri return quickly
1.529     albertel 10577:     if (($uri eq '') || 
                   10578: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  10579: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10580:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10581: 	return undef;
                   10582:     }
1.1172.2.49  raeburn  10583:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10584: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10585: 	return undef;
1.288     albertel 10586:     }
1.73      www      10587:     my $filename=$uri;
                   10588:     $uri=~s/\.meta$//;
1.172     www      10589: #
                   10590: # Is the metadata already cached?
1.177     www      10591: # Look at timestamp of caching
1.172     www      10592: # Everything is cached by the main uri, libraries are never directly cached
                   10593: #
1.428     albertel 10594:     if (!defined($liburi)) {
1.599     albertel 10595: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10596: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10597:     }
                   10598:     {
1.1069    www      10599: # Imported parts would go here
1.1070    www      10600:         my %importedids=();
                   10601:         my @origfileimportpartids=();
1.1069    www      10602:         my $importedparts=0;
1.172     www      10603: #
                   10604: # Is this a recursive call for a library?
                   10605: #
1.599     albertel 10606: #	if (! exists($metacache{$uri})) {
                   10607: #	    $metacache{$uri}={};
                   10608: #	}
1.924     albertel 10609: 	my $cachetime = 60*60;
1.171     www      10610:         if ($liburi) {
                   10611: 	    $liburi=&declutter($liburi);
                   10612:             $filename=$liburi;
1.401     bowersj2 10613:         } else {
1.599     albertel 10614: 	    &devalidate_cache_new('meta',$uri);
                   10615: 	    undef(%metaentry);
1.401     bowersj2 10616: 	}
1.140     www      10617:         my %metathesekeys=();
1.73      www      10618:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10619: 	my $metastring;
1.1140    www      10620: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10621: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10622: 	    $metastring = 
1.929     albertel 10623: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10624: 					  ('grade_target' => 'meta'));
                   10625: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10626: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10627:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10628: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10629: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10630: 	    $metastring=&getfile($file);
1.489     albertel 10631: 	}
1.208     albertel 10632:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10633:         my $token;
1.140     www      10634:         undef %metathesekeys;
1.71      www      10635:         while ($token=$parser->get_token) {
1.339     albertel 10636: 	    if ($token->[0] eq 'S') {
                   10637: 		if (defined($token->[2]->{'package'})) {
1.172     www      10638: #
                   10639: # This is a package - get package info
                   10640: #
1.339     albertel 10641: 		    my $package=$token->[2]->{'package'};
                   10642: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10643: 		    if (defined($token->[2]->{'id'})) { 
                   10644: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10645: 		    }
1.599     albertel 10646: 		    if ($metaentry{':packages'}) {
                   10647: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10648: 		    } else {
1.599     albertel 10649: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10650: 		    }
1.736     albertel 10651: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10652: 			my $part=$keyroot;
                   10653: 			$part=~s/^\_//;
1.736     albertel 10654: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10655: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10656: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10657: 			    # ignore package.tab specified default values
                   10658:                             # here &package_tab_default() will fetch those
                   10659: 			    if ($subp eq 'default') { next; }
1.736     albertel 10660: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10661: 			    my $unikey;
                   10662: 			    if ($pack =~ /_0$/) {
                   10663: 				$unikey='parameter_0_'.$name;
                   10664: 				$part=0;
                   10665: 			    } else {
                   10666: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10667: 			    }
1.339     albertel 10668: 			    if ($subp eq 'display') {
                   10669: 				$value.=' [Part: '.$part.']';
                   10670: 			    }
1.599     albertel 10671: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10672: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10673: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10674: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10675: 			    }
1.599     albertel 10676: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10677: 				$metaentry{':'.$unikey}=
                   10678: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10679: 			    }
1.339     albertel 10680: 			}
                   10681: 		    }
                   10682: 		} else {
1.172     www      10683: #
                   10684: # This is not a package - some other kind of start tag
1.339     albertel 10685: #
                   10686: 		    my $entry=$token->[1];
1.1068    www      10687: 		    my $unikey='';
1.175     www      10688: 
1.339     albertel 10689: 		    if ($entry eq 'import') {
1.175     www      10690: #
                   10691: # Importing a library here
1.339     albertel 10692: #
1.1067    www      10693:                         my $location=$parser->get_text('/import');
                   10694:                         my $dir=$filename;
                   10695:                         $dir=~s|[^/]*$||;
                   10696:                         $location=&filelocation($dir,$location);
1.1069    www      10697:                        
1.1068    www      10698:                         my $importmode=$token->[2]->{'importmode'};
                   10699:                         if ($importmode eq 'problem') {
1.1069    www      10700: # Import as problem/response
1.1068    www      10701:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10702:                         } elsif ($importmode eq 'part') {
                   10703: # Import as part(s)
1.1069    www      10704:                            $importedparts=1;
                   10705: # We need to get the original file and the imported file to get the part order correct
                   10706: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10707: # Load and inspect original file
1.1070    www      10708:                            if ($#origfileimportpartids<0) {
                   10709:                               undef(%importedpartids);
                   10710:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10711:                               my $origfile=&getfile($origfilelocation);
                   10712:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10713:                            }
                   10714: 
1.1069    www      10715: # Load and inspect imported file
                   10716:                            my $impfile=&getfile($location);
                   10717:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10718:                            if ($#impfilepartids>=0) {
                   10719: # This problem had parts
1.1070    www      10720:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10721:                            } else {
                   10722: # Importing by turning a single problem into a problem part
                   10723: # It gets the import-tags ID as part-ID
                   10724:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10725:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10726:                            }
1.1068    www      10727:                         } else {
                   10728: # Normal import
                   10729:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10730:                            if (defined($token->[2]->{'id'})) {
                   10731:                               $unikey.='_'.$token->[2]->{'id'};
                   10732:                            }
1.1067    www      10733:                         }
                   10734: 
1.339     albertel 10735: 			if ($depthcount<20) {
1.736     albertel 10736: 			    my $metadata = 
                   10737: 				&metadata($uri,'keys', $location,$unikey,
                   10738: 					  $depthcount+1);
                   10739: 			    foreach my $meta (split(',',$metadata)) {
                   10740: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10741: 				$metathesekeys{$meta}=1;
1.339     albertel 10742: 			    }
1.1068    www      10743: 			
                   10744:                         }
1.1067    www      10745: 		    } else {
                   10746: #
                   10747: # Not importing, some other kind of non-package, non-library start tag
                   10748: # 
                   10749:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10750:                         if (defined($token->[2]->{'id'})) {
                   10751:                             $unikey.='_'.$token->[2]->{'id'};
                   10752:                         }
1.339     albertel 10753: 			if (defined($token->[2]->{'name'})) { 
                   10754: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10755: 			}
                   10756: 			$metathesekeys{$unikey}=1;
1.736     albertel 10757: 			foreach my $param (@{$token->[3]}) {
                   10758: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10759: 				$token->[2]->{$param};
1.339     albertel 10760: 			}
                   10761: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10762: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10763: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10764: 		 # only ws inside the tag, and not in default, so use default
                   10765: 		 # as value
1.599     albertel 10766: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10767: 			} elsif ( $internaltext =~ /\S/ ) {
                   10768: 		  # something interesting inside the tag
                   10769: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10770: 			} else {
1.908     albertel 10771: 		  # no interesting values, don't set a default
1.339     albertel 10772: 			}
1.172     www      10773: # end of not-a-package not-a-library import
1.339     albertel 10774: 		    }
1.172     www      10775: # end of not-a-package start tag
1.339     albertel 10776: 		}
1.172     www      10777: # the next is the end of "start tag"
1.339     albertel 10778: 	    }
                   10779: 	}
1.483     albertel 10780: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10781: 	$extension = lc($extension);
                   10782: 	if ($extension eq 'htm') { $extension='html'; }
                   10783: 
1.737     albertel 10784: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10785: 	    #no specific packages #how's our extension
                   10786: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10787: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10788: 					 \%metathesekeys);
                   10789: 	}
1.883     albertel 10790: 
                   10791: 	if (!exists($metaentry{':packages'})
                   10792: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10793: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10794: 		#no specific packages well let's get default then
                   10795: 		if ($key!~/^default&/) { next; }
1.488     albertel 10796: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10797: 					     \%metathesekeys);
                   10798: 	    }
                   10799: 	}
1.338     www      10800: # are there custom rights to evaluate
1.599     albertel 10801: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10802: 
1.338     www      10803:     #
                   10804:     # Importing a rights file here
1.339     albertel 10805:     #
                   10806: 	    unless ($depthcount) {
1.599     albertel 10807: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10808: 		my $dir=$filename;
                   10809: 		$dir=~s|[^/]*$||;
                   10810: 		$location=&filelocation($dir,$location);
1.736     albertel 10811: 		my $rights_metadata =
                   10812: 		    &metadata($uri,'keys',$location,'_rights',
                   10813: 			      $depthcount+1);
                   10814: 		foreach my $rights (split(',',$rights_metadata)) {
                   10815: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10816: 		    $metathesekeys{$rights}=1;
1.339     albertel 10817: 		}
                   10818: 	    }
                   10819: 	}
1.737     albertel 10820: 	# uniqifiy package listing
                   10821: 	my %seen;
                   10822: 	my @uniq_packages =
                   10823: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10824: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10825: 
1.1070    www      10826:         if ($importedparts) {
                   10827: # We had imported parts and need to rebuild partorder
                   10828:            $metaentry{':partorder'}='';
                   10829:            $metathesekeys{'partorder'}=1;
                   10830:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10831:                if ($origfileimportpartids[$index] eq 'part') {
                   10832: # original part, part of the problem
                   10833:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10834:                } else {
                   10835: # we have imported parts at this position
                   10836:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10837:                }
                   10838:            }
                   10839:            $metaentry{':partorder'}=~s/^\,//;
                   10840:         }
                   10841: 
1.737     albertel 10842: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10843: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  10844: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 10845: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10846: # this is the end of "was not already recently cached
1.71      www      10847:     }
1.599     albertel 10848:     return $metaentry{':'.$what};
1.261     albertel 10849: }
                   10850: 
1.488     albertel 10851: sub metadata_create_package_def {
1.483     albertel 10852:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10853:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10854:     if ($subp eq 'default') { next; }
                   10855:     
1.599     albertel 10856:     if (defined($metaentry{':packages'})) {
                   10857: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10858:     } else {
1.599     albertel 10859: 	$metaentry{':packages'}=$package;
1.483     albertel 10860:     }
                   10861:     my $value=$packagetab{$key};
                   10862:     my $unikey;
                   10863:     $unikey='parameter_0_'.$name;
1.599     albertel 10864:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10865:     $$metathesekeys{$unikey}=1;
1.599     albertel 10866:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10867: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10868:     }
1.599     albertel 10869:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10870: 	$metaentry{':'.$unikey}=
                   10871: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10872:     }
                   10873: }
                   10874: 
1.261     albertel 10875: sub metadata_generate_part0 {
                   10876:     my ($metadata,$metacache,$uri) = @_;
                   10877:     my %allnames;
1.737     albertel 10878:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10879: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10880: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10881: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10882: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10883: 	    $allnames{$name}=$part;
                   10884: 	  }
                   10885: 	}
                   10886:     }
                   10887:     foreach my $name (keys(%allnames)) {
                   10888:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10889:       my $key=":parameter_0_$name";
1.261     albertel 10890:       $$metacache{"$key.part"}='0';
                   10891:       $$metacache{"$key.name"}=$name;
1.428     albertel 10892:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10893: 					   $allnames{$name}.'_'.$name.
                   10894: 					   '.type'};
1.428     albertel 10895:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10896: 			     '.display'};
1.644     www      10897:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10898:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10899:       $$metacache{"$key.display"}=$olddis;
                   10900:     }
1.71      www      10901: }
                   10902: 
1.764     albertel 10903: # ------------------------------------------------------ Devalidate title cache
                   10904: 
                   10905: sub devalidate_title_cache {
                   10906:     my ($url)=@_;
                   10907:     if (!$env{'request.course.id'}) { return; }
                   10908:     my $symb=&symbread($url);
                   10909:     if (!$symb) { return; }
                   10910:     my $key=$env{'request.course.id'}."\0".$symb;
                   10911:     &devalidate_cache_new('title',$key);
                   10912: }
                   10913: 
1.1014    droeschl 10914: # ------------------------------------------------- Get the title of a course
                   10915: 
                   10916: sub current_course_title {
                   10917:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10918: }
1.301     www      10919: # ------------------------------------------------- Get the title of a resource
                   10920: 
                   10921: sub gettitle {
                   10922:     my $urlsymb=shift;
                   10923:     my $symb=&symbread($urlsymb);
1.534     albertel 10924:     if ($symb) {
1.620     albertel 10925: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 10926: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 10927: 	if (defined($cached)) { 
                   10928: 	    return $result;
                   10929: 	}
1.534     albertel 10930: 	my ($map,$resid,$url)=&decode_symb($symb);
                   10931: 	my $title='';
1.907     albertel 10932: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   10933: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   10934: 	} else {
                   10935: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10936: 		    &GDBM_READER(),0640)) {
                   10937: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   10938: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   10939: 		untie(%bighash);
                   10940: 	    }
1.534     albertel 10941: 	}
                   10942: 	$title=~s/\&colon\;/\:/gs;
                   10943: 	if ($title) {
1.1159    www      10944: # Remember both $symb and $title for dynamic metadata
                   10945:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      10946:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      10947: # Cache this title and then return it
1.599     albertel 10948: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 10949: 	}
                   10950: 	$urlsymb=$url;
                   10951:     }
                   10952:     my $title=&metadata($urlsymb,'title');
                   10953:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   10954:     return $title;
1.301     www      10955: }
1.613     albertel 10956: 
1.614     albertel 10957: sub get_slot {
                   10958:     my ($which,$cnum,$cdom)=@_;
                   10959:     if (!$cnum || !$cdom) {
1.790     albertel 10960: 	(undef,my $courseid)=&whichuser();
1.620     albertel 10961: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   10962: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 10963:     }
1.703     albertel 10964:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   10965:     my %slotinfo;
                   10966:     if (exists($remembered{$key})) {
                   10967: 	$slotinfo{$which} = $remembered{$key};
                   10968:     } else {
                   10969: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   10970: 	&Apache::lonhomework::showhash(%slotinfo);
                   10971: 	my ($tmp)=keys(%slotinfo);
                   10972: 	if ($tmp=~/^error:/) { return (); }
                   10973: 	$remembered{$key} = $slotinfo{$which};
                   10974:     }
1.616     albertel 10975:     if (ref($slotinfo{$which}) eq 'HASH') {
                   10976: 	return %{$slotinfo{$which}};
                   10977:     }
                   10978:     return $slotinfo{$which};
1.614     albertel 10979: }
1.1150    raeburn  10980: 
                   10981: sub get_reservable_slots {
                   10982:     my ($cnum,$cdom,$uname,$udom) = @_;
                   10983:     my $now = time;
                   10984:     my $reservable_info;
                   10985:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   10986:     if (exists($remembered{$key})) {
                   10987:         $reservable_info = $remembered{$key};
                   10988:     } else {
                   10989:         my %resv;
                   10990:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   10991:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   10992:         $reservable_info = \%resv;
                   10993:         $remembered{$key} = $reservable_info;
                   10994:     }
                   10995:     return $reservable_info;
                   10996: }
                   10997: 
                   10998: sub get_course_slots {
                   10999:     my ($cnum,$cdom) = @_;
                   11000:     my $hashid=$cnum.':'.$cdom;
                   11001:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11002:     if (defined($cached)) {
                   11003:         if (ref($result) eq 'HASH') {
                   11004:             return %{$result};
                   11005:         }
                   11006:     } else {
                   11007:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11008:         my ($tmp) = keys(%slots);
                   11009:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  11010:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11011:             return %slots;
                   11012:         }
                   11013:     }
                   11014:     return;
                   11015: }
                   11016: 
                   11017: sub devalidate_slots_cache {
                   11018:     my ($cnum,$cdom)=@_;
                   11019:     my $hashid=$cnum.':'.$cdom;
                   11020:     &devalidate_cache_new('allslots',$hashid);
                   11021: }
                   11022: 
1.1172.2.8  raeburn  11023: sub get_coursechange {
                   11024:     my ($cdom,$cnum) = @_;
                   11025:     if ($cdom eq '' || $cnum eq '') {
                   11026:         return unless ($env{'request.course.id'});
                   11027:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11028:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11029:     }
                   11030:     my $hashid=$cdom.'_'.$cnum;
                   11031:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11032:     if ((defined($cached)) && ($change ne '')) {
                   11033:         return $change;
                   11034:     } else {
                   11035:         my %crshash;
                   11036:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11037:         if ($crshash{'internal.contentchange'} eq '') {
                   11038:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11039:             if ($change eq '') {
                   11040:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11041:                 $change = $crshash{'internal.created'};
                   11042:             }
                   11043:         } else {
                   11044:             $change = $crshash{'internal.contentchange'};
                   11045:         }
                   11046:         my $cachetime = 600;
                   11047:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11048:     }
                   11049:     return $change;
                   11050: }
                   11051: 
                   11052: sub devalidate_coursechange_cache {
                   11053:     my ($cnum,$cdom)=@_;
                   11054:     my $hashid=$cnum.':'.$cdom;
                   11055:     &devalidate_cache_new('crschange',$hashid);
                   11056: }
                   11057: 
1.31      www      11058: # ------------------------------------------------- Update symbolic store links
                   11059: 
                   11060: sub symblist {
                   11061:     my ($mapname,%newhash)=@_;
1.438     www      11062:     $mapname=&deversion(&declutter($mapname));
1.31      www      11063:     my %hash;
1.620     albertel 11064:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11065:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11066:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11067: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11068: 		next if ($url eq 'last_known'
                   11069: 			 && $env{'form.no_update_last_known'});
                   11070: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11071: 						    $newhash{$url}->[1],
                   11072: 						    $newhash{$url}->[0]);
1.191     harris41 11073:             }
1.31      www      11074:             if (untie(%hash)) {
                   11075: 		return 'ok';
                   11076:             }
                   11077:         }
                   11078:     }
                   11079:     return 'error';
1.212     www      11080: }
                   11081: 
                   11082: # --------------------------------------------------------------- Verify a symb
                   11083: 
                   11084: sub symbverify {
1.1172.2.11  raeburn  11085:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11086:     my $thisfn=$thisurl;
1.439     www      11087:     $thisfn=&declutter($thisfn);
1.215     www      11088: # direct jump to resource in page or to a sequence - will construct own symbs
                   11089:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11090: # check URL part
1.409     www      11091:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11092: 
1.431     www      11093:     unless ($url eq $thisfn) { return 0; }
1.213     www      11094: 
1.216     www      11095:     $symb=&symbclean($symb);
1.510     www      11096:     $thisurl=&deversion($thisurl);
1.439     www      11097:     $thisfn=&deversion($thisfn);
1.213     www      11098: 
                   11099:     my %bighash;
                   11100:     my $okay=0;
1.431     www      11101: 
1.620     albertel 11102:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11103:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  11104:         my $noclutter;
1.1032    raeburn  11105:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11106:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  11107:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11108:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11109:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11110:                 $noclutter = 1;
                   11111:             }
                   11112:         }
                   11113:         my $ids;
                   11114:         if ($noclutter) {
                   11115:             $ids=$bighash{'ids_'.$thisurl};
                   11116:         } else {
                   11117:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11118:         }
1.1102    raeburn  11119:         unless ($ids) {
1.1172.2.13  raeburn  11120:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  11121:             $ids=$bighash{$idkey};
1.216     www      11122:         }
                   11123:         if ($ids) {
                   11124: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  11125:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   11126:                 $symb =~ s/\?.+$//;
                   11127:             }
1.800     albertel 11128: 	    foreach my $id (split(/\,/,$ids)) {
                   11129: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11130:                if (
                   11131:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  11132:    eq $symb) {
1.1172.2.11  raeburn  11133:                    if (ref($encstate)) {
                   11134:                        $$encstate = $bighash{'encrypted_'.$id};
                   11135:                    }
1.1172.2.13  raeburn  11136:                    if (($env{'request.role.adv'}) ||
                   11137:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  11138:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  11139:                        $okay=1;
                   11140:                        last;
                   11141:                    }
                   11142:                }
                   11143:            }
1.216     www      11144:         }
1.213     www      11145: 	untie(%bighash);
                   11146:     }
                   11147:     return $okay;
1.31      www      11148: }
                   11149: 
1.210     www      11150: # --------------------------------------------------------------- Clean-up symb
                   11151: 
                   11152: sub symbclean {
                   11153:     my $symb=shift;
1.568     albertel 11154:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11155: # remove version from map
                   11156:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11157: 
1.210     www      11158: # remove version from URL
                   11159:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11160: 
1.507     www      11161: # remove wrapper
                   11162: 
1.510     www      11163:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11164:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11165:     return $symb;
1.409     www      11166: }
                   11167: 
                   11168: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11169: 
                   11170: sub encode_symb {
                   11171:     my ($map,$resid,$url)=@_;
                   11172:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11173: }
1.409     www      11174: 
                   11175: sub decode_symb {
1.568     albertel 11176:     my $symb=shift;
                   11177:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11178:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11179:     return (&fixversion($map),$resid,&fixversion($url));
                   11180: }
                   11181: 
                   11182: sub fixversion {
                   11183:     my $fn=shift;
1.609     banghart 11184:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11185:     my %bighash;
                   11186:     my $uri=&clutter($fn);
1.620     albertel 11187:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11188: # is this cached?
1.599     albertel 11189:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11190:     if (defined($cached)) { return $result; }
                   11191: # unfortunately not cached, or expired
1.620     albertel 11192:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11193: 	    &GDBM_READER(),0640)) {
                   11194:  	if ($bighash{'version_'.$uri}) {
                   11195:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11196:  	    unless (($version eq 'mostrecent') || 
                   11197: 		    ($version==&getversion($uri))) {
1.440     www      11198:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11199:  	    }
                   11200:  	}
                   11201:  	untie %bighash;
1.413     www      11202:     }
1.599     albertel 11203:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11204: }
                   11205: 
                   11206: sub deversion {
                   11207:     my $url=shift;
                   11208:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11209:     return $url;
1.210     www      11210: }
                   11211: 
1.31      www      11212: # ------------------------------------------------------ Return symb list entry
                   11213: 
                   11214: sub symbread {
1.1172.2.66  raeburn  11215:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  11216:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  11217:     if (defined($env{$cache_str})) {
                   11218:         if ($ignorecachednull) {
                   11219:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11220:         } else {
                   11221:             return $env{$cache_str};
                   11222:         }
                   11223:     }
1.242     www      11224: # no filename provided? try from environment
1.1172.2.54  raeburn  11225:     unless ($thisfn) {
1.620     albertel 11226:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  11227:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   11228:         }
                   11229:         $thisfn=$env{'request.filename'};
1.44      www      11230:     }
1.569     albertel 11231:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11232: # is that filename actually a symb? Verify, clean, and return
                   11233:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11234: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11235: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11236: 	}
1.242     www      11237:     }
1.44      www      11238:     $thisfn=declutter($thisfn);
1.31      www      11239:     my %hash;
1.37      www      11240:     my %bighash;
                   11241:     my $syval='';
1.620     albertel 11242:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11243:         my $targetfn = $thisfn;
1.609     banghart 11244:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11245:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11246:         }
1.687     albertel 11247: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11248: 	    $targetfn=$1;
                   11249: 	}
1.620     albertel 11250:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11251:                       &GDBM_READER(),0640)) {
1.481     raeburn  11252: 	    $syval=$hash{$targetfn};
1.37      www      11253:             untie(%hash);
                   11254:         }
                   11255: # ---------------------------------------------------------- There was an entry
                   11256:         if ($syval) {
1.601     albertel 11257: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11258: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11259: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11260: 		    #return $env{$cache_str}='';
1.601     albertel 11261: 		#}    
                   11262: 		#$syval.=$1;
                   11263: 	    #}
1.37      www      11264:         } else {
                   11265: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11266:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11267:                             &GDBM_READER(),0640)) {
1.37      www      11268: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11269:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11270:               unless ($ids) { 
                   11271:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11272:               }
                   11273:               unless ($ids) {
                   11274: # alias?
                   11275: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11276:               }
1.37      www      11277:               if ($ids) {
                   11278: # ------------------------------------------------------------------- Has ID(s)
                   11279:                  my @possibilities=split(/\,/,$ids);
1.39      www      11280:                  if ($#possibilities==0) {
                   11281: # ----------------------------------------------- There is only one possibility
1.37      www      11282: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11283: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11284: 						    $resid,$thisfn);
1.1172.2.66  raeburn  11285:                      if (ref($possibles) eq 'HASH') {
                   11286:                          $possibles->{$syval} = 1;
                   11287:                      }
                   11288:                      if ($checkforblock) {
                   11289:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11290:                          if (@blockers) {
                   11291:                              $syval = '';
                   11292:                              return;
                   11293:                          }
                   11294:                      }
                   11295:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      11296: # ------------------------------------------ There is more than one possibility
                   11297:                      my $realpossible=0;
1.800     albertel 11298:                      foreach my $id (@possibilities) {
                   11299: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  11300:                          my $canaccess;
                   11301:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11302:                              $canaccess = 1;
                   11303:                          } else {
                   11304:                              $canaccess = &allowed('bre',$file);
                   11305:                          }
                   11306:                          if ($canaccess) {
                   11307:          		     my ($mapid,$resid)=split(/\./,$id);
                   11308:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11309:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11310:                                                              $resid,$thisfn);
                   11311:                                  if (ref($possibles) eq 'HASH') {
                   11312:                                      $possibles->{$syval} = 1;
                   11313:                                  }
                   11314:                                  if ($checkforblock) {
                   11315:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11316:                                      unless (@blockers > 0) {
                   11317:                                          $syval = $poss_syval;
                   11318:                                          $realpossible++;
                   11319:                                      }
                   11320:                                  } else {
                   11321:                                      $syval = $poss_syval;
                   11322:                                      $realpossible++;
                   11323:                                  }
                   11324:                              }
1.39      www      11325: 			 }
1.191     harris41 11326:                      }
1.39      www      11327: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11328:                  } else {
                   11329:                      $syval='';
1.37      www      11330:                  }
                   11331: 	      }
1.1172.2.66  raeburn  11332:               untie(%bighash);
1.481     raeburn  11333:            }
1.31      www      11334:         }
1.62      www      11335:         if ($syval) {
1.620     albertel 11336: 	    return $env{$cache_str}=$syval;
1.62      www      11337:         }
1.31      www      11338:     }
1.949     raeburn  11339:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11340:     return $env{$cache_str}='';
1.31      www      11341: }
                   11342: 
                   11343: # ---------------------------------------------------------- Return random seed
                   11344: 
1.32      www      11345: sub numval {
                   11346:     my $txt=shift;
                   11347:     $txt=~tr/A-J/0-9/;
                   11348:     $txt=~tr/a-j/0-9/;
                   11349:     $txt=~tr/K-T/0-9/;
                   11350:     $txt=~tr/k-t/0-9/;
                   11351:     $txt=~tr/U-Z/0-5/;
                   11352:     $txt=~tr/u-z/0-5/;
                   11353:     $txt=~s/\D//g;
1.564     albertel 11354:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11355:     return int($txt);
1.368     albertel 11356: }
                   11357: 
1.484     albertel 11358: sub numval2 {
                   11359:     my $txt=shift;
                   11360:     $txt=~tr/A-J/0-9/;
                   11361:     $txt=~tr/a-j/0-9/;
                   11362:     $txt=~tr/K-T/0-9/;
                   11363:     $txt=~tr/k-t/0-9/;
                   11364:     $txt=~tr/U-Z/0-5/;
                   11365:     $txt=~tr/u-z/0-5/;
                   11366:     $txt=~s/\D//g;
                   11367:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11368:     my $total;
                   11369:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11370:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11371:     return int($total);
                   11372: }
                   11373: 
1.575     albertel 11374: sub numval3 {
                   11375:     use integer;
                   11376:     my $txt=shift;
                   11377:     $txt=~tr/A-J/0-9/;
                   11378:     $txt=~tr/a-j/0-9/;
                   11379:     $txt=~tr/K-T/0-9/;
                   11380:     $txt=~tr/k-t/0-9/;
                   11381:     $txt=~tr/U-Z/0-5/;
                   11382:     $txt=~tr/u-z/0-5/;
                   11383:     $txt=~s/\D//g;
                   11384:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11385:     my $total;
                   11386:     foreach my $val (@txts) { $total+=$val; }
                   11387:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11388:     return $total;
                   11389: }
                   11390: 
1.675     albertel 11391: sub digest {
                   11392:     my ($data)=@_;
                   11393:     my $digest=&Digest::MD5::md5($data);
                   11394:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11395:     my ($e,$f);
                   11396:     {
                   11397:         use integer;
                   11398:         $e=($a+$b);
                   11399:         $f=($c+$d);
                   11400:         if ($_64bit) {
                   11401:             $e=(($e<<32)>>32);
                   11402:             $f=(($f<<32)>>32);
                   11403:         }
                   11404:     }
                   11405:     if (wantarray) {
                   11406: 	return ($e,$f);
                   11407:     } else {
                   11408: 	my $g;
                   11409: 	{
                   11410: 	    use integer;
                   11411: 	    $g=($e+$f);
                   11412: 	    if ($_64bit) {
                   11413: 		$g=(($g<<32)>>32);
                   11414: 	    }
                   11415: 	}
                   11416: 	return $g;
                   11417:     }
                   11418: }
                   11419: 
1.368     albertel 11420: sub latest_rnd_algorithm_id {
1.675     albertel 11421:     return '64bit5';
1.366     albertel 11422: }
1.32      www      11423: 
1.503     albertel 11424: sub get_rand_alg {
                   11425:     my ($courseid)=@_;
1.790     albertel 11426:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11427:     if ($courseid) {
1.620     albertel 11428: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11429:     }
                   11430:     return &latest_rnd_algorithm_id();
                   11431: }
                   11432: 
1.562     albertel 11433: sub validCODE {
                   11434:     my ($CODE)=@_;
                   11435:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11436:     return 0;
                   11437: }
                   11438: 
1.491     albertel 11439: sub getCODE {
1.620     albertel 11440:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11441:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11442: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11443: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11444: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11445:     }
                   11446:     return undef;
                   11447: }
1.1133    foxr     11448: #
                   11449: #  Determines the random seed for a specific context:
                   11450: #
                   11451: # parameters:
                   11452: #   symb      - in course context the symb for the seed.
                   11453: #   course_id - The course id of the form domain_coursenum.
                   11454: #   domain    - Domain for the user.
                   11455: #   course    - Course for the user.
                   11456: #   cenv      - environment of the course.
                   11457: #
                   11458: # NOTE:
                   11459: #   All parameters are picked out of the environment if missing
                   11460: #   or not defined.
                   11461: #   If a symb cannot be determined the current time is used instead.
                   11462: #
                   11463: #  For a given well defined symb, courside, domain, username,
                   11464: #  and course environment, the seed is reproducible.
                   11465: #
1.31      www      11466: sub rndseed {
1.1133    foxr     11467:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11468:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11469:     if (!defined($symb)) {
1.366     albertel 11470: 	unless ($symb=$wsymb) { return time; }
                   11471:     }
1.1146    foxr     11472:     if (!defined $courseid) { 
                   11473: 	$courseid=$wcourseid; 
                   11474:     }
                   11475:     if (!defined $domain) { $domain=$wdomain; }
                   11476:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11477: 
                   11478:     my $which;
                   11479:     if (defined($cenv->{'rndseed'})) {
                   11480: 	$which = $cenv->{'rndseed'};
                   11481:     } else {
                   11482: 	$which =&get_rand_alg($courseid);
                   11483:     }
1.491     albertel 11484:     if (defined(&getCODE())) {
1.675     albertel 11485: 	if ($which eq '64bit5') {
                   11486: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11487: 	} elsif ($which eq '64bit4') {
1.575     albertel 11488: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11489: 	} else {
                   11490: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11491: 	}
1.675     albertel 11492:     } elsif ($which eq '64bit5') {
                   11493: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11494:     } elsif ($which eq '64bit4') {
                   11495: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11496:     } elsif ($which eq '64bit3') {
                   11497: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11498:     } elsif ($which eq '64bit2') {
                   11499: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11500:     } elsif ($which eq '64bit') {
                   11501: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11502:     }
                   11503:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11504: }
                   11505: 
                   11506: sub rndseed_32bit {
                   11507:     my ($symb,$courseid,$domain,$username)=@_;
                   11508:     {
                   11509: 	use integer;
                   11510: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11511: 	my $symbseed=numval($symb) << 22;
                   11512: 	my $namechck=unpack("%32C*",$username) << 17;
                   11513: 	my $nameseed=numval($username) << 12;
                   11514: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11515: 	my $courseseed=unpack("%32C*",$courseid);
                   11516: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11517: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11518: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11519: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11520: 	return $num;
                   11521:     }
                   11522: }
                   11523: 
                   11524: sub rndseed_64bit {
                   11525:     my ($symb,$courseid,$domain,$username)=@_;
                   11526:     {
                   11527: 	use integer;
                   11528: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11529: 	my $symbseed=numval($symb) << 10;
                   11530: 	my $namechck=unpack("%32S*",$username);
                   11531: 	
                   11532: 	my $nameseed=numval($username) << 21;
                   11533: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11534: 	my $courseseed=unpack("%32S*",$courseid);
                   11535: 	
                   11536: 	my $num1=$symbchck+$symbseed+$namechck;
                   11537: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11538: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11539: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11540: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11541: 	return "$num1,$num2";
1.155     albertel 11542:     }
1.366     albertel 11543: }
                   11544: 
1.443     albertel 11545: sub rndseed_64bit2 {
                   11546:     my ($symb,$courseid,$domain,$username)=@_;
                   11547:     {
                   11548: 	use integer;
                   11549: 	# strings need to be an even # of cahracters long, it it is odd the
                   11550:         # last characters gets thrown away
                   11551: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11552: 	my $symbseed=numval($symb) << 10;
                   11553: 	my $namechck=unpack("%32S*",$username.' ');
                   11554: 	
                   11555: 	my $nameseed=numval($username) << 21;
1.501     albertel 11556: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11557: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11558: 	
                   11559: 	my $num1=$symbchck+$symbseed+$namechck;
                   11560: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11561: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11562: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11563: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11564: 	return "$num1,$num2";
                   11565:     }
                   11566: }
                   11567: 
                   11568: sub rndseed_64bit3 {
                   11569:     my ($symb,$courseid,$domain,$username)=@_;
                   11570:     {
                   11571: 	use integer;
                   11572: 	# strings need to be an even # of cahracters long, it it is odd the
                   11573:         # last characters gets thrown away
                   11574: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11575: 	my $symbseed=numval2($symb) << 10;
                   11576: 	my $namechck=unpack("%32S*",$username.' ');
                   11577: 	
                   11578: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11579: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11580: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11581: 	
                   11582: 	my $num1=$symbchck+$symbseed+$namechck;
                   11583: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11584: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11585: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11586: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11587: 	
1.503     albertel 11588: 	return "$num1:$num2";
1.443     albertel 11589:     }
                   11590: }
                   11591: 
1.575     albertel 11592: sub rndseed_64bit4 {
                   11593:     my ($symb,$courseid,$domain,$username)=@_;
                   11594:     {
                   11595: 	use integer;
                   11596: 	# strings need to be an even # of cahracters long, it it is odd the
                   11597:         # last characters gets thrown away
                   11598: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11599: 	my $symbseed=numval3($symb) << 10;
                   11600: 	my $namechck=unpack("%32S*",$username.' ');
                   11601: 	
                   11602: 	my $nameseed=numval3($username) << 21;
                   11603: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11604: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11605: 	
                   11606: 	my $num1=$symbchck+$symbseed+$namechck;
                   11607: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11608: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11609: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11610: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11611: 	
1.575     albertel 11612: 	return "$num1:$num2";
                   11613:     }
                   11614: }
                   11615: 
1.675     albertel 11616: sub rndseed_64bit5 {
                   11617:     my ($symb,$courseid,$domain,$username)=@_;
                   11618:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11619:     return "$num1:$num2";
                   11620: }
                   11621: 
1.366     albertel 11622: sub rndseed_CODE_64bit {
                   11623:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11624:     {
1.366     albertel 11625: 	use integer;
1.443     albertel 11626: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11627: 	my $symbseed=numval2($symb);
1.491     albertel 11628: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11629: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11630: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11631: 	my $num1=$symbseed+$CODEchck;
                   11632: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11633: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11634: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11635: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11636: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11637: 	return "$num1:$num2";
1.366     albertel 11638:     }
                   11639: }
                   11640: 
1.575     albertel 11641: sub rndseed_CODE_64bit4 {
                   11642:     my ($symb,$courseid,$domain,$username)=@_;
                   11643:     {
                   11644: 	use integer;
                   11645: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11646: 	my $symbseed=numval3($symb);
                   11647: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11648: 	my $CODEseed=numval3(&getCODE());
                   11649: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11650: 	my $num1=$symbseed+$CODEchck;
                   11651: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11652: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11653: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11654: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11655: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11656: 	return "$num1:$num2";
                   11657:     }
                   11658: }
                   11659: 
1.675     albertel 11660: sub rndseed_CODE_64bit5 {
                   11661:     my ($symb,$courseid,$domain,$username)=@_;
                   11662:     my $code = &getCODE();
                   11663:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11664:     return "$num1:$num2";
                   11665: }
                   11666: 
1.366     albertel 11667: sub setup_random_from_rndseed {
                   11668:     my ($rndseed)=@_;
1.503     albertel 11669:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  11670: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11671:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11672:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11673:         } else {
                   11674:             &Math::Random::random_set_seed($num1,$num2);
                   11675:         }
1.366     albertel 11676:     } else {
                   11677: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11678:     }
1.36      albertel 11679: }
                   11680: 
1.474     albertel 11681: sub latest_receipt_algorithm_id {
1.835     albertel 11682:     return 'receipt3';
1.474     albertel 11683: }
                   11684: 
1.480     www      11685: sub recunique {
                   11686:     my $fucourseid=shift;
                   11687:     my $unique;
1.835     albertel 11688:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11689: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11690: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11691:     } else {
                   11692: 	$unique=$perlvar{'lonReceipt'};
                   11693:     }
                   11694:     return unpack("%32C*",$unique);
                   11695: }
                   11696: 
                   11697: sub recprefix {
                   11698:     my $fucourseid=shift;
                   11699:     my $prefix;
1.835     albertel 11700:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11701: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11702: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11703:     } else {
                   11704: 	$prefix=$perlvar{'lonHostID'};
                   11705:     }
                   11706:     return unpack("%32C*",$prefix);
                   11707: }
                   11708: 
1.76      www      11709: sub ireceipt {
1.474     albertel 11710:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11711: 
                   11712:     my $return =&recprefix($fucourseid).'-';
                   11713: 
                   11714:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11715: 	$env{'request.state'} eq 'construct') {
                   11716: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11717: 	return $return;
                   11718:     }
                   11719: 
1.76      www      11720:     my $cuname=unpack("%32C*",$funame);
                   11721:     my $cudom=unpack("%32C*",$fudom);
                   11722:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11723:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11724:     my $cunique=&recunique($fucourseid);
1.474     albertel 11725:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11726:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11727: 
1.790     albertel 11728: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11729: 			       
                   11730: 	$return.= ($cunique%$cuname+
                   11731: 		   $cunique%$cudom+
                   11732: 		   $cusymb%$cuname+
                   11733: 		   $cusymb%$cudom+
                   11734: 		   $cucourseid%$cuname+
                   11735: 		   $cucourseid%$cudom+
                   11736: 		   $cpart%$cuname+
                   11737: 		   $cpart%$cudom);
                   11738:     } else {
                   11739: 	$return.= ($cunique%$cuname+
                   11740: 		   $cunique%$cudom+
                   11741: 		   $cusymb%$cuname+
                   11742: 		   $cusymb%$cudom+
                   11743: 		   $cucourseid%$cuname+
                   11744: 		   $cucourseid%$cudom);
                   11745:     }
                   11746:     return $return;
1.76      www      11747: }
                   11748: 
                   11749: sub receipt {
1.474     albertel 11750:     my ($part)=@_;
1.790     albertel 11751:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11752:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11753: }
1.260     ng       11754: 
1.790     albertel 11755: sub whichuser {
                   11756:     my ($passedsymb)=@_;
                   11757:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11758:     if (defined($env{'form.grade_symb'})) {
                   11759: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11760: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11761: 	if (!$allowed &&
                   11762: 	    exists($env{'request.course.sec'}) &&
                   11763: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11764: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11765: 			      '/'.$env{'request.course.sec'});
                   11766: 	}
                   11767: 	if ($allowed) {
                   11768: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11769: 	    $courseid=$tmp_courseid;
                   11770: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11771: 	    ($name)=&get_env_multiple('form.grade_username');
                   11772: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11773: 	}
                   11774:     }
                   11775:     if (!$passedsymb) {
                   11776: 	$symb=&symbread();
                   11777:     } else {
                   11778: 	$symb=$passedsymb;
                   11779:     }
                   11780:     $courseid=$env{'request.course.id'};
                   11781:     $domain=$env{'user.domain'};
                   11782:     $name=$env{'user.name'};
                   11783:     if ($name eq 'public' && $domain eq 'public') {
                   11784: 	if (!defined($env{'form.username'})) {
                   11785: 	    $env{'form.username'}.=time.rand(10000000);
                   11786: 	}
                   11787: 	$name.=$env{'form.username'};
                   11788:     }
                   11789:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11790: 
                   11791: }
                   11792: 
1.36      albertel 11793: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11794: # returns either the contents of the file or 
                   11795: # -1 if the file doesn't exist
1.481     raeburn  11796: #
                   11797: # if the target is a file that was uploaded via DOCS, 
                   11798: # a check will be made to see if a current copy exists on the local server,
                   11799: # if it does this will be served, otherwise a copy will be retrieved from
                   11800: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11801: # the local server.   
1.472     albertel 11802: 
1.36      albertel 11803: sub getfile {
1.538     albertel 11804:     my ($file) = @_;
1.609     banghart 11805:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11806:     &repcopy($file);
                   11807:     return &readfile($file);
                   11808: }
                   11809: 
                   11810: sub repcopy_userfile {
                   11811:     my ($file)=@_;
1.1142    raeburn  11812:     my $londocroot = $perlvar{'lonDocRoot'};
                   11813:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11814:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11815:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11816: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11817:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11818:     if (-e "$file") {
1.828     www      11819: # we already have a local copy, check it out
1.538     albertel 11820: 	my @fileinfo = stat($file);
1.828     www      11821: 	my $rtncode;
                   11822: 	my $info;
1.538     albertel 11823: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11824: 	if ($lwpresp ne 'ok') {
1.828     www      11825: # there is no such file anymore, even though we had a local copy
1.482     albertel 11826: 	    if ($rtncode eq '404') {
1.538     albertel 11827: 		unlink($file);
1.482     albertel 11828: 	    }
                   11829: 	    return -1;
                   11830: 	}
                   11831: 	if ($info < $fileinfo[9]) {
1.828     www      11832: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11833: 	    return 'ok';
1.828     www      11834: 	} else {
                   11835: # the file is outdated, get rid of it
                   11836: 	    unlink($file);
1.482     albertel 11837: 	}
1.828     www      11838:     }
                   11839: # one way or the other, at this point, we don't have the file
                   11840: # construct the correct path for the file
                   11841:     my @parts = ($cdom,$cnum); 
                   11842:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11843: 	push @parts, split(/\//,$1);
                   11844:     }
                   11845:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11846:     foreach my $part (@parts) {
                   11847: 	$path .= '/'.$part;
                   11848: 	if (!-e $path) {
                   11849: 	    mkdir($path,0770);
1.482     albertel 11850: 	}
                   11851:     }
1.828     www      11852: # now the path exists for sure
                   11853: # get a user agent
                   11854:     my $ua=new LWP::UserAgent;
                   11855:     my $transferfile=$file.'.in.transfer';
                   11856: # FIXME: this should flock
                   11857:     if (-e $transferfile) { return 'ok'; }
                   11858:     my $request;
                   11859:     $uri=~s/^\///;
1.980     raeburn  11860:     my $homeserver = &homeserver($cnum,$cdom);
                   11861:     my $protocol = $protocol{$homeserver};
                   11862:     $protocol = 'http' if ($protocol ne 'https');
                   11863:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11864:     my $response=$ua->request($request,$transferfile);
                   11865: # did it work?
                   11866:     if ($response->is_error()) {
                   11867: 	unlink($transferfile);
                   11868: 	&logthis("Userfile repcopy failed for $uri");
                   11869: 	return -1;
                   11870:     }
                   11871: # worked, rename the transfer file
                   11872:     rename($transferfile,$file);
1.607     raeburn  11873:     return 'ok';
1.481     raeburn  11874: }
                   11875: 
1.517     albertel 11876: sub tokenwrapper {
                   11877:     my $uri=shift;
1.980     raeburn  11878:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11879:     $uri=~s|^/||;
1.620     albertel 11880:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11881:     my $token=$1;
1.552     albertel 11882:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11883:     if ($udom && $uname && $file) {
                   11884: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11885:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11886:         my $homeserver = &homeserver($uname,$udom);
                   11887:         my $protocol = $protocol{$homeserver};
                   11888:         $protocol = 'http' if ($protocol ne 'https');
                   11889:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11890:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11891:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11892:     } else {
                   11893:         return '/adm/notfound.html';
                   11894:     }
                   11895: }
                   11896: 
1.828     www      11897: # call with reqtype HEAD: get last modification time
                   11898: # call with reqtype GET: get the file contents
                   11899: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11900: #
1.481     raeburn  11901: sub getuploaded {
                   11902:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11903:     $uri=~s/^\///;
1.980     raeburn  11904:     my $homeserver = &homeserver($cnum,$cdom);
                   11905:     my $protocol = $protocol{$homeserver};
                   11906:     $protocol = 'http' if ($protocol ne 'https');
                   11907:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11908:     my $ua=new LWP::UserAgent;
                   11909:     my $request=new HTTP::Request($reqtype,$uri);
                   11910:     my $response=$ua->request($request);
                   11911:     $$rtncode = $response->code;
1.482     albertel 11912:     if (! $response->is_success()) {
                   11913: 	return 'failed';
                   11914:     }      
                   11915:     if ($reqtype eq 'HEAD') {
1.486     www      11916: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11917:     } elsif ($reqtype eq 'GET') {
                   11918: 	$$info = $response->content;
1.472     albertel 11919:     }
1.482     albertel 11920:     return 'ok';
1.36      albertel 11921: }
                   11922: 
1.481     raeburn  11923: sub readfile {
                   11924:     my $file = shift;
                   11925:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   11926:     my $fh;
                   11927:     open($fh,"<$file");
                   11928:     my $a='';
1.800     albertel 11929:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  11930:     return $a;
                   11931: }
                   11932: 
1.36      albertel 11933: sub filelocation {
1.590     banghart 11934:     my ($dir,$file) = @_;
                   11935:     my $location;
                   11936:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 11937: 
                   11938:     if ($file =~ m-^/adm/-) {
                   11939: 	$file=~s-^/adm/wrapper/-/-;
                   11940: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   11941:     }
1.882     albertel 11942: 
1.1139    www      11943:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  11944:         $location = $file;
1.609     banghart 11945:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 11946:         my ($udom,$uname,$filename)=
1.811     albertel 11947:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 11948:         my $home=&homeserver($uname,$udom);
                   11949:         my $is_me=0;
                   11950:         my @ids=&current_machine_ids();
                   11951:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   11952:         if ($is_me) {
1.1117    foxr     11953:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 11954:         } else {
                   11955:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   11956:   	      $udom.'/'.$uname.'/'.$filename;
                   11957:         }
1.882     albertel 11958:     } elsif ($file =~ m-^/adm/-) {
                   11959: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 11960:     } else {
                   11961:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      11962:         $file=~s:^/(res|priv)/:/:;
                   11963:         my $space=$1;
1.590     banghart 11964:         if ( !( $file =~ m:^/:) ) {
                   11965:             $location = $dir. '/'.$file;
                   11966:         } else {
1.1142    raeburn  11967:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 11968:         }
1.59      albertel 11969:     }
1.590     banghart 11970:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 11971:     while ($location=~m{/\.\./}) {
                   11972: 	if ($location =~ m{/[^/]+/\.\./}) {
                   11973: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   11974: 	} else {
                   11975: 	    $location=~ s{/\.\./}{/}g;
                   11976: 	}
                   11977:     } #remove dir/..
1.590     banghart 11978:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   11979:     return $location;
1.46      www      11980: }
1.36      albertel 11981: 
1.46      www      11982: sub hreflocation {
                   11983:     my ($dir,$file)=@_;
1.980     raeburn  11984:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 11985: 	$file=filelocation($dir,$file);
1.700     albertel 11986:     } elsif ($file=~m-^/adm/-) {
                   11987: 	$file=~s-^/adm/wrapper/-/-;
                   11988: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 11989:     }
                   11990:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   11991: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   11992:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  11993: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   11994: 	        {/uploaded/$1/$2/}x;
1.46      www      11995:     }
1.913     albertel 11996:     if ($file=~ m{^/userfiles/}) {
                   11997: 	$file =~ s{^/userfiles/}{/uploaded/};
                   11998:     }
1.462     albertel 11999:     return $file;
1.465     albertel 12000: }
                   12001: 
1.1139    www      12002: 
                   12003: 
                   12004: 
                   12005: 
1.465     albertel 12006: sub current_machine_domains {
1.853     albertel 12007:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12008: }
                   12009: 
                   12010: sub machine_domains {
                   12011:     my ($hostname) = @_;
1.465     albertel 12012:     my @domains;
1.838     albertel 12013:     my %hostname = &all_hostnames();
1.465     albertel 12014:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12015: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12016: 	if ($hostname eq $name) {
1.844     albertel 12017: 	    push(@domains,&host_domain($id));
1.465     albertel 12018: 	}
                   12019:     }
                   12020:     return @domains;
                   12021: }
                   12022: 
                   12023: sub current_machine_ids {
1.853     albertel 12024:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12025: }
                   12026: 
                   12027: sub machine_ids {
                   12028:     my ($hostname) = @_;
                   12029:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12030:     my @ids;
1.888     albertel 12031:     my %name_to_host = &all_names();
1.889     albertel 12032:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12033: 	return @{ $name_to_host{$hostname} };
                   12034:     }
                   12035:     return;
1.31      www      12036: }
                   12037: 
1.824     raeburn  12038: sub additional_machine_domains {
                   12039:     my @domains;
                   12040:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12041:     while( my $line = <$fh>) {
                   12042:         $line =~ s/\s//g;
                   12043:         push(@domains,$line);
                   12044:     }
                   12045:     return @domains;
                   12046: }
                   12047: 
                   12048: sub default_login_domain {
                   12049:     my $domain = $perlvar{'lonDefDomain'};
                   12050:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12051:     foreach my $posdom (&current_machine_domains(),
                   12052:                         &additional_machine_domains()) {
                   12053:         if (lc($posdom) eq lc($testdomain)) {
                   12054:             $domain=$posdom;
                   12055:             last;
                   12056:         }
                   12057:     }
                   12058:     return $domain;
                   12059: }
                   12060: 
1.31      www      12061: # ------------------------------------------------------------- Declutters URLs
                   12062: 
                   12063: sub declutter {
                   12064:     my $thisfn=shift;
1.569     albertel 12065:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  12066:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12067:         $thisfn=~s{^/home/httpd/html}{};
                   12068:     }
1.31      www      12069:     $thisfn=~s/^\///;
1.697     albertel 12070:     $thisfn=~s|^adm/wrapper/||;
                   12071:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12072:     $thisfn=~s/^res\///;
1.1172    bisitz   12073:     $thisfn=~s/^priv\///;
1.1032    raeburn  12074:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12075:         $thisfn=~s/\?.+$//;
                   12076:     }
1.268     www      12077:     return $thisfn;
                   12078: }
                   12079: 
                   12080: # ------------------------------------------------------------- Clutter up URLs
                   12081: 
                   12082: sub clutter {
                   12083:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12084:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12085: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12086:        $thisfn='/res'.$thisfn; 
                   12087:     }
1.1031    raeburn  12088:     if ($thisfn !~m|^/adm|) {
                   12089: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12090: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12091: 	} else {
                   12092: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12093: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12094: 	    if ($embstyle eq 'ssi'
                   12095: 		|| ($embstyle eq 'hdn')
                   12096: 		|| ($embstyle eq 'rat')
                   12097: 		|| ($embstyle eq 'prv')
                   12098: 		|| ($embstyle eq 'ign')) {
                   12099: 		#do nothing with these
                   12100: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12101: 		|| ($embstyle eq 'emb')
                   12102: 		|| ($embstyle eq 'wrp')) {
                   12103: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12104: 	    } elsif ($embstyle eq 'unk'
                   12105: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12106: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12107: 	    } else {
1.718     www      12108: #		&logthis("Got a blank emb style");
1.695     albertel 12109: 	    }
1.694     albertel 12110: 	}
                   12111:     }
1.31      www      12112:     return $thisfn;
1.12      www      12113: }
                   12114: 
1.787     albertel 12115: sub clutter_with_no_wrapper {
                   12116:     my $uri = &clutter(shift);
                   12117:     if ($uri =~ m-^/adm/-) {
                   12118: 	$uri =~ s-^/adm/wrapper/-/-;
                   12119: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12120:     }
                   12121:     return $uri;
                   12122: }
                   12123: 
1.557     albertel 12124: sub freeze_escape {
                   12125:     my ($value)=@_;
                   12126:     if (ref($value)) {
                   12127: 	$value=&nfreeze($value);
                   12128: 	return '__FROZEN__'.&escape($value);
                   12129:     }
                   12130:     return &escape($value);
                   12131: }
                   12132: 
1.11      www      12133: 
1.557     albertel 12134: sub thaw_unescape {
                   12135:     my ($value)=@_;
                   12136:     if ($value =~ /^__FROZEN__/) {
                   12137: 	substr($value,0,10,undef);
                   12138: 	$value=&unescape($value);
                   12139: 	return &thaw($value);
                   12140:     }
                   12141:     return &unescape($value);
                   12142: }
                   12143: 
1.436     albertel 12144: sub correct_line_ends {
                   12145:     my ($result)=@_;
                   12146:     $$result =~s/\r\n/\n/mg;
                   12147:     $$result =~s/\r/\n/mg;
1.415     albertel 12148: }
1.1       albertel 12149: # ================================================================ Main Program
                   12150: 
1.184     www      12151: sub goodbye {
1.204     albertel 12152:    &logthis("Starting Shut down");
1.443     albertel 12153: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12154:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12155: #converted
1.599     albertel 12156: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12157:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12158: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12159: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12160: #1.1 only
1.870     albertel 12161: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12162: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12163: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12164: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12165:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12166:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12167:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12168:    &flushcourselogs();
                   12169:    &logthis("Shutting down");
                   12170: }
                   12171: 
1.852     albertel 12172: sub get_dns {
1.1172.2.17  raeburn  12173:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12174:     if (!$ignore_cache) {
                   12175: 	my ($content,$cached)=
                   12176: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12177: 	if ($cached) {
1.1172.2.17  raeburn  12178: 	    &$func($content,$hashref);
1.869     albertel 12179: 	    return;
                   12180: 	}
                   12181:     }
                   12182: 
                   12183:     my %alldns;
1.852     albertel 12184:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12185:     foreach my $dns (<$config>) {
                   12186: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12187:         my $line = $1;
                   12188:         my ($host,$protocol) = split(/:/,$line);
                   12189:         if ($protocol ne 'https') {
                   12190:             $protocol = 'http';
                   12191:         }
                   12192: 	$alldns{$host} = $protocol;
1.869     albertel 12193:     }
                   12194:     while (%alldns) {
1.1172.2.52  raeburn  12195: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12196: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12197:         $ua->timeout(30);
1.979     raeburn  12198: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12199: 	my $response=$ua->request($request);
1.979     raeburn  12200:         delete($alldns{$dns});
1.852     albertel 12201: 	next if ($response->is_error());
                   12202: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  12203:         unless ($nocache) {
1.1172.2.23  raeburn  12204: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  12205:         }
                   12206: 	&$func(\@content,$hashref);
1.869     albertel 12207: 	return;
1.852     albertel 12208:     }
                   12209:     close($config);
1.871     albertel 12210:     my $which = (split('/',$url))[3];
                   12211:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12212:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12213:     my @content = <$config>;
1.1172.2.17  raeburn  12214:     &$func(\@content,$hashref);
                   12215:     return;
                   12216: }
                   12217: 
                   12218: # ------------------------------------------------------Get DNS checksums file
                   12219: sub parse_dns_checksums_tab {
                   12220:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  12221:     my $lonhost = $perlvar{'lonHostID'};
                   12222:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  12223:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  12224:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12225:     my $webconfdir = '/etc/httpd/conf';
                   12226:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12227:         $webconfdir = '/etc/apache2';
                   12228:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12229:         if ($1 >= 10) {
                   12230:             $webconfdir = '/etc/apache2';
                   12231:         }
                   12232:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12233:         if ($1 >= 10.0) {
                   12234:             $webconfdir = '/etc/apache2';
                   12235:         }
                   12236:     }
1.1172.2.17  raeburn  12237:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12238:     my (%chksum,%revnum);
                   12239:     if (ref($lines) eq 'ARRAY') {
                   12240:         chomp(@{$lines});
1.1172.2.34  raeburn  12241:         my $version = shift(@{$lines});
                   12242:         if ($version eq $release) {
1.1172.2.17  raeburn  12243:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  12244:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  12245:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12246:                     if ($webconfdir eq '/etc/apache2') {
                   12247:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12248:                     }
                   12249:                 }
1.1172.2.34  raeburn  12250:                 $chksum{$file} = $shasum;
                   12251:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  12252:             }
                   12253:             if (ref($hashref) eq 'HASH') {
                   12254:                 %{$hashref} = (
                   12255:                                 sums     => \%chksum,
                   12256:                                 versions => \%revnum,
                   12257:                               );
                   12258:             }
                   12259:         }
                   12260:     }
1.869     albertel 12261:     return;
1.852     albertel 12262: }
1.1172.2.17  raeburn  12263: 
                   12264: sub fetch_dns_checksums {
                   12265:     my %checksums;
1.1172.2.34  raeburn  12266:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  12267:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  12268:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12269:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  12270:              \%checksums);
                   12271:     return \%checksums;
                   12272: }
                   12273: 
1.327     albertel 12274: # ------------------------------------------------------------ Read domain file
                   12275: {
1.852     albertel 12276:     my $loaded;
1.846     albertel 12277:     my %domain;
                   12278: 
1.852     albertel 12279:     sub parse_domain_tab {
                   12280: 	my ($lines) = @_;
                   12281: 	foreach my $line (@$lines) {
                   12282: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12283: 
1.846     albertel 12284: 	    chomp($line);
1.852     albertel 12285: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12286: 	    my %this_domain;
                   12287: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12288: 			       'lang_def', 'city', 'longi', 'lati',
                   12289: 			       'primary') {
                   12290: 		$this_domain{$field} = shift(@elements);
                   12291: 	    }
                   12292: 	    $domain{$name} = \%this_domain;
1.852     albertel 12293: 	}
                   12294:     }
1.864     albertel 12295: 
                   12296:     sub reset_domain_info {
                   12297: 	undef($loaded);
                   12298: 	undef(%domain);
                   12299:     }
                   12300: 
1.852     albertel 12301:     sub load_domain_tab {
1.1172.2.70  raeburn  12302: 	my ($ignore_cache,$nocache) = @_;
                   12303: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12304: 	my $fh;
                   12305: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12306: 	    my @lines = <$fh>;
                   12307: 	    &parse_domain_tab(\@lines);
1.448     albertel 12308: 	}
1.852     albertel 12309: 	close($fh);
                   12310: 	$loaded = 1;
1.327     albertel 12311:     }
1.846     albertel 12312: 
                   12313:     sub domain {
1.852     albertel 12314: 	&load_domain_tab() if (!$loaded);
                   12315: 
1.846     albertel 12316: 	my ($name,$what) = @_;
                   12317: 	return if ( !exists($domain{$name}) );
                   12318: 
                   12319: 	if (!$what) {
                   12320: 	    return $domain{$name}{'description'};
                   12321: 	}
                   12322: 	return $domain{$name}{$what};
                   12323:     }
1.974     raeburn  12324: 
                   12325:     sub domain_info {
                   12326:         &load_domain_tab() if (!$loaded);
                   12327:         return %domain;
                   12328:     }
                   12329: 
1.327     albertel 12330: }
                   12331: 
                   12332: 
1.1       albertel 12333: # ------------------------------------------------------------- Read hosts file
                   12334: {
1.838     albertel 12335:     my %hostname;
1.844     albertel 12336:     my %hostdom;
1.845     albertel 12337:     my %libserv;
1.852     albertel 12338:     my $loaded;
1.888     albertel 12339:     my %name_to_host;
1.1074    raeburn  12340:     my %internetdom;
1.1107    raeburn  12341:     my %LC_dns_serv;
1.852     albertel 12342: 
                   12343:     sub parse_hosts_tab {
                   12344: 	my ($file) = @_;
                   12345: 	foreach my $configline (@$file) {
                   12346: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12347:             chomp($configline);
                   12348: 	    if ($configline =~ /^\^/) {
                   12349:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12350:                     $LC_dns_serv{$1} = 1;
                   12351:                 }
                   12352:                 next;
                   12353:             }
1.1074    raeburn  12354: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12355: 	    $name=~s/\s//g;
                   12356: 	    if ($id && $domain && $role && $name) {
                   12357: 		$hostname{$id}=$name;
1.888     albertel 12358: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12359: 		$hostdom{$id}=$domain;
                   12360: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12361:                 if (defined($protocol)) {
                   12362:                     if ($protocol eq 'https') {
                   12363:                         $protocol{$id} = $protocol;
                   12364:                     } else {
                   12365:                         $protocol{$id} = 'http'; 
                   12366:                     }
1.968     raeburn  12367:                 } else {
1.969     raeburn  12368:                     $protocol{$id} = 'http';
1.968     raeburn  12369:                 }
1.1074    raeburn  12370:                 if (defined($intdom)) {
                   12371:                     $internetdom{$id} = $intdom;
                   12372:                 }
1.852     albertel 12373: 	    }
                   12374: 	}
                   12375:     }
1.864     albertel 12376:     
                   12377:     sub reset_hosts_info {
1.897     albertel 12378: 	&purge_remembered();
1.864     albertel 12379: 	&reset_domain_info();
                   12380: 	&reset_hosts_ip_info();
1.892     albertel 12381: 	undef(%name_to_host);
1.864     albertel 12382: 	undef(%hostname);
                   12383: 	undef(%hostdom);
                   12384: 	undef(%libserv);
                   12385: 	undef($loaded);
                   12386:     }
1.1       albertel 12387: 
1.852     albertel 12388:     sub load_hosts_tab {
1.1172.2.70  raeburn  12389: 	my ($ignore_cache,$nocache) = @_;
                   12390: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 12391: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12392: 	my @config = <$config>;
                   12393: 	&parse_hosts_tab(\@config);
                   12394: 	close($config);
                   12395: 	$loaded=1;
1.1       albertel 12396:     }
1.852     albertel 12397: 
1.838     albertel 12398:     sub hostname {
1.852     albertel 12399: 	&load_hosts_tab() if (!$loaded);
                   12400: 
1.838     albertel 12401: 	my ($lonid) = @_;
                   12402: 	return $hostname{$lonid};
                   12403:     }
1.845     albertel 12404: 
1.838     albertel 12405:     sub all_hostnames {
1.852     albertel 12406: 	&load_hosts_tab() if (!$loaded);
                   12407: 
1.838     albertel 12408: 	return %hostname;
                   12409:     }
1.845     albertel 12410: 
1.888     albertel 12411:     sub all_names {
1.1172.2.70  raeburn  12412:         my ($ignore_cache,$nocache) = @_;
                   12413: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12414: 
                   12415: 	return %name_to_host;
                   12416:     }
                   12417: 
1.974     raeburn  12418:     sub all_host_domain {
                   12419:         &load_hosts_tab() if (!$loaded);
                   12420:         return %hostdom;
                   12421:     }
                   12422: 
1.845     albertel 12423:     sub is_library {
1.852     albertel 12424: 	&load_hosts_tab() if (!$loaded);
                   12425: 
1.845     albertel 12426: 	return exists($libserv{$_[0]});
                   12427:     }
                   12428: 
                   12429:     sub all_library {
1.852     albertel 12430: 	&load_hosts_tab() if (!$loaded);
                   12431: 
1.845     albertel 12432: 	return %libserv;
                   12433:     }
                   12434: 
1.1062    droeschl 12435:     sub unique_library {
                   12436: 	#2x reverse removes all hostnames that appear more than once
                   12437:         my %unique = reverse &all_library();
                   12438:         return reverse %unique;
                   12439:     }
                   12440: 
1.841     albertel 12441:     sub get_servers {
1.852     albertel 12442: 	&load_hosts_tab() if (!$loaded);
                   12443: 
1.841     albertel 12444: 	my ($domain,$type) = @_;
                   12445: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12446: 	                                          : %hostname;
                   12447: 	my %result;
1.842     albertel 12448: 	if (ref($domain) eq 'ARRAY') {
                   12449: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12450: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12451: 		    $result{$host} = $hostname;
                   12452: 		}
                   12453: 	    }
                   12454: 	} else {
                   12455: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12456: 		if ($hostdom{$host} eq $domain) {
                   12457: 		    $result{$host} = $hostname;
                   12458: 		}
1.841     albertel 12459: 	    }
                   12460: 	}
                   12461: 	return %result;
                   12462:     }
1.845     albertel 12463: 
1.1062    droeschl 12464:     sub get_unique_servers {
                   12465:         my %unique = reverse &get_servers(@_);
                   12466: 	return reverse %unique;
                   12467:     }
                   12468: 
1.844     albertel 12469:     sub host_domain {
1.852     albertel 12470: 	&load_hosts_tab() if (!$loaded);
                   12471: 
1.844     albertel 12472: 	my ($lonid) = @_;
                   12473: 	return $hostdom{$lonid};
                   12474:     }
                   12475: 
1.841     albertel 12476:     sub all_domains {
1.852     albertel 12477: 	&load_hosts_tab() if (!$loaded);
                   12478: 
1.841     albertel 12479: 	my %seen;
                   12480: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12481: 	return @uniq;
                   12482:     }
1.1074    raeburn  12483: 
                   12484:     sub internet_dom {
                   12485:         &load_hosts_tab() if (!$loaded);
                   12486: 
                   12487:         my ($lonid) = @_;
                   12488:         return $internetdom{$lonid};
                   12489:     }
1.1107    raeburn  12490: 
                   12491:     sub is_LC_dns {
                   12492:         &load_hosts_tab() if (!$loaded);
                   12493: 
                   12494:         my ($hostname) = @_;
                   12495:         return exists($LC_dns_serv{$hostname});
                   12496:     }
                   12497: 
1.1       albertel 12498: }
                   12499: 
1.847     albertel 12500: { 
                   12501:     my %iphost;
1.856     albertel 12502:     my %name_to_ip;
                   12503:     my %lonid_to_ip;
1.869     albertel 12504: 
1.847     albertel 12505:     sub get_hosts_from_ip {
                   12506: 	my ($ip) = @_;
                   12507: 	my %iphosts = &get_iphost();
                   12508: 	if (ref($iphosts{$ip})) {
                   12509: 	    return @{$iphosts{$ip}};
                   12510: 	}
                   12511: 	return;
1.839     albertel 12512:     }
1.864     albertel 12513:     
                   12514:     sub reset_hosts_ip_info {
                   12515: 	undef(%iphost);
                   12516: 	undef(%name_to_ip);
                   12517: 	undef(%lonid_to_ip);
                   12518:     }
1.856     albertel 12519: 
                   12520:     sub get_host_ip {
                   12521: 	my ($lonid) = @_;
                   12522: 	if (exists($lonid_to_ip{$lonid})) {
                   12523: 	    return $lonid_to_ip{$lonid};
                   12524: 	}
                   12525: 	my $name=&hostname($lonid);
                   12526:    	my $ip = gethostbyname($name);
                   12527: 	return if (!$ip || length($ip) ne 4);
                   12528: 	$ip=inet_ntoa($ip);
                   12529: 	$name_to_ip{$name}   = $ip;
                   12530: 	$lonid_to_ip{$lonid} = $ip;
                   12531: 	return $ip;
                   12532:     }
1.847     albertel 12533:     
                   12534:     sub get_iphost {
1.1172.2.70  raeburn  12535: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 12536: 
1.869     albertel 12537: 	if (!$ignore_cache) {
                   12538: 	    if (%iphost) {
                   12539: 		return %iphost;
                   12540: 	    }
                   12541: 	    my ($ip_info,$cached)=
                   12542: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12543: 	    if ($cached) {
                   12544: 		%iphost      = %{$ip_info->[0]};
                   12545: 		%name_to_ip  = %{$ip_info->[1]};
                   12546: 		%lonid_to_ip = %{$ip_info->[2]};
                   12547: 		return %iphost;
                   12548: 	    }
                   12549: 	}
1.894     albertel 12550: 
                   12551: 	# get yesterday's info for fallback
                   12552: 	my %old_name_to_ip;
                   12553: 	my ($ip_info,$cached)=
                   12554: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12555: 	if ($cached) {
                   12556: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12557: 	}
                   12558: 
1.1172.2.70  raeburn  12559: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 12560: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12561: 	    my $ip;
                   12562: 	    if (!exists($name_to_ip{$name})) {
                   12563: 		$ip = gethostbyname($name);
                   12564: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12565: 		    if (defined($old_name_to_ip{$name})) {
                   12566: 			$ip = $old_name_to_ip{$name};
                   12567: 			&logthis("Can't find $name defaulting to old $ip");
                   12568: 		    } else {
                   12569: 			&logthis("Name $name no IP found");
                   12570: 			next;
                   12571: 		    }
                   12572: 		} else {
                   12573: 		    $ip=inet_ntoa($ip);
1.847     albertel 12574: 		}
                   12575: 		$name_to_ip{$name} = $ip;
                   12576: 	    } else {
                   12577: 		$ip = $name_to_ip{$name};
1.653     albertel 12578: 	    }
1.888     albertel 12579: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12580: 		$lonid_to_ip{$id} = $ip;
                   12581: 	    }
                   12582: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12583: 	}
1.1172.2.70  raeburn  12584:         unless ($nocache) {
                   12585: 	    &do_cache_new('iphost','iphost',
                   12586: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12587: 		          48*60*60);
                   12588:         }
1.869     albertel 12589: 
1.847     albertel 12590: 	return %iphost;
1.598     albertel 12591:     }
                   12592: 
1.992     raeburn  12593:     #
                   12594:     #  Given a DNS returns the loncapa host name for that DNS 
                   12595:     # 
                   12596:     sub host_from_dns {
                   12597:         my ($dns) = @_;
                   12598:         my @hosts;
                   12599:         my $ip;
                   12600: 
1.993     raeburn  12601:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12602:             $ip = $name_to_ip{$dns};
                   12603:         }
                   12604:         if (!$ip) {
                   12605:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12606:             if (length($ip) == 4) { 
                   12607: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12608:             }
                   12609:         }
                   12610:         if ($ip) {
                   12611: 	    @hosts = get_hosts_from_ip($ip);
                   12612: 	    return $hosts[0];
                   12613:         }
                   12614:         return undef;
1.986     foxr     12615:     }
1.992     raeburn  12616: 
1.1074    raeburn  12617:     sub get_internet_names {
                   12618:         my ($lonid) = @_;
                   12619:         return if ($lonid eq '');
                   12620:         my ($idnref,$cached)=
                   12621:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12622:         if ($cached) {
                   12623:             return $idnref;
                   12624:         }
                   12625:         my $ip = &get_host_ip($lonid);
                   12626:         my @hosts = &get_hosts_from_ip($ip);
                   12627:         my %iphost = &get_iphost();
                   12628:         my (@idns,%seen);
                   12629:         foreach my $id (@hosts) {
                   12630:             my $dom = &host_domain($id);
                   12631:             my $prim_id = &domain($dom,'primary');
                   12632:             my $prim_ip = &get_host_ip($prim_id);
                   12633:             next if ($seen{$prim_ip});
                   12634:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12635:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12636:                     my $intdom = &internet_dom($id);
                   12637:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12638:                         push(@idns,$intdom);
                   12639:                     }
                   12640:                 }
                   12641:             }
                   12642:             $seen{$prim_ip} = 1;
                   12643:         }
1.1172.2.23  raeburn  12644:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12645:     }
                   12646: 
1.986     foxr     12647: }
                   12648: 
1.1079    raeburn  12649: sub all_loncaparevs {
1.1172.2.39  raeburn  12650:     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 2.11);
1.1079    raeburn  12651: }
                   12652: 
1.1172.2.27  raeburn  12653: # ------------------------------------------------------- Read loncaparev table
                   12654: {
                   12655:     sub load_loncaparevs {
                   12656:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12657:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12658:                 while (my $configline=<$config>) {
                   12659:                     chomp($configline);
                   12660:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12661:                     $loncaparevs{$hostid}=$loncaparev;
                   12662:                 }
                   12663:                 close($config);
                   12664:             }
                   12665:         }
                   12666:     }
                   12667: }
                   12668: 
                   12669: # ----------------------------------------------------- Read serverhostID table
                   12670: {
                   12671:     sub load_serverhomeIDs {
                   12672:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12673:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12674:                 while (my $configline=<$config>) {
                   12675:                     chomp($configline);
                   12676:                     my ($name,$id)=split(/:/,$configline);
                   12677:                     $serverhomeIDs{$name}=$id;
                   12678:                 }
                   12679:                 close($config);
                   12680:             }
                   12681:         }
                   12682:     }
                   12683: }
                   12684: 
                   12685: 
1.862     albertel 12686: BEGIN {
                   12687: 
                   12688: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12689:     unless ($readit) {
                   12690: {
                   12691:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12692:     %perlvar = (%perlvar,%{$configvars});
                   12693: }
                   12694: 
                   12695: 
1.1       albertel 12696: # ------------------------------------------------------ Read spare server file
                   12697: {
1.448     albertel 12698:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12699: 
                   12700:     while (my $configline=<$config>) {
                   12701:        chomp($configline);
1.284     matthew  12702:        if ($configline) {
1.784     albertel 12703: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12704: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12705: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12706:        }
                   12707:     }
1.448     albertel 12708:     close($config);
1.1       albertel 12709: }
1.11      www      12710: # ------------------------------------------------------------ Read permissions
                   12711: {
1.448     albertel 12712:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12713: 
                   12714:     while (my $configline=<$config>) {
1.448     albertel 12715: 	chomp($configline);
                   12716: 	if ($configline) {
                   12717: 	    my ($role,$perm)=split(/ /,$configline);
                   12718: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12719: 	}
1.11      www      12720:     }
1.448     albertel 12721:     close($config);
1.11      www      12722: }
                   12723: 
                   12724: # -------------------------------------------- Read plain texts for permissions
                   12725: {
1.448     albertel 12726:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12727: 
                   12728:     while (my $configline=<$config>) {
1.448     albertel 12729: 	chomp($configline);
                   12730: 	if ($configline) {
1.742     raeburn  12731: 	    my ($short,@plain)=split(/:/,$configline);
                   12732:             %{$prp{$short}} = ();
                   12733: 	    if (@plain > 0) {
                   12734:                 $prp{$short}{'std'} = $plain[0];
                   12735:                 for (my $i=1; $i<@plain; $i++) {
                   12736:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12737:                 }
                   12738:             }
1.448     albertel 12739: 	}
1.135     www      12740:     }
1.448     albertel 12741:     close($config);
1.135     www      12742: }
                   12743: 
                   12744: # ---------------------------------------------------------- Read package table
                   12745: {
1.448     albertel 12746:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12747: 
                   12748:     while (my $configline=<$config>) {
1.483     albertel 12749: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12750: 	chomp($configline);
                   12751: 	my ($short,$plain)=split(/:/,$configline);
                   12752: 	my ($pack,$name)=split(/\&/,$short);
                   12753: 	if ($plain ne '') {
                   12754: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12755: 	    $packagetab{$short}=$plain; 
                   12756: 	}
1.11      www      12757:     }
1.448     albertel 12758:     close($config);
1.329     matthew  12759: }
                   12760: 
1.1172.2.27  raeburn  12761: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  12762: 
1.1172.2.27  raeburn  12763: &load_loncaparevs();
                   12764: 
                   12765: # ------------------------------------------------------- Read serverhostID table
                   12766: 
                   12767: &load_serverhomeIDs();
1.1074    raeburn  12768: 
1.1172.2.27  raeburn  12769: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12770: {
                   12771:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12772:     if (-e $file) {
                   12773:         my $parser = HTML::LCParser->new($file);
                   12774:         while (my $token = $parser->get_token()) {
                   12775:             if ($token->[0] eq 'S') {
                   12776:                 my $item = $token->[1];
                   12777:                 my $name = $token->[2]{'name'};
                   12778:                 my $value = $token->[2]{'value'};
                   12779:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12780:                     my $release = $parser->get_text();
                   12781:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12782:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12783:                 }
                   12784:             }
                   12785:         }
                   12786:     }
1.1073    raeburn  12787: }
                   12788: 
1.1138    raeburn  12789: # ---------------------------------------------------------- Read managers table
                   12790: {
                   12791:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12792:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12793:             while (my $configline=<$config>) {
                   12794:                 chomp($configline);
                   12795:                 next if ($configline =~ /^\#/);
                   12796:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12797:                     $managerstab{$configline} = 1;
                   12798:                 }
                   12799:             }
                   12800:             close($config);
                   12801:         }
                   12802:     }
                   12803: }
                   12804: 
1.329     matthew  12805: # ------------- set up temporary directory
                   12806: {
1.1117    foxr     12807:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12808: 
1.11      www      12809: }
                   12810: 
1.794     albertel 12811: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12812: 				'compress_threshold'=> 20_000,
                   12813:  			        });
1.185     www      12814: 
1.281     www      12815: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12816: $dumpcount=0;
1.958     www      12817: $locknum=0;
1.22      www      12818: 
1.163     harris41 12819: &logtouch();
1.672     albertel 12820: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12821: $readit=1;
1.564     albertel 12822:     {
                   12823: 	use integer;
                   12824: 	my $test=(2**32)+1;
1.568     albertel 12825: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12826: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12827:     }
1.195     www      12828: }
1.1       albertel 12829: }
1.179     www      12830: 
1.1       albertel 12831: 1;
1.191     harris41 12832: __END__
                   12833: 
1.243     albertel 12834: =pod
                   12835: 
1.191     harris41 12836: =head1 NAME
                   12837: 
1.243     albertel 12838: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12839: 
                   12840: =head1 SYNOPSIS
                   12841: 
1.243     albertel 12842: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12843: 
                   12844:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12845: 
1.243     albertel 12846: Common parameters:
                   12847: 
                   12848: =over 4
                   12849: 
                   12850: =item *
                   12851: 
                   12852: $uname : an internal username (if $cname expecting a course Id specifically)
                   12853: 
                   12854: =item *
                   12855: 
                   12856: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12857: 
                   12858: =item *
                   12859: 
                   12860: $symb : a resource instance identifier
                   12861: 
                   12862: =item *
                   12863: 
                   12864: $namespace : the name of a .db file that contains the data needed or
                   12865: being set.
                   12866: 
                   12867: =back
                   12868: 
1.394     bowersj2 12869: =head1 OVERVIEW
1.191     harris41 12870: 
1.394     bowersj2 12871: lonnet provides subroutines which interact with the
                   12872: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12873: about classes, users, and resources.
1.243     albertel 12874: 
                   12875: For many of these objects you can also use this to store data about
                   12876: them or modify them in various ways.
1.191     harris41 12877: 
1.394     bowersj2 12878: =head2 Symbs
1.191     harris41 12879: 
1.394     bowersj2 12880: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12881: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12882: map, the resource number of the resource in the map, and the URL of
                   12883: the resource itself. The latter is somewhat redundant, but might help
                   12884: if maps change.
                   12885: 
                   12886: An example is
                   12887: 
                   12888:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12889: 
                   12890: The respective map entry is
                   12891: 
                   12892:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12893:   title="Problem 2">
                   12894:  </resource>
                   12895: 
                   12896: Symbs are used by the random number generator, as well as to store and
                   12897: restore data specific to a certain instance of for example a problem.
                   12898: 
                   12899: =head2 Storing And Retrieving Data
                   12900: 
                   12901: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12902: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12903: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12904: is is the non-critical message twin of cstore. These functions are for
                   12905: handlers to store a perl hash to a user's permanent data space in an
                   12906: easy manner, and to retrieve it again on another call. It is expected
                   12907: that a handler would use this once at the beginning to retrieve data,
                   12908: and then again once at the end to send only the new data back.
                   12909: 
                   12910: The data is stored in the user's data directory on the user's
                   12911: homeserver under the ID of the course.
                   12912: 
                   12913: The hash that is returned by restore will have all of the previous
                   12914: value for all of the elements of the hash.
                   12915: 
                   12916: Example:
                   12917: 
                   12918:  #creating a hash
                   12919:  my %hash;
                   12920:  $hash{'foo'}='bar';
                   12921: 
                   12922:  #storing it
                   12923:  &Apache::lonnet::cstore(\%hash);
                   12924: 
                   12925:  #changing a value
                   12926:  $hash{'foo'}='notbar';
                   12927: 
                   12928:  #adding a new value
                   12929:  $hash{'bar'}='foo';
                   12930:  &Apache::lonnet::cstore(\%hash);
                   12931: 
                   12932:  #retrieving the hash
                   12933:  my %history=&Apache::lonnet::restore();
                   12934: 
                   12935:  #print the hash
                   12936:  foreach my $key (sort(keys(%history))) {
                   12937:    print("\%history{$key} = $history{$key}");
                   12938:  }
                   12939: 
                   12940: Will print out:
1.191     harris41 12941: 
1.394     bowersj2 12942:  %history{1:foo} = bar
                   12943:  %history{1:keys} = foo:timestamp
                   12944:  %history{1:timestamp} = 990455579
                   12945:  %history{2:bar} = foo
                   12946:  %history{2:foo} = notbar
                   12947:  %history{2:keys} = foo:bar:timestamp
                   12948:  %history{2:timestamp} = 990455580
                   12949:  %history{bar} = foo
                   12950:  %history{foo} = notbar
                   12951:  %history{timestamp} = 990455580
                   12952:  %history{version} = 2
                   12953: 
                   12954: Note that the special hash entries C<keys>, C<version> and
                   12955: C<timestamp> were added to the hash. C<version> will be equal to the
                   12956: total number of versions of the data that have been stored. The
                   12957: C<timestamp> attribute will be the UNIX time the hash was
                   12958: stored. C<keys> is available in every historical section to list which
                   12959: keys were added or changed at a specific historical revision of a
                   12960: hash.
                   12961: 
                   12962: B<Warning>: do not store the hash that restore returns directly. This
                   12963: will cause a mess since it will restore the historical keys as if the
                   12964: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 12965: 
1.394     bowersj2 12966: Calling convention:
1.191     harris41 12967: 
1.1172.2.27  raeburn  12968:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  12969:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 12970: 
1.394     bowersj2 12971: For more detailed information, see lonnet specific documentation.
1.191     harris41 12972: 
1.394     bowersj2 12973: =head1 RETURN MESSAGES
1.191     harris41 12974: 
1.394     bowersj2 12975: =over 4
1.191     harris41 12976: 
1.394     bowersj2 12977: =item * B<con_lost>: unable to contact remote host
1.191     harris41 12978: 
1.394     bowersj2 12979: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   12980: when the connection is brought back up
1.191     harris41 12981: 
1.394     bowersj2 12982: =item * B<con_failed>: unable to contact remote host and unable to save message
                   12983: for later delivery
1.191     harris41 12984: 
1.967     bisitz   12985: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 12986: 
1.394     bowersj2 12987: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 12988: that was requested
1.191     harris41 12989: 
1.243     albertel 12990: =back
1.191     harris41 12991: 
1.243     albertel 12992: =head1 PUBLIC SUBROUTINES
1.191     harris41 12993: 
1.243     albertel 12994: =head2 Session Environment Functions
1.191     harris41 12995: 
1.243     albertel 12996: =over 4
1.191     harris41 12997: 
1.394     bowersj2 12998: =item * 
                   12999: X<appenv()>
1.949     raeburn  13000: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13001: the user envirnoment file, and will be restored for each access this
1.620     albertel 13002: user makes during this session, also modifies the %env for the current
1.949     raeburn  13003: process. Optional rolesarrayref - if defined contains a reference to an array
                   13004: of roles which are exempt from the restriction on modifying user.role entries 
                   13005: in the user's environment.db and in %env.    
1.191     harris41 13006: 
                   13007: =item *
1.394     bowersj2 13008: X<delenv()>
1.987     raeburn  13009: B<delenv($delthis,$regexp)>: removes all items from the session
                   13010: environment file that begin with $delthis. If the 
                   13011: optional second arg - $regexp - is true, $delthis is treated as a 
                   13012: regular expression, otherwise \Q$delthis\E is used. 
                   13013: The values are also deleted from the current processes %env.
1.191     harris41 13014: 
1.795     albertel 13015: =item * get_env_multiple($name) 
                   13016: 
                   13017: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13018: values may be defined and end up as an array ref.
                   13019: 
                   13020: returns an array of values
                   13021: 
1.243     albertel 13022: =back
                   13023: 
                   13024: =head2 User Information
1.191     harris41 13025: 
1.243     albertel 13026: =over 4
1.191     harris41 13027: 
                   13028: =item *
1.394     bowersj2 13029: X<queryauthenticate()>
                   13030: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13031: authentication scheme
                   13032: 
                   13033: =item *
1.394     bowersj2 13034: X<authenticate()>
1.1073    raeburn  13035: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13036: authenticate user from domain's lib servers (first use the current
                   13037: one). C<$upass> should be the users password.
1.1073    raeburn  13038: $checkdefauth is optional (value is 1 if a check should be made to
                   13039:    authenticate user using default authentication method, and allow
                   13040:    account creation if username does not have account in the domain).
                   13041: $clientcancheckhost is optional (value is 1 if checking whether the
                   13042:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13043: 
                   13044: =item *
1.394     bowersj2 13045: X<homeserver()>
                   13046: B<homeserver($uname,$udom)>: find the server which has
                   13047: the user's directory and files (there must be only one), this caches
                   13048: the answer, and also caches if there is a borken connection.
1.191     harris41 13049: 
                   13050: =item *
1.394     bowersj2 13051: X<idget()>
                   13052: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13053: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13054: username, and only 1 username per ID in a specific domain) (returns
                   13055: hash: id=>name,id=>name)
1.191     harris41 13056: 
                   13057: =item *
1.394     bowersj2 13058: X<idrget()>
                   13059: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13060: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13061: 
                   13062: =item *
1.394     bowersj2 13063: X<idput()>
                   13064: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13065: 
                   13066: =item *
1.394     bowersj2 13067: X<rolesinit()>
1.1169    droeschl 13068: B<rolesinit($udom,$username)>: get user privileges.
                   13069: returns user role, first access and timer interval hashes
1.243     albertel 13070: 
                   13071: =item *
1.1171    droeschl 13072: X<privileged()>
                   13073: B<privileged($username,$domain)>: returns a true if user has a
                   13074: privileged and active role (i.e. su or dc), false otherwise.
                   13075: 
                   13076: =item *
1.551     albertel 13077: X<getsection()>
                   13078: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13079: course $cname, return section name/number or '' for "not in course"
                   13080: and '-1' for "no section"
                   13081: 
                   13082: =item *
1.394     bowersj2 13083: X<userenvironment()>
                   13084: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13085: passed in @what from the requested user's environment, returns a hash
                   13086: 
1.858     raeburn  13087: =item * 
                   13088: X<userlog_query()>
1.859     albertel 13089: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13090: activity.log file. %filters defines filters applied when parsing the
                   13091: log file. These can be start or end timestamps, or the type of action
                   13092: - log to look for Login or Logout events, check for Checkin or
                   13093: Checkout, role for role selection. The response is in the form
                   13094: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13095: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13096: 
1.243     albertel 13097: =back
                   13098: 
                   13099: =head2 User Roles
                   13100: 
                   13101: =over 4
                   13102: 
                   13103: =item *
                   13104: 
1.1172.2.65  raeburn  13105: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13106: returns codes for allowed actions.
                   13107: 
                   13108: The first argument is required, all others are optional.
                   13109: 
                   13110: $priv is the privilege being checked.
                   13111: $uri contains additional information about what is being checked for access (e.g.,
                   13112: URL, course ID etc.).
                   13113: $symb is the unique resource instance identifier in a course; if needed,
                   13114: but not provided, it will be retrieved via a call to &symbread().
                   13115: $role is the role for which a priv is being checked (only used if priv is evb).
                   13116: $clientip is the user's IP address (only used when checking for access to portfolio
                   13117: files).
                   13118: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   13119: prevents recursive calls to &allowed.
                   13120: 
1.243     albertel 13121:  F: full access
                   13122:  U,I,K: authentication modes (cxx only)
                   13123:  '': forbidden
                   13124:  1: user needs to choose course
                   13125:  2: browse allowed
1.766     albertel 13126:  A: passphrase authentication needed
1.1172.2.65  raeburn  13127:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13128: 
                   13129: =item *
                   13130: 
1.1172.2.13  raeburn  13131: constructaccess($url,$setpriv) : check for access to construction space URL
                   13132: 
                   13133: See if the owner domain and name in the URL match those in the
                   13134: expected environment.  If so, return three element list
                   13135: ($ownername,$ownerdomain,$ownerhome).
                   13136: 
                   13137: Otherwise return the null string.
                   13138: 
                   13139: If second argument 'setpriv' is true, it assigns the privileges,
                   13140: and returns the same three element list, unless the owner has
                   13141: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13142: in which case the null string is returned.
                   13143: 
                   13144: =item *
                   13145: 
1.243     albertel 13146: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   13147: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   13148: and course level
                   13149: 
                   13150: =item *
                   13151: 
1.988     raeburn  13152: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13153: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13154: $type is Course (default) or Community.
1.988     raeburn  13155: If $forcedefault evaluates to true, text returned will be default 
                   13156: text for $type. Otherwise, if this is a course, the text returned 
                   13157: will be a custom name for the role (if defined in the course's 
                   13158: environment).  If no custom name is defined the default is returned.
                   13159:    
1.832     raeburn  13160: =item *
                   13161: 
1.1172.2.23  raeburn  13162: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13163: All arguments are optional. Returns a hash of a roles, either for
                   13164: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13165: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13166: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13167: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13168: For each key, value is set to colon-separated start and end times for
                   13169: the role.  If no username and domain are specified, will default to
1.934     raeburn  13170: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13171: of role statuses (active, future or previous), roles 
                   13172: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13173: to restrict the list of roles reported. If no array ref is 
                   13174: provided for types, will default to return only active roles.
1.834     albertel 13175: 
1.1172.2.13  raeburn  13176: =item *
                   13177: 
                   13178: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   13179: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   13180: 
                   13181: Additional optional arguments are: $type (if role checking is to be restricted
                   13182: to certain user status types -- previous (expired roles), active (currently
                   13183: available roles) or future (roles available in the future), and
                   13184: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  13185: have active Domain Coordinator role in course's domain or in additional
                   13186: domains (specified in 'Domains to check for privileged users' in course
                   13187: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13188: 
                   13189: =item *
                   13190: 
                   13191: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13192: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13193: $possdomains and $possroles are optional array refs -- to domains to check and
                   13194: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13195: users' roles.db to check for a dc or su role in any domain. This can be
                   13196: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13197: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13198: this then allows &privileged_by_domain() to be used, which caches the identity
                   13199: of privileged users, eliminating the need for repeated calls to &dump().
                   13200: 
                   13201: =item *
                   13202: 
                   13203: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13204: where the outer hash keys are domains specified in the $possdomains array ref,
                   13205: next inner hash keys are privileged roles specified in the $roles array ref,
                   13206: and the innermost hash contains key = value pairs for username:domain = end:start
                   13207: for active or future "privileged" users with that role in that domain. To avoid
                   13208: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13209: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  13210: 
1.243     albertel 13211: =back
                   13212: 
                   13213: =head2 User Modification
                   13214: 
                   13215: =over 4
                   13216: 
                   13217: =item *
                   13218: 
1.957     raeburn  13219: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13220: user for the level given by URL.  Optional start and end dates (leave empty
                   13221: string or zero for "no date")
1.191     harris41 13222: 
                   13223: =item *
                   13224: 
1.243     albertel 13225: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13226: change a users, password, possible return values are: ok,
                   13227: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13228: refused
1.191     harris41 13229: 
                   13230: =item *
                   13231: 
1.243     albertel 13232: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13233: 
                   13234: =item *
                   13235: 
1.1058    raeburn  13236: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13237:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13238: 
                   13239: will update user information (firstname,middlename,lastname,generation,
                   13240: permanentemail), and if forceid is true, student/employee ID also.
                   13241: A user's institutional affiliation(s) can also be updated.
                   13242: User information fields will not be overwritten with empty entries 
                   13243: unless the field is included in the $candelete array reference.
                   13244: This array is included when a single user is modified via "Manage Users",
                   13245: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13246: 
                   13247: =item *
                   13248: 
1.286     matthew  13249: modifystudent
                   13250: 
1.957     raeburn  13251: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  13252: The course id is resolved based on the current user's environment.  
                   13253: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13254: associated with a course.
                   13255: 
1.297     matthew  13256: This call is essentially a wrapper for lonnet::modifyuser and
                   13257: lonnet::modify_student_enrollment
1.286     matthew  13258: 
                   13259: Inputs: 
                   13260: 
                   13261: =over 4
                   13262: 
1.957     raeburn  13263: =item B<$udom> Student's loncapa domain
1.286     matthew  13264: 
1.957     raeburn  13265: =item B<$uname> Student's loncapa login name
1.286     matthew  13266: 
1.964     bisitz   13267: =item B<$uid> Student/Employee ID
1.286     matthew  13268: 
1.957     raeburn  13269: =item B<$umode> Student's authentication mode
1.286     matthew  13270: 
1.957     raeburn  13271: =item B<$upass> Student's password
1.286     matthew  13272: 
1.957     raeburn  13273: =item B<$first> Student's first name
1.286     matthew  13274: 
1.957     raeburn  13275: =item B<$middle> Student's middle name
1.286     matthew  13276: 
1.957     raeburn  13277: =item B<$last> Student's last name
1.286     matthew  13278: 
1.957     raeburn  13279: =item B<$gene> Student's generation
1.286     matthew  13280: 
1.957     raeburn  13281: =item B<$usec> Student's section in course
1.286     matthew  13282: 
                   13283: =item B<$end> Unix time of the roles expiration
                   13284: 
                   13285: =item B<$start> Unix time of the roles start date
                   13286: 
                   13287: =item B<$forceid> If defined, allow $uid to be changed
                   13288: 
                   13289: =item B<$desiredhome> server to use as home server for student
                   13290: 
1.957     raeburn  13291: =item B<$email> Student's permanent e-mail address
                   13292: 
                   13293: =item B<$type> Type of enrollment (auto or manual)
                   13294: 
1.963     raeburn  13295: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13296: 
                   13297: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13298: 
1.963     raeburn  13299: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13300: 
1.963     raeburn  13301: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13302: 
1.1172.2.19  raeburn  13303: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13304: 
                   13305: =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  13306: 
1.286     matthew  13307: =back
1.297     matthew  13308: 
                   13309: =item *
                   13310: 
                   13311: modify_student_enrollment
                   13312: 
1.1172.2.31  raeburn  13313: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13314: 'role.request.course' must be defined for this function to proceed.
                   13315: 
                   13316: Inputs:
                   13317: 
                   13318: =over 4
                   13319: 
1.1172.2.31  raeburn  13320: =item $udom, student's domain
1.297     matthew  13321: 
1.1172.2.31  raeburn  13322: =item $uname, student's name
1.297     matthew  13323: 
1.1172.2.31  raeburn  13324: =item $uid, student's user id
1.297     matthew  13325: 
1.1172.2.31  raeburn  13326: =item $first, student's first name
1.297     matthew  13327: 
                   13328: =item $middle
                   13329: 
                   13330: =item $last
                   13331: 
                   13332: =item $gene
                   13333: 
                   13334: =item $usec
                   13335: 
                   13336: =item $end
                   13337: 
                   13338: =item $start
                   13339: 
1.957     raeburn  13340: =item $type
                   13341: 
                   13342: =item $locktype
                   13343: 
                   13344: =item $cid
                   13345: 
                   13346: =item $selfenroll
                   13347: 
                   13348: =item $context
                   13349: 
1.1172.2.19  raeburn  13350: =item $credits, number of credits student will earn from this class
                   13351: 
1.297     matthew  13352: =back
                   13353: 
1.191     harris41 13354: 
                   13355: =item *
                   13356: 
1.243     albertel 13357: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13358: custom role; give a custom role to a user for the level given by URL.  Specify
                   13359: name and domain of role author, and role name
1.191     harris41 13360: 
                   13361: =item *
                   13362: 
1.243     albertel 13363: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13364: 
                   13365: =item *
                   13366: 
1.243     albertel 13367: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13368: 
                   13369: =back
                   13370: 
                   13371: =head2 Course Infomation
                   13372: 
                   13373: =over 4
1.191     harris41 13374: 
                   13375: =item *
                   13376: 
1.1118    foxr     13377: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13378: specified course id, including all environment settings for the
                   13379: course, the description of the course will be in the hash under the
                   13380: key 'description'
1.191     harris41 13381: 
1.1118    foxr     13382: $options is an optional parameter that if supplied is a hash reference that controls
                   13383: what how this function works.  It has the following key/values:
                   13384: 
                   13385: =over 4
                   13386: 
                   13387: =item freshen_cache
                   13388: 
                   13389: If defined, and the environment cache for the course is valid, it is 
                   13390: returned in the returned hash.
                   13391: 
                   13392: =item one_time
                   13393: 
                   13394: If defined, the last cache time is set to _now_
                   13395: 
                   13396: =item user
                   13397: 
                   13398: If defined, the supplied username is used instead of the current user.
                   13399: 
                   13400: 
                   13401: =back
                   13402: 
1.191     harris41 13403: =item *
                   13404: 
1.624     albertel 13405: resdata($name,$domain,$type,@which) : request for current parameter
                   13406: setting for a specific $type, where $type is either 'course' or 'user',
                   13407: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  13408: answers for 10 minutes.
1.243     albertel 13409: 
1.877     foxr     13410: =item *
                   13411: 
                   13412: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13413: data base, returning a hash that is keyed by the resource name and has
                   13414: values that are the resource value.  I believe that the timestamps and
                   13415: versions are also returned.
                   13416: 
1.1172.2.31  raeburn  13417: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13418: supplemental content area. This routine caches the number of files for
                   13419: 10 minutes.
                   13420: 
1.243     albertel 13421: =back
                   13422: 
                   13423: =head2 Course Modification
                   13424: 
                   13425: =over 4
1.191     harris41 13426: 
                   13427: =item *
                   13428: 
1.243     albertel 13429: writecoursepref($courseid,%prefs) : write preferences (environment
                   13430: database) for a course
1.191     harris41 13431: 
                   13432: =item *
                   13433: 
1.1011    raeburn  13434: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13435: 
                   13436: =item *
                   13437: 
1.1038    raeburn  13438: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13439: 
1.1167    droeschl 13440: =item *
                   13441: 
                   13442: is_course($courseid), is_course($cdom, $cnum)
                   13443: 
                   13444: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13445: two component version $cdom, $cnum. It checks if the specified course exists.
                   13446: 
                   13447: Returns:
                   13448:     undef if the course doesn't exist, otherwise
                   13449:     in scalar context the combined courseid.
                   13450:     in list context the two components of the course identifier, domain and 
                   13451:     courseid.    
                   13452: 
1.243     albertel 13453: =back
                   13454: 
                   13455: =head2 Resource Subroutines
                   13456: 
                   13457: =over 4
1.191     harris41 13458: 
                   13459: =item *
                   13460: 
1.243     albertel 13461: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13462: 
                   13463: =item *
                   13464: 
1.243     albertel 13465: repcopy($filename) : subscribes to the requested file, and attempts to
                   13466: replicate from the owning library server, Might return
1.607     raeburn  13467: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13468: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13469: resource. Expects the local filesystem pathname
                   13470: (/home/httpd/html/res/....)
                   13471: 
                   13472: =back
                   13473: 
                   13474: =head2 Resource Information
                   13475: 
                   13476: =over 4
1.191     harris41 13477: 
                   13478: =item *
                   13479: 
1.1172.2.28  raeburn  13480: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13481: and returns the value of a variety of different possible values,
                   13482: $varname should be a request string, and the other parameters can be
                   13483: used to specify who and what one is asking about. Ordinarily, $cid 
                   13484: does not need to be specified, as it is retrived from 
                   13485: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13486: within lonuserstate::loadmap() when initializing a course, before
                   13487: $env{'request.course.id'} has been set, so it needs to be provided
                   13488: in that one case.
1.243     albertel 13489: 
                   13490: Possible values for $varname are environment.lastname (or other item
                   13491: from the envirnment hash), user.name (or someother aspect about the
                   13492: user), resource.0.maxtries (or some other part and parameter of a
                   13493: resource)
1.204     albertel 13494: 
                   13495: =item *
                   13496: 
1.243     albertel 13497: directcondval($number) : get current value of a condition; reads from a state
                   13498: string
1.204     albertel 13499: 
                   13500: =item *
                   13501: 
1.243     albertel 13502: condval($condidx) : value of condition index based on state
1.204     albertel 13503: 
                   13504: =item *
                   13505: 
1.243     albertel 13506: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13507: resource's metadata, $what should be either a specific key, or either
                   13508: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13509: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13510: 
                   13511: this function automatically caches all requests
1.191     harris41 13512: 
                   13513: =item *
                   13514: 
1.243     albertel 13515: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13516: network of library servers; returns file handle of where SQL and regex results
                   13517: will be stored for query
1.191     harris41 13518: 
                   13519: =item *
                   13520: 
1.1172.2.66  raeburn  13521: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   13522: return symbolic list entry (all arguments optional).
                   13523: 
                   13524: Args: filename is the filename (including path) for the file for which a symb
                   13525: is required; donotrecurse, if true will prevent calls to allowed() being made
                   13526: to check access status if more than one resource was found in the bighash
                   13527: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   13528: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   13529: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   13530: cause possible symbs to be checked to determine if they are subject to content
                   13531: blocking, if so they will not be included as possible symbs; possibles is a
                   13532: ref to a hash, which, as a side effect, will be populated with all possible
                   13533: symbs (content blocking not tested).
                   13534: 
1.243     albertel 13535: returns the data handle
1.191     harris41 13536: 
                   13537: =item *
                   13538: 
1.1172.2.17  raeburn  13539: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  13540: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13541: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  13542: on failure, user must be in a course, as it assumes the existence of
                   13543: the course initial hash, and uses $env('request.course.id'}.  The third
                   13544: arg is an optional reference to a scalar.  If this arg is passed in the
                   13545: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13546: encrypted; otherwise it will be null.
1.243     albertel 13547: 
1.191     harris41 13548: =item *
                   13549: 
1.243     albertel 13550: symbclean($symb) : removes versions numbers from a symb, returns the
                   13551: cleaned symb
1.191     harris41 13552: 
                   13553: =item *
                   13554: 
1.243     albertel 13555: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13556: course map, user must be in a course for it to work.
1.191     harris41 13557: 
                   13558: =item *
                   13559: 
1.243     albertel 13560: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13561: 
                   13562: =item *
                   13563: 
1.243     albertel 13564: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13565: a random seed, all arguments are optional, if they aren't sent it uses the
                   13566: environment to derive them. Note: if symb isn't sent and it can't get one
                   13567: from &symbread it will use the current time as its return value
1.191     harris41 13568: 
                   13569: =item *
                   13570: 
1.243     albertel 13571: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13572: unfakeable, receipt
1.191     harris41 13573: 
                   13574: =item *
                   13575: 
1.620     albertel 13576: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13577: 
                   13578: =item *
                   13579: 
1.243     albertel 13580: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13581: 
                   13582: =item *
                   13583: 
1.243     albertel 13584: 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 13585: 
                   13586: =item *
                   13587: 
1.243     albertel 13588: 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 13589: 
                   13590: =item *
                   13591: 
1.243     albertel 13592: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13593: 
                   13594: =item *
                   13595: 
1.243     albertel 13596: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13597: forcing spreadsheet to reevaluate the resource scores next time.
                   13598: 
1.1172.2.13  raeburn  13599: =item *
                   13600: 
                   13601: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13602: when viewing in course context.
                   13603: 
                   13604:  input: six args -- filename (decluttered), course number, course domain,
                   13605:                     url, symb (if registered) and group (if this is a
                   13606:                     group item -- e.g., bulletin board, group page etc.).
                   13607: 
                   13608:  output: array of five scalars --
                   13609:          $cfile -- url for file editing if editable on current server
                   13610:          $home -- homeserver of resource (i.e., for author if published,
                   13611:                                           or course if uploaded.).
                   13612:          $switchserver --  1 if server switch will be needed.
                   13613:          $forceedit -- 1 if icon/link should be to go to edit mode
                   13614:          $forceview -- 1 if icon/link should be to go to view mode
                   13615: 
                   13616: =item *
                   13617: 
                   13618: is_course_upload($file,$cnum,$cdom)
                   13619: 
                   13620: Used in course context to determine if current file was uploaded to
                   13621: the course (i.e., would be found in /userfiles/docs on the course's
                   13622: homeserver.
                   13623: 
                   13624:   input: 3 args -- filename (decluttered), course number and course domain.
                   13625:   output: boolean -- 1 if file was uploaded.
                   13626: 
1.243     albertel 13627: =back
                   13628: 
                   13629: =head2 Storing/Retreiving Data
                   13630: 
                   13631: =over 4
1.191     harris41 13632: 
                   13633: =item *
                   13634: 
1.1172.2.64  raeburn  13635: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   13636: permanently for this url; hashref needs to be given and should be a \%hashname;
                   13637: the remaining args aren't required and if they aren't passed or are '' they will
                   13638: be derived from the env (with the exception of $laststore, which is an
                   13639: optional arg used when a user's submission is stored in grading).
                   13640: $laststore is $version=$timestamp, where $version is the most recent version
                   13641: number retrieved for the corresponding $symb in the $namespace db file, and
                   13642: $timestamp is the timestamp for that transaction (UNIX time).
                   13643: $laststore is currently only passed when cstore() is called by
                   13644: structuretags::finalize_storage().
1.191     harris41 13645: 
                   13646: =item *
                   13647: 
1.1172.2.64  raeburn  13648: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   13649: but uses critical subroutine
1.191     harris41 13650: 
                   13651: =item *
                   13652: 
1.243     albertel 13653: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13654: all args are optional
1.191     harris41 13655: 
                   13656: =item *
                   13657: 
1.717     albertel 13658: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13659: dumps the complete (or key matching regexp) namespace into a hash
                   13660: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13661: normally &store()ed into
                   13662: 
                   13663: $range should be either an integer '100' (give me the first 100
                   13664:                                            matching records)
                   13665:               or be  two integers sperated by a - with no spaces
                   13666:                  '30-50' (give me the 30th through the 50th matching
                   13667:                           records)
                   13668: 
                   13669: 
                   13670: =item *
                   13671: 
1.1172.2.59  raeburn  13672: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 13673: replaces a &store() version of data with a replacement set of data
                   13674: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  13675: reference. If $tolog is true, the transaction is logged in the courselog
                   13676: with an action=PUTSTORE.
1.717     albertel 13677: 
                   13678: =item *
                   13679: 
1.243     albertel 13680: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13681: works very similar to store/cstore, but all data is stored in a
                   13682: temporary location and can be reset using tmpreset, $storehash should
                   13683: be a hash reference, returns nothing on success
1.191     harris41 13684: 
                   13685: =item *
                   13686: 
1.243     albertel 13687: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13688: similar to restore, but all data is stored in a temporary location and
                   13689: can be reset using tmpreset. Returns a hash of values on success,
                   13690: error string otherwise.
1.191     harris41 13691: 
                   13692: =item *
                   13693: 
1.243     albertel 13694: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13695: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13696: 
                   13697: =item *
                   13698: 
1.243     albertel 13699: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13700: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13701: 
                   13702: =item *
                   13703: 
1.243     albertel 13704: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13705: namesp ($udom and $uname are optional)
1.191     harris41 13706: 
                   13707: =item *
                   13708: 
1.702     albertel 13709: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13710: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13711: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13712: 
1.702     albertel 13713: $range should be either an integer '100' (give me the first 100
                   13714:                                            matching records)
                   13715:               or be  two integers sperated by a - with no spaces
                   13716:                  '30-50' (give me the 30th through the 50th matching
                   13717:                           records)
1.449     matthew  13718: =item *
                   13719: 
                   13720: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13721: $store can be a scalar, an array reference, or if the amount to be 
                   13722: incremented is > 1, a hash reference.
                   13723: 
                   13724: ($udom and $uname are optional)
1.191     harris41 13725: 
                   13726: =item *
                   13727: 
1.243     albertel 13728: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13729: ($udom and $uname are optional)
1.191     harris41 13730: 
                   13731: =item *
                   13732: 
1.243     albertel 13733: cput($namespace,$storehash,$udom,$uname) : critical put
                   13734: ($udom and $uname are optional)
1.191     harris41 13735: 
                   13736: =item *
                   13737: 
1.748     albertel 13738: newput($namespace,$storehash,$udom,$uname) :
                   13739: 
                   13740: Attempts to store the items in the $storehash, but only if they don't
                   13741: currently exist, if this succeeds you can be certain that you have 
                   13742: successfully created a new key value pair in the $namespace db.
                   13743: 
                   13744: 
                   13745: Args:
                   13746:  $namespace: name of database to store values to
                   13747:  $storehash: hashref to store to the db
                   13748:  $udom: (optional) domain of user containing the db
                   13749:  $uname: (optional) name of user caontaining the db
                   13750: 
                   13751: Returns:
                   13752:  'ok' -> succeeded in storing all keys of $storehash
                   13753:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13754:                         least <key> already existed in the db (other
                   13755:                         requested keys may also already exist)
1.967     bisitz   13756:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13757:  'con_lost' -> unable to contact request server
                   13758:  'refused' -> action was not allowed by remote machine
                   13759: 
                   13760: 
                   13761: =item *
                   13762: 
1.243     albertel 13763: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13764: reference filled in from namesp (encrypts the return communication)
                   13765: ($udom and $uname are optional)
1.191     harris41 13766: 
                   13767: =item *
                   13768: 
1.243     albertel 13769: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13770: critical subroutine
                   13771: 
1.806     raeburn  13772: =item *
                   13773: 
1.860     raeburn  13774: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13775: array reference filled in from namespace found in domain level on either
                   13776: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13777: 
                   13778: =item *
                   13779: 
1.860     raeburn  13780: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13781: domain level either on specified domain server ($uhome) or primary domain 
                   13782: server ($udom and $uhome are optional)
1.806     raeburn  13783: 
1.943     raeburn  13784: =item * 
                   13785: 
1.1172.2.35  raeburn  13786: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   13787: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13788: the target domain.
                   13789: 
                   13790: May also include additional key => value pairs for the following groups:
                   13791: 
                   13792: =over
                   13793: 
                   13794: =item
                   13795: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13796: 
                   13797: =over
                   13798: 
                   13799: =item defaultquota, authorquota
                   13800: 
                   13801: =back
                   13802: 
                   13803: =item
                   13804: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13805: portfolio for users).
                   13806: 
                   13807: =over
                   13808: 
                   13809: =item
                   13810: aboutme, blog, webdav, portfolio
                   13811: 
                   13812: =back
                   13813: 
                   13814: =item
                   13815: requestcourses: ability to request courses, and how requests are processed.
                   13816: 
                   13817: =over
                   13818: 
                   13819: =item
1.1172.2.37  raeburn  13820: official, unofficial, community, textbook
1.1172.2.35  raeburn  13821: 
                   13822: =back
                   13823: 
                   13824: =item
                   13825: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13826: 
                   13827: =over
                   13828: 
                   13829: =item
1.1172.2.44  raeburn  13830: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  13831: 
                   13832: =back
                   13833: 
                   13834: =item
                   13835: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13836: for course's uploaded content.
                   13837: 
                   13838: =over
                   13839: 
                   13840: =item
1.1172.2.68  raeburn  13841: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   13842: communityquota, textbookquota
1.1172.2.35  raeburn  13843: 
                   13844: =back
                   13845: 
                   13846: =item
                   13847: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13848: on your servers.
                   13849: 
                   13850: =over
                   13851: 
                   13852: =item
                   13853: remotesessions, hostedsessions
                   13854: 
                   13855: =back
                   13856: 
                   13857: =back
                   13858: 
                   13859: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13860: utility to create a configuration.db file on a domain's primary library server
                   13861: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13862: -- corresponding values are authentication type (internal, krb4, krb5,
                   13863: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   13864: will be available. Values are retrieved from cache (if current), unless the
                   13865: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13866: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13867: 
                   13868: Typical usage:
1.943     raeburn  13869: 
1.1172.2.35  raeburn  13870: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13871: 
1.243     albertel 13872: =back
                   13873: 
                   13874: =head2 Network Status Functions
                   13875: 
                   13876: =over 4
1.191     harris41 13877: 
                   13878: =item *
                   13879: 
1.1137    raeburn  13880: dirlist() : return directory list based on URI (first arg).
                   13881: 
                   13882: Inputs: 1 required, 5 optional.
                   13883: 
                   13884: =over
                   13885: 
                   13886: =item 
                   13887: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13888: 
                   13889: =item
                   13890: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13891: 
                   13892: =item
                   13893: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13894: 
                   13895: =item
                   13896: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13897: 
                   13898: =item
                   13899: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13900: 
                   13901: =item 
                   13902: $alternateRoot - path to prepend in place of path from $uri.
                   13903: 
                   13904: =back
                   13905: 
                   13906: Returns: Array of up to two items.
                   13907: 
                   13908: =over
                   13909: 
                   13910: a reference to an array of files/subdirectories
                   13911: 
                   13912: =over
                   13913: 
                   13914: Each element in the array of files/subdirectories is a & separated list of
                   13915: item name and the result of running stat on the item.  If dirlist was requested
                   13916: for a file instead of a directory, the item name will be ''. For a directory 
                   13917: listing, if the item is a metadata file, the element will end &N&M 
                   13918: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13919: default copyright set (1).  
                   13920: 
                   13921: =back
                   13922: 
                   13923: a scalar containing error condition (if encountered).
                   13924: 
                   13925: =over
                   13926: 
                   13927: =item 
                   13928: no_host (no homeserver identified for $username:$domain).
                   13929: 
                   13930: =item 
                   13931: no_such_host (server contacted for listing not identified as valid host).
                   13932: 
                   13933: =item 
                   13934: con_lost (connection to remote server failed).
                   13935: 
                   13936: =item 
                   13937: refused (invalid $username:$domain received on lond side).
                   13938: 
                   13939: =item 
                   13940: no_such_dir (directory at specified path on lond side does not exist). 
                   13941: 
                   13942: =item 
                   13943: empty (directory at specified path on lond side is empty).
                   13944: 
                   13945: =over
                   13946: 
                   13947: This is currently not encountered because the &ls3, &ls2, 
                   13948: &ls (_handler) routines on the lond side do not filter out
                   13949: . and .. from a directory listing. 
                   13950: 
                   13951: =back
                   13952: 
                   13953: =back
                   13954: 
                   13955: =back
1.191     harris41 13956: 
                   13957: =item *
                   13958: 
1.243     albertel 13959: spareserver() : find server with least workload from spare.tab
                   13960: 
1.986     foxr     13961: 
                   13962: =item *
                   13963: 
                   13964: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   13965: if there is no corresponding loncapa host.
                   13966: 
1.243     albertel 13967: =back
                   13968: 
1.986     foxr     13969: 
1.243     albertel 13970: =head2 Apache Request
                   13971: 
                   13972: =over 4
1.191     harris41 13973: 
                   13974: =item *
                   13975: 
1.243     albertel 13976: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   13977: localhost, posts hash
                   13978: 
                   13979: =back
                   13980: 
                   13981: =head2 Data to String to Data
                   13982: 
                   13983: =over 4
1.191     harris41 13984: 
                   13985: =item *
                   13986: 
1.243     albertel 13987: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   13988: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 13989: 
                   13990: =item *
                   13991: 
1.243     albertel 13992: hashref2str($hashref) : convert a hashref into a string complete with
                   13993: escaping and '=' and '&' separators, supports elements that are
                   13994: arrayrefs and hashrefs
1.191     harris41 13995: 
                   13996: =item *
                   13997: 
1.243     albertel 13998: arrayref2str($arrayref) : convert an arrayref into a string complete
                   13999: with escaping and '&' separators, supports elements that are arrayrefs
                   14000: and hashrefs
1.191     harris41 14001: 
                   14002: =item *
                   14003: 
1.243     albertel 14004: str2hash($string) : convert string to hash using unescaping and
                   14005: splitting on '=' and '&', supports elements that are arrayrefs and
                   14006: hashrefs
1.191     harris41 14007: 
                   14008: =item *
                   14009: 
1.243     albertel 14010: str2array($string) : convert string to hash using unescaping and
                   14011: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14012: 
                   14013: =back
                   14014: 
                   14015: =head2 Logging Routines
                   14016: 
                   14017: 
                   14018: These routines allow one to make log messages in the lonnet.log and
                   14019: lonnet.perm logfiles.
1.191     harris41 14020: 
1.1119    foxr     14021: =over 4
                   14022: 
1.191     harris41 14023: =item *
                   14024: 
1.243     albertel 14025: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14026: 
                   14027: =item *
                   14028: 
1.243     albertel 14029: logthis() : append message to the normal lonnet.log file, it gets
                   14030: preiodically rolled over and deleted.
1.191     harris41 14031: 
                   14032: =item *
                   14033: 
1.243     albertel 14034: logperm() : append a permanent message to lonnet.perm.log, this log
                   14035: file never gets deleted by any automated portion of the system, only
                   14036: messages of critical importance should go in here.
                   14037: 
1.1119    foxr     14038: 
1.243     albertel 14039: =back
                   14040: 
                   14041: =head2 General File Helper Routines
                   14042: 
                   14043: =over 4
1.191     harris41 14044: 
                   14045: =item *
                   14046: 
1.481     raeburn  14047: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14048: (a) files in /uploaded
                   14049:   (i) If a local copy of the file exists - 
                   14050:       compares modification date of local copy with last-modified date for 
                   14051:       definitive version stored on home server for course. If local copy is 
                   14052:       stale, requests a new version from the home server and stores it. 
                   14053:       If the original has been removed from the home server, then local copy 
                   14054:       is unlinked.
                   14055:   (ii) If local copy does not exist -
                   14056:       requests the file from the home server and stores it. 
                   14057:   
                   14058:   If $caller is 'uploadrep':  
                   14059:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14060:     for request for files originally uploaded via DOCS. 
                   14061:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14062:   
                   14063:   Otherwise:
                   14064:      This indicates a call from the content generation phase of the request.
                   14065:      -  returns the entire contents of the file or -1.
                   14066:      
                   14067: (b) files in /res
                   14068:    - returns the entire contents of a file or -1; 
                   14069:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14070: 
1.712     albertel 14071: 
                   14072: =item *
                   14073: 
                   14074: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14075:                   reference
                   14076: 
                   14077: returns either a stat() list of data about the file or an empty list
                   14078: if the file doesn't exist or couldn't find out about it (connection
                   14079: problems or user unknown)
                   14080: 
1.191     harris41 14081: =item *
                   14082: 
1.243     albertel 14083: filelocation($dir,$file) : returns file system location of a file
                   14084: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14085: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14086: and a file of ../bob will become /a/bob)
1.191     harris41 14087: 
                   14088: =item *
                   14089: 
                   14090: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14091: filelocation except for hrefs
                   14092: 
                   14093: =item *
                   14094: 
1.1172.2.49  raeburn  14095: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14096: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14097: 
1.243     albertel 14098: =back
                   14099: 
1.608     albertel 14100: =head2 Usererfile file routines (/uploaded*)
                   14101: 
                   14102: =over 4
                   14103: 
                   14104: =item *
                   14105: 
                   14106: userfileupload(): main rotine for putting a file in a user or course's
                   14107:                   filespace, arguments are,
                   14108: 
1.620     albertel 14109:  formname - required - this is the name of the element in $env where the
1.608     albertel 14110:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14111:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14112:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14113:  context - if coursedoc, store the file in the course of the active role
                   14114:              of the current user; 
                   14115:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14116:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14117:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14118:          if undefined, it will be placed in "unknown"
                   14119: 
                   14120:  (This routine calls clean_filename() to remove any dangerous
                   14121:  characters from the filename, and then calls finuserfileupload() to
                   14122:  complete the transaction)
                   14123: 
                   14124:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14125:  and /adm/notfound.html if unsuccessful
                   14126: 
                   14127: =item *
                   14128: 
                   14129: clean_filename(): routine for cleaing a filename up for storage in
                   14130:                  userfile space, argument is:
                   14131: 
                   14132:  filename - proposed filename
                   14133: 
                   14134: returns: the new clean filename
                   14135: 
                   14136: =item *
                   14137: 
1.1090    raeburn  14138: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14139: userspace, probably shouldn't be called directly
                   14140: 
                   14141:   docuname: username or courseid of destination for the file
                   14142:   docudom: domain of user/course of destination for the file
                   14143:   formname: same as for userfileupload()
1.1090    raeburn  14144:   fname: filename (including subdirectories) for the file
                   14145:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14146:   allfiles: reference to hash used to store objects found by parser
                   14147:   codebase: reference to hash used for codebases of java objects found by parser
                   14148:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14149:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14150:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14151:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14152:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14153:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14154:   mimetype: reference to scalar to accommodate mime type determined
                   14155:             from File::MMagic if $parser = parse.
1.608     albertel 14156: 
                   14157:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14158:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14159:  was 'overwrite').
                   14160:  
1.608     albertel 14161: 
                   14162: =item *
                   14163: 
                   14164: renameuserfile(): renames an existing userfile to a new name
                   14165: 
                   14166:   Args:
                   14167:    docuname: username or courseid of destination for the file
                   14168:    docudom: domain of user/course of destination for the file
                   14169:    old: current file name (including any subdirs under userfiles)
                   14170:    new: desired file name (including any subdirs under userfiles)
                   14171: 
                   14172: =item *
                   14173: 
                   14174: mkdiruserfile(): creates a directory is a userfiles dir
                   14175: 
                   14176:   Args:
                   14177:    docuname: username or courseid of destination for the file
                   14178:    docudom: domain of user/course of destination for the file
                   14179:    dir: dir to create (including any subdirs under userfiles)
                   14180: 
                   14181: =item *
                   14182: 
                   14183: removeuserfile(): removes a file that exists in userfiles
                   14184: 
                   14185:   Args:
                   14186:    docuname: username or courseid of destination for the file
                   14187:    docudom: domain of user/course of destination for the file
                   14188:    fname: filname to delete (including any subdirs under userfiles)
                   14189: 
                   14190: =item *
                   14191: 
                   14192: removeuploadedurl(): convience function for removeuserfile()
                   14193: 
                   14194:   Args:
                   14195:    url:  a full /uploaded/... url to delete
                   14196: 
1.747     albertel 14197: =item * 
                   14198: 
                   14199: get_portfile_permissions():
                   14200:   Args:
                   14201:     domain: domain of user or course contain the portfolio files
                   14202:     user: name of user or num of course contain the portfolio files
                   14203:   Returns:
                   14204:     hashref of a dump of the proper file_permissions.db
                   14205:    
                   14206: 
                   14207: =item * 
                   14208: 
                   14209: get_access_controls():
                   14210: 
                   14211: Args:
                   14212:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14213:   group: (optional) the group you want the files associated with
                   14214:   file: (optional) the file you want access info on
                   14215: 
                   14216: Returns:
1.749     raeburn  14217:     a hash (keys are file names) of hashes containing
                   14218:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14219:         values are XML containing access control settings (see below) 
1.747     albertel 14220: 
                   14221: Internal notes:
                   14222: 
1.749     raeburn  14223:  access controls are stored in file_permissions.db as key=value pairs.
                   14224:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14225:         where scope -> public,guest,course,group,domains or users.
                   14226:               end -> UNIX time for end of access (0 -> no end date)
                   14227:               start -> UNIX time for start of access
                   14228: 
                   14229:     value -> XML description of access control
                   14230:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14231:             <start></start>
                   14232:             <end></end>
                   14233: 
                   14234:             <password></password>  for scope type = guest
                   14235: 
                   14236:             <domain></domain>     for scope type = course or group
                   14237:             <number></number>
                   14238:             <roles id="">
                   14239:              <role></role>
                   14240:              <access></access>
                   14241:              <section></section>
                   14242:              <group></group>
                   14243:             </roles>
                   14244: 
                   14245:             <dom></dom>         for scope type = domains
                   14246: 
                   14247:             <users>             for scope type = users
                   14248:              <user>
                   14249:               <uname></uname>
                   14250:               <udom></udom>
                   14251:              </user>
                   14252:             </users>
                   14253:            </scope> 
                   14254:               
                   14255:  Access data is also aggregated for each file in an additional key=value pair:
                   14256:  key -> path to file/file_name\0accesscontrol 
                   14257:  value -> reference to hash
                   14258:           hash contains key = value pairs
                   14259:           where key = uniqueID:scope_end_start
                   14260:                 value = UNIX time record was last updated
                   14261: 
                   14262:           Used to improve speed of look-ups of access controls for each file.  
                   14263:  
                   14264:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14265: 
1.1172.2.13  raeburn  14266: =item *
                   14267: 
1.749     raeburn  14268: modify_access_controls():
                   14269: 
                   14270: Modifies access controls for a portfolio file
                   14271: Args
                   14272: 1. file name
                   14273: 2. reference to hash of required changes,
                   14274: 3. domain
                   14275: 4. username
                   14276:   where domain,username are the domain of the portfolio owner 
                   14277:   (either a user or a course) 
                   14278: 
                   14279: Returns:
                   14280: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14281: 2. result of deletions ('ok' or 'error', with error message).
                   14282: 3. reference to hash of any new or updated access controls.
                   14283: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14284:    key = integer (inbound ID)
1.1172.2.13  raeburn  14285:    value = uniqueID
                   14286: 
                   14287: =item *
                   14288: 
                   14289: get_timebased_id():
                   14290: 
                   14291: Attempts to get a unique timestamp-based suffix for use with items added to a
                   14292: course via the Course Editor (e.g., folders, composite pages,
                   14293: group bulletin boards).
                   14294: 
                   14295: Args: (first three required; six others optional)
                   14296: 
                   14297: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14298:    docssequence, or name of group
                   14299: 
                   14300: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14301:    e.g., num, boardids
                   14302: 
                   14303: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   14304:    file will be named nohist_namespace.db
                   14305: 
                   14306: 4. cdom: domain of course; default is current course domain from %env
                   14307: 
                   14308: 5. cnum: course number; default is current course number from %env
                   14309: 
                   14310: 6. idtype: set to concat if an additional digit is to be appended to the
                   14311:    unix timestamp to form the suffix, if the plain timestamp is already
                   14312:    in use.  Default is to not do this, but simply increment the unix
                   14313:    timestamp by 1 until a unique key is obtained.
                   14314: 
                   14315: 7. who: holder of locking key; defaults to user:domain for user.
                   14316: 
                   14317: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   14318:    retrying); default is 3.
                   14319: 
                   14320: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   14321: 
                   14322: Returns:
                   14323: 
                   14324: 1. suffix obtained (numeric)
                   14325: 
                   14326: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14327: 
                   14328: 3. error: contains (localized) error message if an error occurred.
                   14329: 
1.747     albertel 14330: 
1.608     albertel 14331: =back
                   14332: 
1.243     albertel 14333: =head2 HTTP Helper Routines
                   14334: 
                   14335: =over 4
                   14336: 
1.191     harris41 14337: =item *
                   14338: 
                   14339: escape() : unpack non-word characters into CGI-compatible hex codes
                   14340: 
                   14341: =item *
                   14342: 
                   14343: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14344: 
1.243     albertel 14345: =back
                   14346: 
                   14347: =head1 PRIVATE SUBROUTINES
                   14348: 
                   14349: =head2 Underlying communication routines (Shouldn't call)
                   14350: 
                   14351: =over 4
                   14352: 
                   14353: =item *
                   14354: 
                   14355: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14356: 
                   14357: =item *
                   14358: 
                   14359: reply() : uses subreply to send a message to remote machine, logs all failures
                   14360: 
                   14361: =item *
                   14362: 
                   14363: critical() : passes a critical message to another server; if cannot
                   14364: get through then place message in connection buffer directory and
                   14365: returns con_delayed, if incapable of saving message, returns
                   14366: con_failed
                   14367: 
                   14368: =item *
                   14369: 
                   14370: reconlonc() : tries to reconnect lonc client processes.
                   14371: 
                   14372: =back
                   14373: 
                   14374: =head2 Resource Access Logging
                   14375: 
                   14376: =over 4
                   14377: 
                   14378: =item *
                   14379: 
                   14380: flushcourselogs() : flush (save) buffer logs and access logs
                   14381: 
                   14382: =item *
                   14383: 
                   14384: courselog($what) : save message for course in hash
                   14385: 
                   14386: =item *
                   14387: 
                   14388: courseacclog($what) : save message for course using &courselog().  Perform
                   14389: special processing for specific resource types (problems, exams, quizzes, etc).
                   14390: 
1.191     harris41 14391: =item *
                   14392: 
                   14393: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14394: as a PerlChildExitHandler
1.243     albertel 14395: 
                   14396: =back
                   14397: 
                   14398: =head2 Other
                   14399: 
                   14400: =over 4
                   14401: 
                   14402: =item *
                   14403: 
                   14404: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14405: 
                   14406: =back
                   14407: 
                   14408: =cut
1.877     foxr     14409: 

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