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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.81! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.80 2016/09/17 19:23:42 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.1172.2.79  raeburn    92: use Time::HiRes qw( sleep 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.1172.2.79  raeburn   105: my $max_connection_retries = 20;     # 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.
1.1172.2.79  raeburn   373: 	sleep(0.1);
1.549     foxr      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.1172.2.79  raeburn   391:         sleep(0.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:             }
1.1172.2.79  raeburn   484:             sleep 1;
1.1       albertel  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',
1.1172.2.76  raeburn  2103:                                   'coursecategories','autoenroll'],$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.76  raeburn  2228:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2229:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2230:     }
1.1172.2.23  raeburn  2231:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2232:     return %domdefaults;
                   2233: }
                   2234: 
1.344     www      2235: # --------------------------------------------------- Assign a key to a student
                   2236: 
                   2237: sub assign_access_key {
1.364     www      2238: #
                   2239: # a valid key looks like uname:udom#comments
                   2240: # comments are being appended
                   2241: #
1.498     www      2242:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2243:     $kdom=
1.620     albertel 2244:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2245:     $knum=
1.620     albertel 2246:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2247:     $cdom=
1.620     albertel 2248:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2249:     $cnum=
1.620     albertel 2250:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2251:     $udom=$env{'user.name'} unless (defined($udom));
                   2252:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2253:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2254:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2255:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2256:                                                   # assigned to this person
                   2257:                                                   # - this should not happen,
1.345     www      2258:                                                   # unless something went wrong
                   2259:                                                   # the first time around
                   2260: # ready to assign
1.364     www      2261:         $logentry=$1.'; '.$logentry;
1.496     www      2262:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2263:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2264: # key now belongs to user
1.346     www      2265: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2266:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2267:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2268:                 return 'ok';
                   2269:             } else {
                   2270:                 return 
                   2271:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2272: 	    }
                   2273:         } else {
                   2274:             return 'error: Could not assign key, try again later.';
                   2275:         }
1.364     www      2276:     } elsif (!$existing{$ckey}) {
1.345     www      2277: # the key does not exist
                   2278: 	return 'error: The key does not exist';
                   2279:     } else {
                   2280: # the key is somebody else's
                   2281: 	return 'error: The key is already in use';
                   2282:     }
1.344     www      2283: }
                   2284: 
1.364     www      2285: # ------------------------------------------ put an additional comment on a key
                   2286: 
                   2287: sub comment_access_key {
                   2288: #
                   2289: # a valid key looks like uname:udom#comments
                   2290: # comments are being appended
                   2291: #
                   2292:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2293:     $cdom=
1.620     albertel 2294:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2295:     $cnum=
1.620     albertel 2296:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2297:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2298:     if ($existing{$ckey}) {
                   2299:         $existing{$ckey}.='; '.$logentry;
                   2300: # ready to assign
1.367     www      2301:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2302:                                                  $cdom,$cnum) eq 'ok') {
                   2303: 	    return 'ok';
                   2304:         } else {
                   2305: 	    return 'error: Count not store comment.';
                   2306:         }
                   2307:     } else {
                   2308: # the key does not exist
                   2309: 	return 'error: The key does not exist';
                   2310:     }
                   2311: }
                   2312: 
1.344     www      2313: # ------------------------------------------------------ Generate a set of keys
                   2314: 
                   2315: sub generate_access_keys {
1.364     www      2316:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2317:     $cdom=
1.620     albertel 2318:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2319:     $cnum=
1.620     albertel 2320:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2321:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2322:     unless (($cdom) && ($cnum)) { return 0; }
                   2323:     if ($number>10000) { return 0; }
                   2324:     sleep(2); # make sure don't get same seed twice
                   2325:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2326:     my $total=0;
                   2327:     for (my $i=1;$i<=$number;$i++) {
                   2328:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2329:                   sprintf("%lx",int(100000*rand)).'-'.
                   2330:                   sprintf("%lx",int(100000*rand));
                   2331:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2332:        $newkey=~s/0/h/g; # and also 0 and O
                   2333:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2334:        if ($existing{$newkey}) {
                   2335:            $i--;
                   2336:        } else {
1.364     www      2337: 	  if (&put('accesskeys',
                   2338:               { $newkey => '# generated '.localtime().
1.620     albertel 2339:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2340:                            '; '.$logentry },
                   2341: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2342:               $total++;
                   2343: 	  }
                   2344:        }
                   2345:     }
1.620     albertel 2346:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2347:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2348:     return $total;
                   2349: }
                   2350: 
                   2351: # ------------------------------------------------------- Validate an accesskey
                   2352: 
                   2353: sub validate_access_key {
                   2354:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2355:     $cdom=
1.620     albertel 2356:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2357:     $cnum=
1.620     albertel 2358:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2359:     $udom=$env{'user.domain'} unless (defined($udom));
                   2360:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2361:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2362:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2363: }
                   2364: 
                   2365: # ------------------------------------- Find the section of student in a course
1.652     albertel 2366: sub devalidate_getsection_cache {
                   2367:     my ($udom,$unam,$courseid)=@_;
                   2368:     my $hashid="$udom:$unam:$courseid";
                   2369:     &devalidate_cache_new('getsection',$hashid);
                   2370: }
1.298     matthew  2371: 
1.815     albertel 2372: sub courseid_to_courseurl {
                   2373:     my ($courseid) = @_;
                   2374:     #already url style courseid
                   2375:     return $courseid if ($courseid =~ m{^/});
                   2376: 
                   2377:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2378: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2379: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2380: 	return "/$cdom/$cnum";
                   2381:     }
                   2382: 
                   2383:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2384:     if (exists($courseinfo{'num'})) {
                   2385: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2386:     }
                   2387: 
                   2388:     return undef;
                   2389: }
                   2390: 
1.298     matthew  2391: sub getsection {
                   2392:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2393:     my $cachetime=1800;
1.551     albertel 2394: 
                   2395:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2396:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2397:     if (defined($cached)) { return $result; }
                   2398: 
1.298     matthew  2399:     my %Pending; 
                   2400:     my %Expired;
                   2401:     #
                   2402:     # Each role can either have not started yet (pending), be active, 
                   2403:     #    or have expired.
                   2404:     #
                   2405:     # If there is an active role, we are done.
                   2406:     #
                   2407:     # If there is more than one role which has not started yet, 
                   2408:     #     choose the one which will start sooner
                   2409:     # If there is one role which has not started yet, return it.
                   2410:     #
                   2411:     # If there is more than one expired role, choose the one which ended last.
                   2412:     # If there is a role which has expired, return it.
                   2413:     #
1.815     albertel 2414:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2415:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2416:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2417:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2418:         my $section=$1;
                   2419:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2420:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2421:         my $now=time;
1.548     albertel 2422:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2423:             $Expired{$end}=$section;
                   2424:             next;
                   2425:         }
1.548     albertel 2426:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2427:             $Pending{$start}=$section;
                   2428:             next;
                   2429:         }
1.599     albertel 2430:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2431:     }
                   2432:     #
                   2433:     # Presumedly there will be few matching roles from the above
                   2434:     # loop and the sorting time will be negligible.
                   2435:     if (scalar(keys(%Pending))) {
                   2436:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2437:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2438:     } 
                   2439:     if (scalar(keys(%Expired))) {
                   2440:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2441:         my $time = pop(@sorted);
1.599     albertel 2442:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2443:     }
1.599     albertel 2444:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2445: }
1.70      www      2446: 
1.599     albertel 2447: sub save_cache {
                   2448:     &purge_remembered();
1.722     albertel 2449:     #&Apache::loncommon::validate_page();
1.620     albertel 2450:     undef(%env);
1.780     albertel 2451:     undef($env_loaded);
1.599     albertel 2452: }
1.452     albertel 2453: 
1.599     albertel 2454: my $to_remember=-1;
                   2455: my %remembered;
                   2456: my %accessed;
                   2457: my $kicks=0;
                   2458: my $hits=0;
1.849     albertel 2459: sub make_key {
                   2460:     my ($name,$id) = @_;
1.872     albertel 2461:     if (length($id) > 65 
                   2462: 	&& length(&escape($id)) > 200) {
                   2463: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2464:     }
1.849     albertel 2465:     return &escape($name.':'.$id);
                   2466: }
                   2467: 
1.599     albertel 2468: sub devalidate_cache_new {
                   2469:     my ($name,$id,$debug) = @_;
                   2470:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81! raeburn  2471:     my $remembered_id=$name.':'.$id;
1.849     albertel 2472:     $id=&make_key($name,$id);
1.599     albertel 2473:     $memcache->delete($id);
1.1172.2.81! raeburn  2474:     delete($remembered{$remembered_id});
        !          2475:     delete($accessed{$remembered_id});
1.599     albertel 2476: }
                   2477: 
                   2478: sub is_cached_new {
                   2479:     my ($name,$id,$debug) = @_;
1.1172.2.81! raeburn  2480:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
        !          2481:                                      # keys in %remembered hash, which persists for
        !          2482:                                      # duration of request (no restriction on key length).
        !          2483:     if (exists($remembered{$remembered_id})) {
        !          2484: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
        !          2485: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2486: 	$hits++;
1.1172.2.81! raeburn  2487: 	return ($remembered{$remembered_id},1);
1.599     albertel 2488:     }
1.1172.2.81! raeburn  2489:     $id=&make_key($name,$id);
1.599     albertel 2490:     my $value = $memcache->get($id);
                   2491:     if (!(defined($value))) {
                   2492: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2493: 	return (undef,undef);
1.416     albertel 2494:     }
1.599     albertel 2495:     if ($value eq '__undef__') {
                   2496: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2497: 	$value=undef;
                   2498:     }
1.1172.2.81! raeburn  2499:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2500:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2501:     return ($value,1);
                   2502: }
                   2503: 
                   2504: sub do_cache_new {
                   2505:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81! raeburn  2506:     my $remembered_id=$name.':'.$id;
1.849     albertel 2507:     $id=&make_key($name,$id);
1.599     albertel 2508:     my $setvalue=$value;
                   2509:     if (!defined($setvalue)) {
                   2510: 	$setvalue='__undef__';
                   2511:     }
1.623     albertel 2512:     if (!defined($time) ) {
                   2513: 	$time=600;
                   2514:     }
1.599     albertel 2515:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2516:     my $result = $memcache->set($id,$setvalue,$time);
                   2517:     if (! $result) {
1.872     albertel 2518: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2519: 	$memcache->disconnect_all();
1.872     albertel 2520:     }
1.600     albertel 2521:     # need to make a copy of $value
1.1172.2.81! raeburn  2522:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2523:     return $value;
                   2524: }
                   2525: 
                   2526: sub make_room {
1.1172.2.81! raeburn  2527:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2528: 
1.1172.2.81! raeburn  2529:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2530:                                     : $value;
1.599     albertel 2531:     if ($to_remember<0) { return; }
1.1172.2.81! raeburn  2532:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2533:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2534:     my $to_kick;
                   2535:     my $max_time=0;
                   2536:     foreach my $other (keys(%accessed)) {
                   2537: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2538: 	    $to_kick=$other;
                   2539: 	    $max_time=&tv_interval($accessed{$other});
                   2540: 	}
                   2541:     }
                   2542:     delete($remembered{$to_kick});
                   2543:     delete($accessed{$to_kick});
                   2544:     $kicks++;
                   2545:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2546:     return;
                   2547: }
                   2548: 
1.599     albertel 2549: sub purge_remembered {
1.604     albertel 2550:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2551:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2552:     undef(%remembered);
                   2553:     undef(%accessed);
1.428     albertel 2554: }
1.70      www      2555: # ------------------------------------- Read an entry from a user's environment
                   2556: 
                   2557: sub userenvironment {
                   2558:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2559:     my $items;
                   2560:     foreach my $item (@what) {
                   2561:         $items.=&escape($item).'&';
                   2562:     }
                   2563:     $items=~s/\&$//;
1.70      www      2564:     my %returnhash=();
1.1009    raeburn  2565:     my $uhome = &homeserver($unam,$udom);
                   2566:     unless ($uhome eq 'no_host') {
                   2567:         my @answer=split(/\&/, 
                   2568:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2569:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2570:             return %returnhash;
                   2571:         }
1.1009    raeburn  2572:         my $i;
                   2573:         for ($i=0;$i<=$#what;$i++) {
                   2574: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2575:         }
1.70      www      2576:     }
                   2577:     return %returnhash;
1.1       albertel 2578: }
                   2579: 
1.617     albertel 2580: # ---------------------------------------------------------- Get a studentphoto
                   2581: sub studentphoto {
                   2582:     my ($udom,$unam,$ext) = @_;
                   2583:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2584:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2585:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2586:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2587:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2588:             } else {
                   2589:                 my ($result,$perm_reqd)=
1.707     albertel 2590: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2591:                 if ($result eq 'ok') {
                   2592:                     if (!($perm_reqd eq 'yes')) {
                   2593:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2594:                     }
                   2595:                 }
                   2596:             }
                   2597:         }
                   2598:     } else {
                   2599:         my ($result,$perm_reqd) = 
1.707     albertel 2600: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2601:         if ($result eq 'ok') {
                   2602:             if (!($perm_reqd eq 'yes')) {
                   2603:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2604:             }
                   2605:         }
                   2606:     }
                   2607:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2608: }
                   2609: 
                   2610: sub retrievestudentphoto {
                   2611:     my ($udom,$unam,$ext,$type) = @_;
                   2612:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2613:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2614:     if ($ret eq 'ok') {
                   2615:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2616:         if ($type eq 'thumbnail') {
                   2617:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2618:         }
                   2619:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2620:         return $tokenurl;
                   2621:     } else {
                   2622:         if ($type eq 'thumbnail') {
                   2623:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2624:         } else { 
                   2625:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2626:         }
1.617     albertel 2627:     }
                   2628: }
                   2629: 
1.263     www      2630: # -------------------------------------------------------------------- New chat
                   2631: 
                   2632: sub chatsend {
1.724     raeburn  2633:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2634:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2635:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2636:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2637:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2638: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2639: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2640: }
                   2641: 
                   2642: # ------------------------------------------ Find current version of a resource
                   2643: 
                   2644: sub getversion {
                   2645:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2646:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2647:     return &currentversion(&filelocation('',$fname));
                   2648: }
                   2649: 
                   2650: sub currentversion {
                   2651:     my $fname=shift;
                   2652:     my $author=$fname;
                   2653:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2654:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2655:     my $home=&homeserver($uname,$udom);
1.292     www      2656:     if ($home eq 'no_host') { 
                   2657:         return -1; 
                   2658:     }
1.1112    www      2659:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2660:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2661: 	return -1;
                   2662:     }
1.1112    www      2663:     return $answer;
1.263     www      2664: }
                   2665: 
1.1111    www      2666: #
                   2667: # Return special version number of resource if set by override, empty otherwise
                   2668: #
                   2669: sub usedversion {
                   2670:     my $fname=shift;
                   2671:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2672:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2673:     if ($urlversion) { return $urlversion; }
                   2674:     return '';
                   2675: }
                   2676: 
1.1       albertel 2677: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2678: 
1.1       albertel 2679: sub subscribe {
                   2680:     my $fname=shift;
1.761     raeburn  2681:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2682:     $fname=~s/[\n\r]//g;
1.1       albertel 2683:     my $author=$fname;
                   2684:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2685:     my ($udom,$uname)=split(/\//,$author);
                   2686:     my $home=homeserver($uname,$udom);
1.335     albertel 2687:     if ($home eq 'no_host') {
                   2688:         return 'not_found';
1.1       albertel 2689:     }
                   2690:     my $answer=reply("sub:$fname",$home);
1.64      www      2691:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2692: 	$answer.=' by '.$home;
                   2693:     }
1.1       albertel 2694:     return $answer;
                   2695: }
                   2696:     
1.8       www      2697: # -------------------------------------------------------------- Replicate file
                   2698: 
                   2699: sub repcopy {
                   2700:     my $filename=shift;
1.23      www      2701:     $filename=~s/\/+/\//g;
1.1142    raeburn  2702:     my $londocroot = $perlvar{'lonDocRoot'};
                   2703:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2704:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2705:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2706: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2707: 	return &repcopy_userfile($filename);
                   2708:     }
1.532     albertel 2709:     $filename=~s/[\n\r]//g;
1.8       www      2710:     my $transname="$filename.in.transfer";
1.828     www      2711: # FIXME: this should flock
1.607     raeburn  2712:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2713:     my $remoteurl=subscribe($filename);
1.64      www      2714:     if ($remoteurl =~ /^con_lost by/) {
                   2715: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2716:            return 'unavailable';
1.8       www      2717:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2718: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2719: 	   return 'not_found';
1.64      www      2720:     } elsif ($remoteurl =~ /^rejected by/) {
                   2721: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2722:            return 'forbidden';
1.20      www      2723:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2724:            return 'ok';
1.8       www      2725:     } else {
1.290     www      2726:         my $author=$filename;
                   2727:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2728:         my ($udom,$uname)=split(/\//,$author);
                   2729:         my $home=homeserver($uname,$udom);
                   2730:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2731:            my @parts=split(/\//,$filename);
                   2732:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2733:            if ($path ne "$londocroot/res") {
1.8       www      2734:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2735: 	       return 'bad_request';
1.8       www      2736:            }
                   2737:            my $count;
                   2738:            for ($count=5;$count<$#parts;$count++) {
                   2739:                $path.="/$parts[$count]";
                   2740:                if ((-e $path)!=1) {
                   2741: 		   mkdir($path,0777);
                   2742:                }
                   2743:            }
                   2744:            my $ua=new LWP::UserAgent;
                   2745:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2746:            my $response=$ua->request($request,$transname);
                   2747:            if ($response->is_error()) {
                   2748: 	       unlink($transname);
                   2749:                my $message=$response->status_line;
1.672     albertel 2750:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2751:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2752:                return 'unavailable';
1.8       www      2753:            } else {
1.16      www      2754: 	       if ($remoteurl!~/\.meta$/) {
                   2755:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2756:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2757:                   if ($mresponse->is_error()) {
                   2758: 		      unlink($filename.'.meta');
                   2759:                       &logthis(
1.672     albertel 2760:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2761:                   }
                   2762: 	       }
1.8       www      2763:                rename($transname,$filename);
1.607     raeburn  2764:                return 'ok';
1.8       www      2765:            }
1.290     www      2766:        }
1.8       www      2767:     }
1.330     www      2768: }
                   2769: 
                   2770: # ------------------------------------------------ Get server side include body
                   2771: sub ssi_body {
1.381     albertel 2772:     my ($filelink,%form)=@_;
1.606     matthew  2773:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2774:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2775:     }
1.953     www      2776:     my $output='';
                   2777:     my $response;
1.980     raeburn  2778:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2779:        ($output,$response)=&externalssi($filelink);
1.953     www      2780:     } else {
1.1004    droeschl 2781:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2782:        $filelink .= 'inhibitmenu=yes';
1.953     www      2783:        ($output,$response)=&ssi($filelink,%form);
                   2784:     }
1.778     albertel 2785:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2786:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2787:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2788:     if (wantarray) {
                   2789:         return ($output, $response);
                   2790:     } else {
                   2791:         return $output;
                   2792:     }
1.8       www      2793: }
                   2794: 
1.15      www      2795: # --------------------------------------------------------- Server Side Include
                   2796: 
1.782     albertel 2797: sub absolute_url {
                   2798:     my ($host_name) = @_;
                   2799:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2800:     if ($host_name eq '') {
                   2801: 	$host_name = $ENV{'SERVER_NAME'};
                   2802:     }
                   2803:     return $protocol.$host_name;
                   2804: }
                   2805: 
1.942     foxr     2806: #
                   2807: #   Server side include.
                   2808: # Parameters:
                   2809: #  fn     Possibly encrypted resource name/id.
                   2810: #  form   Hash that describes how the rendering should be done
                   2811: #         and other things.
1.944     foxr     2812: # Returns:
1.950     raeburn  2813: #   Scalar context: The content of the response.
                   2814: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2815: #     
1.15      www      2816: sub ssi {
                   2817: 
1.944     foxr     2818:     my ($fn,%form)=@_;
1.15      www      2819:     my $ua=new LWP::UserAgent;
1.23      www      2820:     my $request;
1.711     albertel 2821: 
                   2822:     $form{'no_update_last_known'}=1;
1.895     albertel 2823:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2824:     if (%form) {
1.782     albertel 2825:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  2826:       $request->content(join('&',map {
                   2827:             my $name = escape($_);
                   2828:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   2829:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   2830:             : &escape($form{$_}) );
                   2831:         } keys(%form)));
1.23      www      2832:     } else {
1.782     albertel 2833:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2834:     }
                   2835: 
1.15      www      2836:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2837:     my $response= $ua->request($request);
1.944     foxr     2838:     if (wantarray) {
1.1172.2.3  raeburn  2839: 	return ($response->content, $response);
1.944     foxr     2840:     } else {
1.1172.2.3  raeburn  2841: 	return $response->content;
1.942     foxr     2842:     }
1.324     www      2843: }
                   2844: 
                   2845: sub externalssi {
                   2846:     my ($url)=@_;
                   2847:     my $ua=new LWP::UserAgent;
                   2848:     my $request=new HTTP::Request('GET',$url);
                   2849:     my $response=$ua->request($request);
1.954     raeburn  2850:     if (wantarray) {
                   2851:         return ($response->content, $response);
                   2852:     } else {
                   2853:         return $response->content;
                   2854:     }
1.15      www      2855: }
1.254     www      2856: 
1.492     albertel 2857: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2858: 
                   2859: sub allowuploaded {
                   2860:     my ($srcurl,$url)=@_;
                   2861:     $url=&clutter(&declutter($url));
                   2862:     my $dir=$url;
                   2863:     $dir=~s/\/[^\/]+$//;
                   2864:     my %httpref=();
                   2865:     my $httpurl=&hreflocation('',$url);
                   2866:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2867:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2868: }
1.477     raeburn  2869: 
1.1172.2.13  raeburn  2870: #
                   2871: # Determine if the current user should be able to edit a particular resource,
                   2872: # when viewing in course context.
                   2873: # (a) When viewing resource used to determine if "Edit" item is included in
                   2874: #     Functions.
                   2875: # (b) When displaying folder contents in course editor, used to determine if
                   2876: #     "Edit" link will be displayed alongside resource.
                   2877: #
                   2878: #  input: six args -- filename (decluttered), course number, course domain,
                   2879: #                   url, symb (if registered) and group (if this is a group
                   2880: #                   item -- e.g., bulletin board, group page etc.).
                   2881: #  output: array of five scalars --
                   2882: #          $cfile -- url for file editing if editable on current server
                   2883: #          $home -- homeserver of resource (i.e., for author if published,
                   2884: #                                           or course if uploaded.).
                   2885: #          $switchserver --  1 if server switch will be needed.
                   2886: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2887: #          $forceview -- 1 if icon/link should be to go to view mode
                   2888: #
                   2889: 
                   2890: sub can_edit_resource {
                   2891:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2892:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2893: #
                   2894: # For aboutme pages user can only edit his/her own.
                   2895: #
                   2896:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2897:         my ($sdom,$sname) = ($1,$2);
                   2898:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2899:             $home = $env{'user.home'};
                   2900:             $cfile = $resurl;
                   2901:             if ($env{'form.forceedit'}) {
                   2902:                 $forceview = 1;
                   2903:             } else {
                   2904:                 $forceedit = 1;
                   2905:             }
                   2906:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2907:         } else {
                   2908:             return;
                   2909:         }
                   2910:     }
                   2911: 
                   2912:     if ($env{'request.course.id'}) {
                   2913:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2914:         if ($group ne '') {
                   2915: # if this is a group homepage or group bulletin board, check group privs
                   2916:             my $allowed = 0;
                   2917:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2918:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2919:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2920:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2921:                     $allowed = 1;
                   2922:                 }
                   2923:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2924:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2925:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2926:                     $allowed = 1;
                   2927:                 }
                   2928:             }
                   2929:             if ($allowed) {
                   2930:                 $home=&homeserver($cnum,$cdom);
                   2931:                 if ($env{'form.forceedit'}) {
                   2932:                     $forceview = 1;
                   2933:                 } else {
                   2934:                     $forceedit = 1;
                   2935:                 }
                   2936:                 $cfile = $resurl;
                   2937:             } else {
                   2938:                 return;
                   2939:             }
                   2940:         } else {
1.1172.2.15  raeburn  2941:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2942:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2943:                     return;
                   2944:                 }
                   2945:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2946: #
                   2947: # No edit allowed where CC has switched to student role.
                   2948: #
                   2949:                 return;
                   2950:             }
                   2951:         }
                   2952:     }
                   2953: 
                   2954:     if ($file ne '') {
                   2955:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2956:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2957:                 $uploaded = 1;
                   2958:                 $incourse = 1;
                   2959:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2960:                     $cfile = &hreflocation('',$file);
                   2961:                     if ($env{'form.forceedit'}) {
                   2962:                         $forceview = 1;
                   2963:                     } else {
                   2964:                         $forceedit = 1;
                   2965:                     }
                   2966:                 }
                   2967:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2968:                 $incourse = 1;
                   2969:                 if ($env{'form.forceedit'}) {
                   2970:                     $forceview = 1;
                   2971:                 } else {
                   2972:                     $forceedit = 1;
                   2973:                 }
                   2974:                 $cfile = $resurl;
                   2975:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2976:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2977:                     $incourse = 1;
                   2978:                     if ($env{'form.forceedit'}) {
                   2979:                         $forceview = 1;
                   2980:                     } else {
                   2981:                         $forceedit = 1;
                   2982:                     }
                   2983:                     $cfile = $resurl;
                   2984:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2985:                     $incourse = 1;
                   2986:                     $cfile = $resurl.'/smpedit';
                   2987:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   2988:                     $incourse = 1;
                   2989:                     if ($env{'form.forceedit'}) {
                   2990:                         $forceview = 1;
                   2991:                     } else {
                   2992:                         $forceedit = 1;
                   2993:                     }
                   2994:                     $cfile = $resurl;
1.1172.2.15  raeburn  2995:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2996:                     $incourse = 1;
                   2997:                     if ($env{'form.forceedit'}) {
                   2998:                         $forceview = 1;
                   2999:                     } else {
                   3000:                         $forceedit = 1;
                   3001:                     }
                   3002:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3003:                 }
                   3004:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3005:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3006:                 if (&is_on_map($template)) {
                   3007:                     $incourse = 1;
                   3008:                     $forceview = 1;
                   3009:                     $cfile = $template;
                   3010:                 }
                   3011:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3012:                     $incourse = 1;
                   3013:                     if ($env{'form.forceedit'}) {
                   3014:                         $forceview = 1;
                   3015:                     } else {
                   3016:                         $forceedit = 1;
                   3017:                     }
                   3018:                     $cfile = $resurl;
                   3019:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3020:                 $incourse = 1;
                   3021:                 $forceview = 1;
                   3022:                 if ($symb) {
                   3023:                     my ($map,$id,$res)=&decode_symb($symb);
                   3024:                     $env{'request.symb'} = $symb;
                   3025:                     $cfile = &clutter($res);
                   3026:                 } else {
                   3027:                     $cfile = $env{'form.suppurl'};
                   3028:                     $cfile =~ s{^http://}{};
                   3029:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3030:                 }
1.1172.2.31  raeburn  3031:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3032:                 if ($env{'form.forceedit'}) {
                   3033:                     $forceview = 1;
                   3034:                 } else {
                   3035:                     $forceedit = 1;
                   3036:                 }
                   3037:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3038:             }
                   3039:         }
                   3040:         if ($uploaded || $incourse) {
                   3041:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3042:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3043:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3044:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3045:             # Check that the user has permission to edit this resource
                   3046:             my $setpriv = 1;
                   3047:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3048:             if (defined($cfudom)) {
                   3049:                 $home=&homeserver($cfuname,$cfudom);
                   3050:                 $cfile=$file;
                   3051:             }
                   3052:         }
                   3053:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3054:             (($home ne '') && ($home ne 'no_host'))) {
                   3055:             my @ids=&current_machine_ids();
                   3056:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3057:                 $switchserver=1;
                   3058:             }
                   3059:         }
                   3060:     }
                   3061:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3062: }
                   3063: 
                   3064: sub is_course_upload {
                   3065:     my ($file,$cnum,$cdom) = @_;
                   3066:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3067:     $uploadpath =~ s{^\/}{};
                   3068:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3069:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3070:         return 1;
                   3071:     }
                   3072:     return;
                   3073: }
                   3074: 
                   3075: sub in_course {
                   3076:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3077:     if ($hideprivileged) {
                   3078:         my $skipuser;
1.1172.2.23  raeburn  3079:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3080:         my @possdoms = ($cdom);
                   3081:         if ($coursehash{'checkforpriv'}) {
                   3082:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3083:         }
                   3084:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3085:             $skipuser = 1;
                   3086:             if ($coursehash{'nothideprivileged'}) {
                   3087:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3088:                     my $user;
                   3089:                     if ($item =~ /:/) {
                   3090:                         $user = $item;
                   3091:                     } else {
                   3092:                         $user = join(':',split(/[\@]/,$item));
                   3093:                     }
                   3094:                     if ($user eq $uname.':'.$udom) {
                   3095:                         undef($skipuser);
                   3096:                         last;
                   3097:                     }
                   3098:                 }
                   3099:             }
                   3100:             if ($skipuser) {
                   3101:                 return 0;
                   3102:             }
                   3103:         }
                   3104:     }
                   3105:     $type ||= 'any';
                   3106:     if (!defined($cdom) || !defined($cnum)) {
                   3107:         my $cid  = $env{'request.course.id'};
                   3108:         $cdom = $env{'course.'.$cid.'.domain'};
                   3109:         $cnum = $env{'course.'.$cid.'.num'};
                   3110:     }
                   3111:     my $typesref;
                   3112:     if (($type eq 'any') || ($type eq 'all')) {
                   3113:         $typesref = ['active','previous','future'];
                   3114:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3115:         $typesref = [$type];
                   3116:     }
                   3117:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3118:                               $typesref,undef,[$cdom]);
                   3119:     my ($tmp) = keys(%roles);
                   3120:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3121:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3122:     if (@course_roles > 0) {
                   3123:         return 1;
                   3124:     }
                   3125:     return 0;
                   3126: }
                   3127: 
1.478     albertel 3128: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3129: # input: action, courseID, current domain, intended
1.637     raeburn  3130: #        path to file, source of file, instruction to parse file for objects,
                   3131: #        ref to hash for embedded objects,
                   3132: #        ref to hash for codebase of java objects.
1.1095    raeburn  3133: #        reference to scalar to accommodate mime type determined
                   3134: #          from File::MMagic if $parser = parse.
1.637     raeburn  3135: #
1.485     raeburn  3136: # output: url to file (if action was uploaddoc), 
                   3137: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3138: #
1.478     albertel 3139: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3140: # course.
1.477     raeburn  3141: #
1.478     albertel 3142: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3143: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3144: #          course's home server.
1.477     raeburn  3145: #
1.478     albertel 3146: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3147: #          be copied from $source (current location) to 
                   3148: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3149: #         and will then be copied to
                   3150: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3151: #         course's home server.
1.485     raeburn  3152: #
1.481     raeburn  3153: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3154: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3155: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3156: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3157: #         in course's home server.
1.637     raeburn  3158: #
1.477     raeburn  3159: 
                   3160: sub process_coursefile {
1.1095    raeburn  3161:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3162:         $mimetype)=@_;
1.477     raeburn  3163:     my $fetchresult;
1.638     albertel 3164:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3165:     if ($action eq 'propagate') {
1.638     albertel 3166:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3167: 			     $home);
1.481     raeburn  3168:     } else {
1.477     raeburn  3169:         my $fpath = '';
                   3170:         my $fname = $file;
1.478     albertel 3171:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3172:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3173:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3174:         if ($action eq 'copy') {
                   3175:             if ($source eq '') {
                   3176:                 $fetchresult = 'no source file';
                   3177:                 return $fetchresult;
                   3178:             } else {
                   3179:                 my $destination = $filepath.'/'.$fname;
                   3180:                 rename($source,$destination);
                   3181:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3182:                                  $home);
1.481     raeburn  3183:             }
                   3184:         } elsif ($action eq 'uploaddoc') {
                   3185:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3186:             print $fh $env{'form.'.$source};
1.481     raeburn  3187:             close($fh);
1.637     raeburn  3188:             if ($parser eq 'parse') {
1.1024    raeburn  3189:                 my $mm = new File::MMagic;
1.1095    raeburn  3190:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3191:                 if ($type eq 'text/html') {
1.1024    raeburn  3192:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3193:                     unless ($parse_result eq 'ok') {
                   3194:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3195:                     }
1.637     raeburn  3196:                 }
1.1095    raeburn  3197:                 if (ref($mimetype)) {
                   3198:                     $$mimetype = $type;
                   3199:                 } 
1.637     raeburn  3200:             }
1.477     raeburn  3201:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3202:                                  $home);
1.481     raeburn  3203:             if ($fetchresult eq 'ok') {
                   3204:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3205:             } else {
                   3206:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3207:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3208:                 return '/adm/notfound.html';
                   3209:             }
1.477     raeburn  3210:         }
                   3211:     }
1.485     raeburn  3212:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3213:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3214:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3215:     }
                   3216:     return $fetchresult;
                   3217: }
                   3218: 
1.637     raeburn  3219: sub build_filepath {
                   3220:     my ($fpath) = @_;
                   3221:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3222:     unless ($fpath eq '') {
                   3223:         my @parts=split('/',$fpath);
                   3224:         foreach my $part (@parts) {
                   3225:             $filepath.= '/'.$part;
                   3226:             if ((-e $filepath)!=1) {
                   3227:                 mkdir($filepath,0777);
                   3228:             }
                   3229:         }
                   3230:     }
                   3231:     return $filepath;
                   3232: }
                   3233: 
                   3234: sub store_edited_file {
1.638     albertel 3235:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3236:     my $file = $primary_url;
                   3237:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3238:     my $fpath = '';
                   3239:     my $fname = $file;
                   3240:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3241:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3242:     my $filepath = &build_filepath($fpath);
                   3243:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3244:     print $fh $content;
                   3245:     close($fh);
1.638     albertel 3246:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3247:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3248: 			  $home);
1.637     raeburn  3249:     if ($$fetchresult eq 'ok') {
                   3250:         return '/uploaded/'.$fpath.'/'.$fname;
                   3251:     } else {
1.638     albertel 3252:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3253: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3254:         return '/adm/notfound.html';
                   3255:     }
                   3256: }
                   3257: 
1.531     albertel 3258: sub clean_filename {
1.831     albertel 3259:     my ($fname,$args)=@_;
1.315     www      3260: # Replace Windows backslashes by forward slashes
1.257     www      3261:     $fname=~s/\\/\//g;
1.831     albertel 3262:     if (!$args->{'keep_path'}) {
                   3263:         # Get rid of everything but the actual filename
                   3264: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3265:     }
1.315     www      3266: # Replace spaces by underscores
                   3267:     $fname=~s/\s+/\_/g;
                   3268: # Replace all other weird characters by nothing
1.831     albertel 3269:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3270: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3271: # numbers
                   3272:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3273:     return $fname;
                   3274: }
1.1051    raeburn  3275: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3276: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3277: # image with the same aspect ratio as the original, but with dimensions which do 
                   3278: # not exceed $resizewidth and $resizeheight.
                   3279:  
1.984     neumanie 3280: sub resizeImage {
1.1051    raeburn  3281:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3282:     my $ima = Image::Magick->new;
                   3283:     my $resized;
                   3284:     if (-e $img_path) {
                   3285:         $ima->Read($img_path);
                   3286:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3287:             my $width = $ima->Get('width');
                   3288:             my $height = $ima->Get('height');
                   3289:             if ($width > $resizewidth) {
                   3290: 	        my $factor = $width/$resizewidth;
                   3291:                 my $newheight = $height/$factor;
                   3292:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3293:                 $resized = 1;
                   3294:             }
                   3295:         }
                   3296:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3297:             my $width = $ima->Get('width');
                   3298:             my $height = $ima->Get('height');
                   3299:             if ($height > $resizeheight) {
                   3300:                 my $factor = $height/$resizeheight;
                   3301:                 my $newwidth = $width/$factor;
                   3302:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3303:                 $resized = 1;
                   3304:             }
                   3305:         }
                   3306:         if ($resized) {
                   3307:             $ima->Write($img_path);
                   3308:         }
                   3309:     }
                   3310:     return;
1.977     amueller 3311: }
                   3312: 
1.608     albertel 3313: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3314: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3315: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3316: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3317: #                                    canceloverwrite, or ''. 
                   3318: #                   if 'coursedoc': upload to the current course
                   3319: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3320: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3321: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3322: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3323: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3324: #        $allfiles - reference to hash for embedded objects
                   3325: #        $codebase - reference to hash for codebase of java objects
                   3326: #        $desuname - username for permanent storage of uploaded file
                   3327: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3328: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3329: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3330: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3331: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3332: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3333: #                    from File::MMagic.
1.858     raeburn  3334: # 
1.686     albertel 3335: # output: url of file in userspace, or error: <message> 
                   3336: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3337: 
1.531     albertel 3338: sub userfileupload {
1.1090    raeburn  3339:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3340:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3341:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3342:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3343:     $fname=&clean_filename($fname);
1.1090    raeburn  3344:     # See if there is anything left
1.257     www      3345:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3346:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3347:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3348:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3349:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3350:         my $now = time;
1.1090    raeburn  3351:         my $filepath;
1.1095    raeburn  3352:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3353:              $filepath = 'tmp/helprequests/'.$now;
                   3354:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3355:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3356:                          '_'.$env{'user.domain'}.'/pending';
                   3357:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3358:             my ($docuname,$docudom);
                   3359:             if ($destudom) {
                   3360:                 $docudom = $destudom;
                   3361:             } else {
                   3362:                 $docudom = $env{'user.domain'};
                   3363:             }
                   3364:             if ($destuname) {
                   3365:                 $docuname = $destuname;
                   3366:             } else {
                   3367:                 $docuname = $env{'user.name'};
                   3368:             }
                   3369:             if (exists($env{'form.group'})) {
                   3370:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3371:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3372:             }
                   3373:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3374:             if ($context eq 'canceloverwrite') {
                   3375:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3376:                 if (-e  $tempfile) {
                   3377:                     my @info = stat($tempfile);
                   3378:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3379:                         unlink($tempfile);
                   3380:                     }
                   3381:                 }
                   3382:                 return;
1.523     raeburn  3383:             }
                   3384:         }
1.1090    raeburn  3385:         # Create the directory if not present
1.741     raeburn  3386:         my @parts=split(/\//,$filepath);
                   3387:         my $fullpath = $perlvar{'lonDaemons'};
                   3388:         for (my $i=0;$i<@parts;$i++) {
                   3389:             $fullpath .= '/'.$parts[$i];
                   3390:             if ((-e $fullpath)!=1) {
                   3391:                 mkdir($fullpath,0777);
                   3392:             }
                   3393:         }
                   3394:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3395:         print $fh $env{'form.'.$formname};
                   3396:         close($fh);
1.1090    raeburn  3397:         if ($context eq 'existingfile') {
                   3398:             my @info = stat($fullpath.'/'.$fname);
                   3399:             return ($fullpath.'/'.$fname,$info[9]);
                   3400:         } else {
                   3401:             return $fullpath.'/'.$fname;
                   3402:         }
1.523     raeburn  3403:     }
1.995     raeburn  3404:     if ($subdir eq 'scantron') {
                   3405:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3406:     } else {
1.995     raeburn  3407:         $fname="$subdir/$fname";
                   3408:     }
1.1090    raeburn  3409:     if ($context eq 'coursedoc') {
1.638     albertel 3410: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3411: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3412:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3413:             return &finishuserfileupload($docuname,$docudom,
                   3414: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3415: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3416:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3417:         } else {
1.1172.2.21  raeburn  3418:             if ($env{'form.folder'}) {
                   3419:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3420:             }
1.638     albertel 3421:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3422: 				       $fname,$formname,$parser,
1.1095    raeburn  3423: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3424:         }
1.719     banghart 3425:     } elsif (defined($destuname)) {
                   3426:         my $docuname=$destuname;
                   3427:         my $docudom=$destudom;
1.860     raeburn  3428: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3429: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3430:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3431:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3432:     } else {
1.638     albertel 3433:         my $docuname=$env{'user.name'};
                   3434:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3435:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3436:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3437:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3438:         }
1.860     raeburn  3439: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3440: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3441:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3442:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3443:     }
1.271     www      3444: }
                   3445: 
                   3446: sub finishuserfileupload {
1.860     raeburn  3447:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3448:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3449:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3450:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3451:   
1.860     raeburn  3452:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3453:     $file=$fname;
                   3454:     if ($fname=~m|/|) {
                   3455:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3456: 	$path.=$fnamepath.'/';
                   3457:     }
1.259     www      3458:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3459:     my $count;
                   3460:     for ($count=4;$count<=$#parts;$count++) {
                   3461:         $filepath.="/$parts[$count]";
                   3462:         if ((-e $filepath)!=1) {
                   3463: 	    mkdir($filepath,0777);
                   3464:         }
                   3465:     }
1.984     neumanie 3466: 
1.258     www      3467: # Save the file
                   3468:     {
1.701     albertel 3469: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3470: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3471: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3472: 	    return '/adm/notfound.html';
                   3473: 	}
1.1090    raeburn  3474:         if ($context eq 'overwrite') {
1.1117    foxr     3475:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3476:             my $target = $filepath.'/'.$file;
                   3477:             if (-e $source) {
                   3478:                 my @info = stat($source);
                   3479:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3480:                     unless (&File::Copy::move($source,$target)) {
                   3481:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3482:                         return "Moving from $source failed";
                   3483:                     }
                   3484:                 } else {
                   3485:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3486:                 }
                   3487:             } else {
                   3488:                 return "Temporary file: $source missing";
                   3489:             }
                   3490:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3491: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3492: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3493: 	    return '/adm/notfound.html';
                   3494: 	}
1.570     albertel 3495: 	close(FH);
1.1051    raeburn  3496:         if ($resizewidth && $resizeheight) {
                   3497:             my $mm = new File::MMagic;
                   3498:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3499:             if ($mime_type =~ m{^image/}) {
                   3500: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3501:             }  
1.977     amueller 3502: 	}
1.258     www      3503:     }
1.1152    raeburn  3504:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3505:         if (ref($mimetype)) {
                   3506:             if ($$mimetype eq '') {
                   3507:                 my $mm = new File::MMagic;
                   3508:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3509:                 $$mimetype = $type;
                   3510:             }
                   3511:         }
                   3512:     }
1.637     raeburn  3513:     if ($parser eq 'parse') {
1.1152    raeburn  3514:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3515:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3516:                                                        $allfiles,$codebase);
                   3517:             unless ($parse_result eq 'ok') {
                   3518:                 &logthis('Failed to parse '.$filepath.$file.
                   3519: 	   	         ' for embedded media: '.$parse_result); 
                   3520:             }
1.637     raeburn  3521:         }
                   3522:     }
1.860     raeburn  3523:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3524:         my $input = $filepath.'/'.$file;
                   3525:         my $output = $filepath.'/'.'tn-'.$file;
                   3526:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3527:         system("convert -sample $thumbsize $input $output");
                   3528:         if (-e $filepath.'/'.'tn-'.$file) {
                   3529:             $fetchthumb  = 1; 
                   3530:         }
                   3531:     }
1.858     raeburn  3532:  
1.259     www      3533: # Notify homeserver to grep it
                   3534: #
1.984     neumanie 3535:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3536:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3537:     if ($fetchresult eq 'ok') {
1.860     raeburn  3538:         if ($fetchthumb) {
                   3539:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3540:             if ($thumbresult ne 'ok') {
                   3541:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3542:                          $docuhome.': '.$thumbresult);
                   3543:             }
                   3544:         }
1.259     www      3545: #
1.258     www      3546: # Return the URL to it
1.494     albertel 3547:         return '/uploaded/'.$path.$file;
1.263     www      3548:     } else {
1.494     albertel 3549:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3550: 		 ': '.$fetchresult);
1.263     www      3551:         return '/adm/notfound.html';
1.858     raeburn  3552:     }
1.493     albertel 3553: }
                   3554: 
1.637     raeburn  3555: sub extract_embedded_items {
1.961     raeburn  3556:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3557:     my @state = ();
1.1164    raeburn  3558:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3559:     my %javafiles = (
                   3560:                       codebase => '',
                   3561:                       code => '',
                   3562:                       archive => ''
                   3563:                     );
                   3564:     my %mediafiles = (
                   3565:                       src => '',
                   3566:                       movie => '',
                   3567:                      );
1.648     raeburn  3568:     my $p;
                   3569:     if ($content) {
                   3570:         $p = HTML::LCParser->new($content);
                   3571:     } else {
1.961     raeburn  3572:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3573:     }
1.641     albertel 3574:     while (my $t=$p->get_token()) {
1.640     albertel 3575: 	if ($t->[0] eq 'S') {
                   3576: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3577: 	    push(@state, $tagname);
1.648     raeburn  3578:             if (lc($tagname) eq 'allow') {
                   3579:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3580:             }
1.640     albertel 3581: 	    if (lc($tagname) eq 'img') {
                   3582: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3583: 	    }
1.886     albertel 3584: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3585:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3586: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3587:                 }
1.886     albertel 3588: 	    }
1.645     raeburn  3589:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3590:                 my $src;
1.645     raeburn  3591:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3592:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3593:                 } else {
1.1164    raeburn  3594:                     if ($attr->{'src'} ne '') {
                   3595:                         $src = $attr->{'src'};
                   3596:                         &add_filetype($allfiles,$src,'src');
                   3597:                     }
                   3598:                 }
                   3599:                 my $text = $p->get_trimmed_text();
                   3600:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3601:                     my @swfargs = split(/,/,$1);
                   3602:                     foreach my $item (@swfargs) {
                   3603:                         $item =~ s/["']//g;
                   3604:                         $item =~ s/^\s+//;
                   3605:                         $item =~ s/\s+$//;
                   3606:                     }
                   3607:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3608:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3609:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3610:                         } else {
                   3611:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3612:                         }
                   3613:                     }
1.645     raeburn  3614:                 }
                   3615:             }
                   3616:             if (lc($tagname) eq 'link') {
                   3617:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3618:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3619:                 }
                   3620:             }
1.640     albertel 3621: 	    if (lc($tagname) eq 'object' ||
                   3622: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3623: 		foreach my $item (keys(%javafiles)) {
                   3624: 		    $javafiles{$item} = '';
                   3625: 		}
1.1164    raeburn  3626:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3627:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3628:                 }
1.640     albertel 3629: 	    }
                   3630: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3631: 		my $name = lc($attr->{'name'});
                   3632: 		foreach my $item (keys(%javafiles)) {
                   3633: 		    if ($name eq $item) {
                   3634: 			$javafiles{$item} = $attr->{'value'};
                   3635: 			last;
                   3636: 		    }
                   3637: 		}
1.1164    raeburn  3638:                 my $pathfrom;
1.640     albertel 3639: 		foreach my $item (keys(%mediafiles)) {
                   3640: 		    if ($name eq $item) {
1.1164    raeburn  3641:                         $pathfrom = $attr->{'value'};
                   3642:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3643: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3644: 			last;
                   3645: 		    }
                   3646: 		}
1.1164    raeburn  3647:                 if ($name eq 'flashvars') {
                   3648:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3649:                 }
                   3650:                 if ($pathfrom ne '') {
                   3651:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3652:                                          $pathfrom);
                   3653:                 }
1.640     albertel 3654: 	    }
                   3655: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3656: 		foreach my $item (keys(%javafiles)) {
                   3657: 		    if ($attr->{$item}) {
                   3658: 			$javafiles{$item} = $attr->{$item};
                   3659: 			last;
                   3660: 		    }
                   3661: 		}
                   3662: 		foreach my $item (keys(%mediafiles)) {
                   3663: 		    if ($attr->{$item}) {
                   3664: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3665: 			last;
                   3666: 		    }
                   3667: 		}
1.1164    raeburn  3668:                 if (lc($tagname) eq 'embed') {
                   3669:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3670:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3671:                                              $attr->{'src'});
                   3672:                     }
                   3673:                 }
1.640     albertel 3674: 	    }
1.1172.2.35  raeburn  3675:             if (lc($tagname) eq 'iframe') {
                   3676:                 my $src = $attr->{'src'} ;
                   3677:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3678:                     &add_filetype($allfiles,$src,'src');
                   3679:                 } elsif ($src =~ m{^/}) {
                   3680:                     if ($env{'request.course.id'}) {
                   3681:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3682:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3683:                         my $url = &hreflocation('',$fullpath);
                   3684:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3685:                             my $relpath = $1;
                   3686:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3687:                                 &add_filetype($allfiles,$1,'src');
                   3688:                             }
                   3689:                         }
                   3690:                     }
                   3691:                 }
                   3692:             }
1.1164    raeburn  3693:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3694:                 pop(@state);
1.1164    raeburn  3695:             }
1.640     albertel 3696: 	} elsif ($t->[0] eq 'E') {
                   3697: 	    my ($tagname) = ($t->[1]);
                   3698: 	    if ($javafiles{'codebase'} ne '') {
                   3699: 		$javafiles{'codebase'} .= '/';
                   3700: 	    }  
                   3701: 	    if (lc($tagname) eq 'applet' ||
                   3702: 		lc($tagname) eq 'object' ||
                   3703: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3704: 		) {
                   3705: 		foreach my $item (keys(%javafiles)) {
                   3706: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3707: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3708: 			&add_filetype($allfiles,$file,$item);
                   3709: 		    }
                   3710: 		}
                   3711: 	    } 
                   3712: 	    pop @state;
                   3713: 	}
                   3714:     }
1.1164    raeburn  3715:     foreach my $id (sort(keys(%flashvars))) {
                   3716:         if ($shockwave{$id} ne '') {
                   3717:             my @pairs = split(/\&/,$flashvars{$id});
                   3718:             foreach my $pair (@pairs) {
                   3719:                 my ($key,$value) = split(/\=/,$pair);
                   3720:                 if ($key eq 'thumb') {
                   3721:                     &add_filetype($allfiles,$value,$key);
                   3722:                 } elsif ($key eq 'content') {
                   3723:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3724:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3725:                     if ($ext ne '') {
                   3726:                         &add_filetype($allfiles,$path.$value,$ext);
                   3727:                     }
                   3728:                 }
                   3729:             }
                   3730:         }
                   3731:     }
1.637     raeburn  3732:     return 'ok';
                   3733: }
                   3734: 
1.639     albertel 3735: sub add_filetype {
                   3736:     my ($allfiles,$file,$type)=@_;
                   3737:     if (exists($allfiles->{$file})) {
                   3738: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3739: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3740: 	}
                   3741:     } else {
                   3742: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3743:     }
                   3744: }
                   3745: 
1.1164    raeburn  3746: sub embedded_dependency {
                   3747:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3748:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3749:         if (($identifier ne '') &&
                   3750:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3751:             ($pathfrom ne '')) {
                   3752:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3753:             foreach my $dep (@{$related->{$identifier}}) {
                   3754:                 &add_filetype($allfiles,$path.$dep,'object');
                   3755:             }
                   3756:         }
                   3757:     }
                   3758:     return;
                   3759: }
                   3760: 
1.493     albertel 3761: sub removeuploadedurl {
1.984     neumanie 3762:     my ($url)=@_;	
                   3763:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3764:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3765: }
                   3766: 
                   3767: sub removeuserfile {
                   3768:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3769:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3770:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3771:     if ($result eq 'ok') {	
1.798     raeburn  3772:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3773:             my $metafile = $fname.'.meta';
                   3774:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3775: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3776:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3777:             my $sqlresult = 
1.823     albertel 3778:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3779:                                         'portfolio_metadata',$group,
                   3780:                                         'delete');
1.798     raeburn  3781:         }
                   3782:     }
                   3783:     return $result;
1.257     www      3784: }
1.15      www      3785: 
1.530     albertel 3786: sub mkdiruserfile {
                   3787:     my ($docuname,$docudom,$dir)=@_;
                   3788:     my $home=&homeserver($docuname,$docudom);
                   3789:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3790: }
                   3791: 
1.531     albertel 3792: sub renameuserfile {
                   3793:     my ($docuname,$docudom,$old,$new)=@_;
                   3794:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3795:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3796:                         &escape("$old").':'.&escape("$new"),$home);
                   3797:     if ($result eq 'ok') {
                   3798:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3799:             my $oldmeta = $old.'.meta';
                   3800:             my $newmeta = $new.'.meta';
                   3801:             my $metaresult = 
                   3802:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3803: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3804:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3805:             my $sqlresult = 
1.823     albertel 3806:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3807:                                         'portfolio_metadata',$group,
                   3808:                                         'delete');
1.798     raeburn  3809:         }
                   3810:     }
                   3811:     return $result;
1.531     albertel 3812: }
                   3813: 
1.14      www      3814: # ------------------------------------------------------------------------- Log
                   3815: 
                   3816: sub log {
                   3817:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3818:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3819: }
                   3820: 
                   3821: # ------------------------------------------------------------------ Course Log
1.352     www      3822: #
                   3823: # This routine flushes several buffers of non-mission-critical nature
                   3824: #
1.157     www      3825: 
                   3826: sub flushcourselogs {
1.352     www      3827:     &logthis('Flushing log buffers');
                   3828: #
                   3829: # course logs
                   3830: # This is a log of all transactions in a course, which can be used
                   3831: # for data mining purposes
                   3832: #
                   3833: # It also collects the courseid database, which lists last transaction
                   3834: # times and course titles for all courseids
                   3835: #
                   3836:     my %courseidbuffer=();
1.921     raeburn  3837:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3838:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3839: 		          &escape($courselogs{$crsid}),
                   3840: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3841: 	    delete $courselogs{$crsid};
                   3842:         } else {
                   3843:             &logthis('Failed to flush log buffer for '.$crsid);
                   3844:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3845:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3846:                         " exceeded maximum size, deleting.</font>");
                   3847:                delete $courselogs{$crsid};
                   3848:             }
1.352     www      3849:         }
1.920     raeburn  3850:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3851:             'description' => $coursedescrbuf{$crsid},
                   3852:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3853:             'type'        => $coursetypebuf{$crsid},
                   3854:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3855:         };
1.191     harris41 3856:     }
1.352     www      3857: #
                   3858: # Write course id database (reverse lookup) to homeserver of courses 
                   3859: # Is used in pickcourse
                   3860: #
1.840     albertel 3861:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3862:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3863:                                     $courseidbuffer{$crs_home},
                   3864:                                     $crs_home,'timeonly');
1.352     www      3865:     }
                   3866: #
                   3867: # File accesses
                   3868: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3869: #
1.449     matthew  3870:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3871:         if ($entry =~ /___count$/) {
                   3872:             my ($dom,$name);
1.807     albertel 3873:             ($dom,$name,undef)=
1.811     albertel 3874: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3875:             if (! defined($dom) || $dom eq '' || 
                   3876:                 ! defined($name) || $name eq '') {
1.620     albertel 3877:                 my $cid = $env{'request.course.id'};
                   3878:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3879:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3880:             }
1.450     matthew  3881:             my $value = $accesshash{$entry};
                   3882:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3883:             my %temphash=($url => $value);
1.449     matthew  3884:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3885:             if ($result eq 'ok') {
                   3886:                 delete $accesshash{$entry};
                   3887:             }
                   3888:         } else {
1.811     albertel 3889:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3890:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3891:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3892:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3893:                 delete $accesshash{$entry};
                   3894:             }
1.185     www      3895:         }
1.191     harris41 3896:     }
1.352     www      3897: #
                   3898: # Roles
                   3899: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3900: #
1.800     albertel 3901:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3902:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3903: 	    split(/\:/,$entry);
                   3904:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3905:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3906:                 $rudom,$runame) eq 'ok') {
                   3907: 	    delete $userrolehash{$entry};
                   3908:         }
                   3909:     }
1.662     raeburn  3910: #
                   3911: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3912: #
                   3913:     my %domrolebuffer = ();
1.1000    raeburn  3914:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3915:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3916:         if ($domrolebuffer{$rudom}) {
                   3917:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3918:                       '='.&escape($domainrolehash{$entry});
                   3919:         } else {
                   3920:             $domrolebuffer{$rudom}.=&escape($entry).
                   3921:                       '='.&escape($domainrolehash{$entry});
                   3922:         }
                   3923:         delete $domainrolehash{$entry};
                   3924:     }
                   3925:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3926: 	my %servers = &get_servers($dom,'library');
                   3927: 	foreach my $tryserver (keys(%servers)) {
                   3928: 	    unless (&reply('domroleput:'.$dom.':'.
                   3929: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3930: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3931: 	    }
1.662     raeburn  3932:         }
                   3933:     }
1.186     www      3934:     $dumpcount++;
1.157     www      3935: }
                   3936: 
                   3937: sub courselog {
                   3938:     my $what=shift;
1.158     www      3939:     $what=time.':'.$what;
1.620     albertel 3940:     unless ($env{'request.course.id'}) { return ''; }
                   3941:     $coursedombuf{$env{'request.course.id'}}=
                   3942:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3943:     $coursenumbuf{$env{'request.course.id'}}=
                   3944:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3945:     $coursehombuf{$env{'request.course.id'}}=
                   3946:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3947:     $coursedescrbuf{$env{'request.course.id'}}=
                   3948:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3949:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3950:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3951:     $courseownerbuf{$env{'request.course.id'}}=
                   3952:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3953:     $coursetypebuf{$env{'request.course.id'}}=
                   3954:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3955:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3956: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3957:     } else {
1.620     albertel 3958: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3959:     }
1.620     albertel 3960:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3961: 	&flushcourselogs();
                   3962:     }
1.158     www      3963: }
                   3964: 
                   3965: sub courseacclog {
                   3966:     my $fnsymb=shift;
1.620     albertel 3967:     unless ($env{'request.course.id'}) { return ''; }
                   3968:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3969:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3970:         $what.=':POST';
1.583     matthew  3971:         # FIXME: Probably ought to escape things....
1.800     albertel 3972: 	foreach my $key (keys(%env)) {
                   3973:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3974:                 my $formitem = $1;
                   3975:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3976:                     $what.=':'.$formitem.'='.$env{$key};
                   3977:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3978:                     $what.=':'.$formitem.'='.$env{$key};
                   3979:                 }
1.158     www      3980:             }
1.191     harris41 3981:         }
1.583     matthew  3982:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3983:         # FIXME: We should not be depending on a form parameter that someone
                   3984:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3985:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3986:             $what.= ':POST';
                   3987:             # FIXME: Probably ought to escape things....
                   3988:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3989:                                  'crsdiscuss') {
1.620     albertel 3990:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3991:             }
                   3992:         }
1.158     www      3993:     }
                   3994:     &courselog($what);
1.149     www      3995: }
                   3996: 
1.185     www      3997: sub countacc {
                   3998:     my $url=&declutter(shift);
1.458     matthew  3999:     return if (! defined($url) || $url eq '');
1.620     albertel 4000:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4001: #
                   4002: # Mark that this url was used in this course
                   4003: #
1.620     albertel 4004:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4005: #
                   4006: # Increase the access count for this resource in this child process
                   4007: #
1.281     www      4008:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4009:     $accesshash{$key}++;
1.185     www      4010: }
1.349     www      4011: 
1.361     www      4012: sub linklog {
                   4013:     my ($from,$to)=@_;
                   4014:     $from=&declutter($from);
                   4015:     $to=&declutter($to);
                   4016:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4017:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4018: }
1.1160    www      4019: 
                   4020: sub statslog {
                   4021:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4022:     if ($users<2) { return; }
                   4023:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4024:             'course'       => $env{'request.course.id'},
                   4025:             'sections'     => '"all"',
                   4026:             'num_students' => $users,
                   4027:             'part'         => $part,
                   4028:             'symb'         => $symb,
                   4029:             'mean_tries'   => $av_attempts,
                   4030:             'deg_of_diff'  => $degdiff});
                   4031:     foreach my $key (keys(%dynstore)) {
                   4032:         $accesshash{$key}=$dynstore{$key};
                   4033:     }
                   4034: }
1.361     www      4035:   
1.349     www      4036: sub userrolelog {
                   4037:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4038:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4039:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4040:        $userrolehash
                   4041:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4042:                     =$tend.':'.$tstart;
1.662     raeburn  4043:     }
1.1169    droeschl 4044:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4045:        $userrolehash
                   4046:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4047:                     =$tend.':'.$tstart;
                   4048:     }
1.1169    droeschl 4049:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  4050:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4051:        $domainrolehash
                   4052:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4053:                     = $tend.':'.$tstart;
                   4054:     }
1.351     www      4055: }
                   4056: 
1.957     raeburn  4057: sub courserolelog {
                   4058:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4059:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4060:         my $cdom = $1;
                   4061:         my $cnum = $2;
                   4062:         my $sec = $3;
                   4063:         my $namespace = 'rolelog';
                   4064:         my %storehash = (
                   4065:                            role    => $trole,
                   4066:                            start   => $tstart,
                   4067:                            end     => $tend,
                   4068:                            selfenroll => $selfenroll,
                   4069:                            context    => $context,
                   4070:                         );
                   4071:         if ($trole eq 'gr') {
                   4072:             $namespace = 'groupslog';
                   4073:             $storehash{'group'} = $sec;
                   4074:         } else {
                   4075:             $storehash{'section'} = $sec;
                   4076:         }
                   4077:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4078:                    $domain,$cnum,$cdom);
                   4079:         if (($trole ne 'st') || ($sec ne '')) {
                   4080:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4081:         }
                   4082:     }
                   4083:     return;
                   4084: }
                   4085: 
1.1172.2.9  raeburn  4086: sub domainrolelog {
                   4087:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4088:     if ($area =~ m{^/($match_domain)/$}) {
                   4089:         my $cdom = $1;
                   4090:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4091:         my $namespace = 'rolelog';
                   4092:         my %storehash = (
                   4093:                            role    => $trole,
                   4094:                            start   => $tstart,
                   4095:                            end     => $tend,
                   4096:                            context => $context,
                   4097:                         );
                   4098:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4099:                    $domain,$domconfiguser,$cdom);
                   4100:     }
                   4101:     return;
                   4102: 
                   4103: }
                   4104: 
                   4105: sub coauthorrolelog {
                   4106:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4107:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4108:         my $audom = $1;
                   4109:         my $auname = $2;
                   4110:         my $namespace = 'rolelog';
                   4111:         my %storehash = (
                   4112:                            role    => $trole,
                   4113:                            start   => $tstart,
                   4114:                            end     => $tend,
                   4115:                            context => $context,
                   4116:                         );
                   4117:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4118:                    $domain,$auname,$audom);
                   4119:     }
                   4120:     return;
                   4121: }
                   4122: 
1.351     www      4123: sub get_course_adv_roles {
1.948     raeburn  4124:     my ($cid,$codes) = @_;
1.620     albertel 4125:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4126:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4127:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4128:     my %nothide=();
1.800     albertel 4129:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4130:         if ($user !~ /:/) {
                   4131: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4132:         } else {
                   4133:             $nothide{$user}=1;
                   4134:         }
1.470     www      4135:     }
1.1172.2.23  raeburn  4136:     my @possdoms = ($coursehash{'domain'});
                   4137:     if ($coursehash{'checkforpriv'}) {
                   4138:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4139:     }
1.351     www      4140:     my %returnhash=();
                   4141:     my %dumphash=
                   4142:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4143:     my $now=time;
1.997     raeburn  4144:     my %privileged;
1.1000    raeburn  4145:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4146: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4147:         if (($tstart) && ($tstart<0)) { next; }
                   4148:         if (($tend) && ($tend<$now)) { next; }
                   4149:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4150:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4151: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4152:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4153:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4154: 	if ($role eq 'cr') { next; }
1.948     raeburn  4155:         if ($codes) {
                   4156:             if ($section) { $role .= ':'.$section; }
                   4157:             if ($returnhash{$role}) {
                   4158:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4159:             } else {
                   4160:                 $returnhash{$role}=$username.':'.$domain;
                   4161:             }
1.351     www      4162:         } else {
1.988     raeburn  4163:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4164:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4165:             if ($returnhash{$key}) {
                   4166: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4167:             } else {
                   4168:                 $returnhash{$key}=$username.':'.$domain;
                   4169:             }
1.351     www      4170:         }
1.948     raeburn  4171:     }
1.400     www      4172:     return %returnhash;
                   4173: }
                   4174: 
                   4175: sub get_my_roles {
1.937     raeburn  4176:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4177:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4178:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4179:     my (%dumphash,%nothide);
1.1086    raeburn  4180:     if ($context eq 'userroles') {
1.1166    raeburn  4181:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4182:     } else {
1.1172.2.23  raeburn  4183:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4184:         if ($hidepriv) {
                   4185:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4186:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4187:                 if ($user !~ /:/) {
                   4188:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4189:                 } else {
                   4190:                     $nothide{$user} = 1;
                   4191:                 }
                   4192:             }
                   4193:         }
1.858     raeburn  4194:     }
1.400     www      4195:     my %returnhash=();
                   4196:     my $now=time;
1.999     raeburn  4197:     my %privileged;
1.800     albertel 4198:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4199:         my ($role,$tend,$tstart);
                   4200:         if ($context eq 'userroles') {
1.1149    raeburn  4201:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4202: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4203:         } else {
                   4204:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4205:         }
1.400     www      4206:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4207:         my $status = 'active';
1.939     raeburn  4208:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4209:             $status = 'previous';
                   4210:         } 
                   4211:         if (($tstart) && ($now<$tstart)) {
                   4212:             $status = 'future';
                   4213:         }
                   4214:         if (ref($types) eq 'ARRAY') {
                   4215:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4216:                 next;
                   4217:             } 
                   4218:         } else {
                   4219:             if ($status ne 'active') {
                   4220:                 next;
                   4221:             }
                   4222:         }
1.867     raeburn  4223:         my ($rolecode,$username,$domain,$section,$area);
                   4224:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4225:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4226:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4227:         } else {
                   4228:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4229:         }
1.832     raeburn  4230:         if (ref($roledoms) eq 'ARRAY') {
                   4231:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4232:                 next;
                   4233:             }
                   4234:         }
                   4235:         if (ref($roles) eq 'ARRAY') {
                   4236:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4237:                 if ($role =~ /^cr\//) {
                   4238:                     if (!grep(/^cr$/,@{$roles})) {
                   4239:                         next;
                   4240:                     }
1.1104    raeburn  4241:                 } elsif ($role =~ /^gr\//) {
                   4242:                     if (!grep(/^gr$/,@{$roles})) {
                   4243:                         next;
                   4244:                     }
1.922     raeburn  4245:                 } else {
                   4246:                     next;
                   4247:                 }
1.832     raeburn  4248:             }
1.867     raeburn  4249:         }
1.937     raeburn  4250:         if ($hidepriv) {
1.1172.2.23  raeburn  4251:             my @privroles = ('dc','su');
1.999     raeburn  4252:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4253:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4254:             } else {
1.1172.2.23  raeburn  4255:                 my $possdoms = [$domain];
                   4256:                 if (ref($roledoms) eq 'ARRAY') {
                   4257:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4258:                 }
1.1172.2.23  raeburn  4259:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4260:                     if (!$nothide{$username.':'.$domain}) {
                   4261:                         next;
                   4262:                     }
                   4263:                 }
1.937     raeburn  4264:             }
                   4265:         }
1.933     raeburn  4266:         if ($withsec) {
                   4267:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4268:                 $tstart.':'.$tend;
                   4269:         } else {
                   4270:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4271:         }
1.832     raeburn  4272:     }
1.373     www      4273:     return %returnhash;
1.399     www      4274: }
                   4275: 
                   4276: # ----------------------------------------------------- Frontpage Announcements
                   4277: #
                   4278: #
                   4279: 
                   4280: sub postannounce {
                   4281:     my ($server,$text)=@_;
1.844     albertel 4282:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4283:     unless ($text=~/\w/) { $text=''; }
                   4284:     return &reply('setannounce:'.&escape($text),$server);
                   4285: }
                   4286: 
                   4287: sub getannounce {
1.448     albertel 4288: 
                   4289:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4290: 	my $announcement='';
1.800     albertel 4291: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4292: 	close($fh);
1.399     www      4293: 	if ($announcement=~/\w/) { 
                   4294: 	    return 
                   4295:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4296:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4297: 	} else {
                   4298: 	    return '';
                   4299: 	}
                   4300:     } else {
                   4301: 	return '';
                   4302:     }
1.351     www      4303: }
1.353     www      4304: 
                   4305: # ---------------------------------------------------------- Course ID routines
                   4306: # Deal with domain's nohist_courseid.db files
                   4307: #
                   4308: 
                   4309: sub courseidput {
1.921     raeburn  4310:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4311:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4312:     my $outcome;
                   4313:     if ($caller eq 'timeonly') {
                   4314:         my $cids = '';
                   4315:         foreach my $item (keys(%$storehash)) {
                   4316:             $cids.=&escape($item).'&';
                   4317:         }
                   4318:         $cids=~s/\&$//;
                   4319:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4320:                           $coursehome);       
                   4321:     } else {
                   4322:         my $items = '';
                   4323:         foreach my $item (keys(%$storehash)) {
                   4324:             $items.= &escape($item).'='.
                   4325:                      &freeze_escape($$storehash{$item}).'&';
                   4326:         }
                   4327:         $items=~s/\&$//;
                   4328:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4329:                           $coursehome);
1.918     raeburn  4330:     }
                   4331:     if ($outcome eq 'unknown_cmd') {
                   4332:         my $what;
                   4333:         foreach my $cid (keys(%$storehash)) {
                   4334:             $what .= &escape($cid).'=';
1.921     raeburn  4335:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4336:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4337:             }
                   4338:             $what =~ s/\:$/&/;
                   4339:         }
                   4340:         $what =~ s/\&$//;  
                   4341:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4342:     } else {
                   4343:         return $outcome;
                   4344:     }
1.353     www      4345: }
                   4346: 
                   4347: sub courseiddump {
1.921     raeburn  4348:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4349:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4350:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4351:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  4352:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4353:     my $as_hash = 1;
                   4354:     my %returnhash;
                   4355:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4356:     my %libserv = &all_library();
                   4357:     foreach my $tryserver (keys(%libserv)) {
                   4358:         if ( (  $hostidflag == 1 
                   4359: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4360: 	     || (!defined($hostidflag)) ) {
                   4361: 
1.918     raeburn  4362: 	    if (($domfilter eq '') ||
                   4363: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4364:                 my $rep;
                   4365:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4366:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4367:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4368:                                 &escape($descfilter), &escape($instcodefilter),
                   4369:                                 &escape($ownerfilter), &escape($coursefilter),
                   4370:                                 &escape($typefilter), &escape($regexp_ok),
                   4371:                                 $as_hash, &escape($selfenrollonly),
                   4372:                                 &escape($catfilter), $showhidden, $caller,
                   4373:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4374:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  4375:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4376:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  4377:                 } else {
                   4378:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4379:                              $sincefilter.':'.&escape($descfilter).':'.
                   4380:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4381:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4382:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4383:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4384:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4385:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4386:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  4387:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4388:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  4389:                 }
                   4390: 
1.918     raeburn  4391:                 my @pairs=split(/\&/,$rep);
                   4392:                 foreach my $item (@pairs) {
                   4393:                     my ($key,$value)=split(/\=/,$item,2);
                   4394:                     $key = &unescape($key);
                   4395:                     next if ($key =~ /^error: 2 /);
                   4396:                     my $result = &thaw_unescape($value);
                   4397:                     if (ref($result) eq 'HASH') {
                   4398:                         $returnhash{$key}=$result;
                   4399:                     } else {
1.921     raeburn  4400:                         my @responses = split(/:/,$value);
                   4401:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4402:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4403:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4404:                         }
1.1008    raeburn  4405:                     }
1.353     www      4406:                 }
                   4407:             }
                   4408:         }
                   4409:     }
                   4410:     return %returnhash;
                   4411: }
                   4412: 
1.1055    raeburn  4413: sub courselastaccess {
                   4414:     my ($cdom,$cnum,$hostidref) = @_;
                   4415:     my %returnhash;
                   4416:     if ($cdom && $cnum) {
                   4417:         my $chome = &homeserver($cnum,$cdom);
                   4418:         if ($chome ne 'no_host') {
                   4419:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4420:             &extract_lastaccess(\%returnhash,$rep);
                   4421:         }
                   4422:     } else {
                   4423:         if (!$cdom) { $cdom=''; }
                   4424:         my %libserv = &all_library();
                   4425:         foreach my $tryserver (keys(%libserv)) {
                   4426:             if (ref($hostidref) eq 'ARRAY') {
                   4427:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4428:             } 
                   4429:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4430:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4431:                 &extract_lastaccess(\%returnhash,$rep);
                   4432:             }
                   4433:         }
                   4434:     }
                   4435:     return %returnhash;
                   4436: }
                   4437: 
                   4438: sub extract_lastaccess {
                   4439:     my ($returnhash,$rep) = @_;
                   4440:     if (ref($returnhash) eq 'HASH') {
                   4441:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4442:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4443:                  $rep eq '') {
                   4444:             my @pairs=split(/\&/,$rep);
                   4445:             foreach my $item (@pairs) {
                   4446:                 my ($key,$value)=split(/\=/,$item,2);
                   4447:                 $key = &unescape($key);
                   4448:                 next if ($key =~ /^error: 2 /);
                   4449:                 $returnhash->{$key} = &thaw_unescape($value);
                   4450:             }
                   4451:         }
                   4452:     }
                   4453:     return;
                   4454: }
                   4455: 
1.658     raeburn  4456: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4457: 
                   4458: sub dcmailput {
1.685     raeburn  4459:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4460:     my $status = &Apache::lonnet::critical(
1.740     www      4461:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4462:        &escape($message),$server);
1.662     raeburn  4463:     return $status;
                   4464: }
                   4465: 
1.658     raeburn  4466: sub dcmaildump {
                   4467:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4468:     my %returnhash=();
1.846     albertel 4469: 
                   4470:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4471:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4472:                                                          &escape($enddate).':';
                   4473: 	my @esc_senders=map { &escape($_)} @$senders;
                   4474: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4475: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4476:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4477:             if (($key) && ($value)) {
                   4478:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4479:             }
                   4480:         }
                   4481:     }
                   4482:     return %returnhash;
                   4483: }
1.662     raeburn  4484: # ---------------------------------------------------------- Domain roles
                   4485: 
                   4486: sub get_domain_roles {
                   4487:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4488:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4489:         $startdate = '.';
                   4490:     }
1.1018    raeburn  4491:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4492:         $enddate = '.';
                   4493:     }
1.922     raeburn  4494:     my $rolelist;
                   4495:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4496:         $rolelist = join('&',@{$roles});
1.922     raeburn  4497:     }
1.662     raeburn  4498:     my %personnel = ();
1.841     albertel 4499: 
                   4500:     my %servers = &get_servers($dom,'library');
                   4501:     foreach my $tryserver (keys(%servers)) {
                   4502: 	%{$personnel{$tryserver}}=();
                   4503: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4504: 					    &escape($startdate).':'.
                   4505: 					    &escape($enddate).':'.
                   4506: 					    &escape($rolelist), $tryserver))) {
                   4507: 	    my ($key,$value) = split(/\=/,$line,2);
                   4508: 	    if (($key) && ($value)) {
                   4509: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4510: 	    }
                   4511: 	}
1.662     raeburn  4512:     }
                   4513:     return %personnel;
                   4514: }
1.658     raeburn  4515: 
1.1057    www      4516: # ----------------------------------------------------------- Interval timing 
1.149     www      4517: 
1.1153    www      4518: {
                   4519: # Caches needed for speedup of navmaps
                   4520: # We don't want to cache this for very long at all (5 seconds at most)
                   4521: # 
                   4522: # The user for whom we cache
                   4523: my $cachedkey='';
                   4524: # The cached times for this user
                   4525: my %cachedtimes=();
                   4526: # When this was last done
1.1172.2.66  raeburn  4527: my $cachedtime='';
1.1153    www      4528: 
                   4529: sub load_all_first_access {
1.1154    raeburn  4530:     my ($uname,$udom)=@_;
1.1156    www      4531:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4532:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4533:         return;
                   4534:     }
                   4535:     $cachedtime=time;
                   4536:     $cachedkey=$uname.':'.$udom;
                   4537:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4538: }
                   4539: 
1.504     albertel 4540: sub get_first_access {
1.1162    raeburn  4541:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4542:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4543:     if ($argsymb) { $symb=$argsymb; }
                   4544:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4545:     if ($argmap) { $map = $argmap; }
1.926     albertel 4546:     if ($type eq 'course') {
                   4547: 	$res='course';
                   4548:     } elsif ($type eq 'map') {
1.588     albertel 4549: 	$res=&symbread($map);
                   4550:     } else {
                   4551: 	$res=$symb;
                   4552:     }
1.1153    www      4553:     &load_all_first_access($uname,$udom);
                   4554:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4555: }
                   4556: 
                   4557: sub set_first_access {
1.1162    raeburn  4558:     my ($type,$interval)=@_;
1.790     albertel 4559:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4560:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4561:     if ($type eq 'course') {
                   4562: 	$res='course';
                   4563:     } elsif ($type eq 'map') {
1.588     albertel 4564: 	$res=&symbread($map);
                   4565:     } else {
                   4566: 	$res=$symb;
                   4567:     }
1.1153    www      4568:     $cachedkey='';
1.1162    raeburn  4569:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4570:     if (!$firstaccess) {
1.1162    raeburn  4571:         my $start = time;
                   4572: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4573:                           $udom,$uname);
                   4574:         if ($putres eq 'ok') {
                   4575:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4576:                  $udom,$uname); 
                   4577:             &appenv(
                   4578:                      {
                   4579:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4580:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4581:                      }
                   4582:                   );
                   4583:         }
                   4584:         return $putres;
1.505     albertel 4585:     }
                   4586:     return 'already_set';
1.504     albertel 4587: }
1.1153    www      4588: }
1.1172.2.32  raeburn  4589: 
                   4590: sub checkout {
                   4591:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4592:     my $now=time;
                   4593:     my $lonhost=$perlvar{'lonHostID'};
                   4594:     my $infostr=&escape(
                   4595:                  'CHECKOUTTOKEN&'.
                   4596:                  $tuname.'&'.
                   4597:                  $tudom.'&'.
                   4598:                  $tcrsid.'&'.
                   4599:                  $symb.'&'.
                   4600:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4601:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4602:     if ($token=~/^error\:/) {
                   4603:         &logthis("<font color=\"blue\">WARNING: ".
                   4604:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4605:                  "</font>");
                   4606:         return '';
                   4607:     }
                   4608: 
                   4609:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4610:     $token=~tr/a-z/A-Z/;
                   4611: 
                   4612:     my %infohash=('resource.0.outtoken' => $token,
                   4613:                   'resource.0.checkouttime' => $now,
                   4614:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4615: 
                   4616:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4617:        return '';
                   4618:     } else {
                   4619:         &logthis("<font color=\"blue\">WARNING: ".
                   4620:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4621:                  "</font>");
                   4622:     }
                   4623: 
                   4624:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4625:                          &escape('Checkout '.$infostr.' - '.
                   4626:                                                  $token)) ne 'ok') {
                   4627:         return '';
                   4628:     } else {
                   4629:         &logthis("<font color=\"blue\">WARNING: ".
                   4630:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4631:                  "</font>");
                   4632:     }
                   4633:     return $token;
                   4634: }
                   4635: 
                   4636: # ------------------------------------------------------------ Check in an item
                   4637: 
                   4638: sub checkin {
                   4639:     my $token=shift;
                   4640:     my $now=time;
                   4641:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4642:     $lonhost=~tr/A-Z/a-z/;
                   4643:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4644:     $dtoken=~s/\W/\_/g;
                   4645:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4646:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4647: 
                   4648:     unless (($tuname) && ($tudom)) {
                   4649:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4650:         return '';
                   4651:     }
                   4652: 
                   4653:     unless (&allowed('mgr',$tcrsid)) {
                   4654:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4655:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4656:         return '';
                   4657:     }
                   4658: 
                   4659:     my %infohash=('resource.0.intoken' => $token,
                   4660:                   'resource.0.checkintime' => $now,
                   4661:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4662: 
                   4663:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4664:        return '';
                   4665:     }
                   4666: 
                   4667:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4668:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4669:         return '';
                   4670:     }
                   4671: 
                   4672:     return ($symb,$tuname,$tudom,$tcrsid);
                   4673: }
                   4674: 
1.110     www      4675: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4676: 
                   4677: sub expirespread {
                   4678:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4679:     my $cid=$env{'request.course.id'}; 
1.110     www      4680:     if ($cid) {
                   4681:        my $now=time;
                   4682:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4683:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4684:                             $env{'course.'.$cid.'.num'}.
1.110     www      4685: 	        	    ':nohist_expirationdates:'.
                   4686:                             &escape($key).'='.$now,
1.620     albertel 4687:                             $env{'course.'.$cid.'.home'})
1.110     www      4688:     }
                   4689:     return 'ok';
1.14      www      4690: }
                   4691: 
1.109     www      4692: # ----------------------------------------------------- Devalidate Spreadsheets
                   4693: 
                   4694: sub devalidate {
1.325     www      4695:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4696:     my $cid=$env{'request.course.id'}; 
1.109     www      4697:     if ($cid) {
1.391     matthew  4698:         # delete the stored spreadsheets for
                   4699:         # - the student level sheet of this user in course's homespace
                   4700:         # - the assessment level sheet for this resource 
                   4701:         #   for this user in user's homespace
1.553     albertel 4702: 	# - current conditional state info
1.325     www      4703: 	my $key=$uname.':'.$udom.':';
1.109     www      4704:         my $status=
1.299     matthew  4705: 	    &del('nohist_calculatedsheets',
1.391     matthew  4706: 		 [$key.'studentcalc:'],
1.620     albertel 4707: 		 $env{'course.'.$cid.'.domain'},
                   4708: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4709: 		.' '.
                   4710: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4711: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4712:         unless ($status eq 'ok ok') {
                   4713:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4714:                     $uname.' at '.$udom.' for '.
1.109     www      4715: 		    $symb.': '.$status);
1.133     albertel 4716:         }
1.553     albertel 4717: 	&delenv('user.state.'.$cid);
1.109     www      4718:     }
                   4719: }
                   4720: 
1.265     albertel 4721: sub get_scalar {
                   4722:     my ($string,$end) = @_;
                   4723:     my $value;
                   4724:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4725: 	$value = $1;
                   4726:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4727: 	$value = $1;
                   4728:     }
                   4729:     return &unescape($value);
                   4730: }
                   4731: 
                   4732: sub array2str {
                   4733:   my (@array) = @_;
                   4734:   my $result=&arrayref2str(\@array);
                   4735:   $result=~s/^__ARRAY_REF__//;
                   4736:   $result=~s/__END_ARRAY_REF__$//;
                   4737:   return $result;
                   4738: }
                   4739: 
1.204     albertel 4740: sub arrayref2str {
                   4741:   my ($arrayref) = @_;
1.265     albertel 4742:   my $result='__ARRAY_REF__';
1.204     albertel 4743:   foreach my $elem (@$arrayref) {
1.265     albertel 4744:     if(ref($elem) eq 'ARRAY') {
                   4745:       $result.=&arrayref2str($elem).'&';
                   4746:     } elsif(ref($elem) eq 'HASH') {
                   4747:       $result.=&hashref2str($elem).'&';
                   4748:     } elsif(ref($elem)) {
                   4749:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4750:     } else {
                   4751:       $result.=&escape($elem).'&';
                   4752:     }
                   4753:   }
                   4754:   $result=~s/\&$//;
1.265     albertel 4755:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4756:   return $result;
                   4757: }
                   4758: 
1.168     albertel 4759: sub hash2str {
1.204     albertel 4760:   my (%hash) = @_;
                   4761:   my $result=&hashref2str(\%hash);
1.265     albertel 4762:   $result=~s/^__HASH_REF__//;
                   4763:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4764:   return $result;
                   4765: }
                   4766: 
                   4767: sub hashref2str {
                   4768:   my ($hashref)=@_;
1.265     albertel 4769:   my $result='__HASH_REF__';
1.800     albertel 4770:   foreach my $key (sort(keys(%$hashref))) {
                   4771:     if (ref($key) eq 'ARRAY') {
                   4772:       $result.=&arrayref2str($key).'=';
                   4773:     } elsif (ref($key) eq 'HASH') {
                   4774:       $result.=&hashref2str($key).'=';
                   4775:     } elsif (ref($key)) {
1.265     albertel 4776:       $result.='=';
1.800     albertel 4777:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4778:     } else {
1.1132    raeburn  4779: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4780:     }
                   4781: 
1.800     albertel 4782:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4783:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4784:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4785:       $result.=&hashref2str($hashref->{$key}).'&';
                   4786:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4787:        $result.='&';
1.800     albertel 4788:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4789:     } else {
1.800     albertel 4790:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4791:     }
                   4792:   }
1.168     albertel 4793:   $result=~s/\&$//;
1.265     albertel 4794:   $result .= '__END_HASH_REF__';
1.168     albertel 4795:   return $result;
                   4796: }
                   4797: 
                   4798: sub str2hash {
1.265     albertel 4799:     my ($string)=@_;
                   4800:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4801:     return %$hash;
                   4802: }
                   4803: 
                   4804: sub str2hashref {
1.168     albertel 4805:   my ($string) = @_;
1.265     albertel 4806: 
                   4807:   my %hash;
                   4808: 
                   4809:   if($string !~ /^__HASH_REF__/) {
                   4810:       if (! ($string eq '' || !defined($string))) {
                   4811: 	  $hash{'error'}='Not hash reference';
                   4812:       }
                   4813:       return (\%hash, $string);
                   4814:   }
                   4815: 
                   4816:   $string =~ s/^__HASH_REF__//;
                   4817: 
                   4818:   while($string !~ /^__END_HASH_REF__/) {
                   4819:       #key
                   4820:       my $key='';
                   4821:       if($string =~ /^__HASH_REF__/) {
                   4822:           ($key, $string)=&str2hashref($string);
                   4823:           if(defined($key->{'error'})) {
                   4824:               $hash{'error'}='Bad data';
                   4825:               return (\%hash, $string);
                   4826:           }
                   4827:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4828:           ($key, $string)=&str2arrayref($string);
                   4829:           if($key->[0] eq 'Array reference error') {
                   4830:               $hash{'error'}='Bad data';
                   4831:               return (\%hash, $string);
                   4832:           }
                   4833:       } else {
                   4834:           $string =~ s/^(.*?)=//;
1.267     albertel 4835: 	  $key=&unescape($1);
1.265     albertel 4836:       }
                   4837:       $string =~ s/^=//;
                   4838: 
                   4839:       #value
                   4840:       my $value='';
                   4841:       if($string =~ /^__HASH_REF__/) {
                   4842:           ($value, $string)=&str2hashref($string);
                   4843:           if(defined($value->{'error'})) {
                   4844:               $hash{'error'}='Bad data';
                   4845:               return (\%hash, $string);
                   4846:           }
                   4847:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4848:           ($value, $string)=&str2arrayref($string);
                   4849:           if($value->[0] eq 'Array reference error') {
                   4850:               $hash{'error'}='Bad data';
                   4851:               return (\%hash, $string);
                   4852:           }
                   4853:       } else {
                   4854: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4855:       }
                   4856:       $string =~ s/^&//;
                   4857: 
                   4858:       $hash{$key}=$value;
1.204     albertel 4859:   }
1.265     albertel 4860: 
                   4861:   $string =~ s/^__END_HASH_REF__//;
                   4862: 
                   4863:   return (\%hash, $string);
1.204     albertel 4864: }
                   4865: 
                   4866: sub str2array {
1.265     albertel 4867:     my ($string)=@_;
                   4868:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4869:     return @$array;
                   4870: }
                   4871: 
                   4872: sub str2arrayref {
1.204     albertel 4873:   my ($string) = @_;
1.265     albertel 4874:   my @array;
                   4875: 
                   4876:   if($string !~ /^__ARRAY_REF__/) {
                   4877:       if (! ($string eq '' || !defined($string))) {
                   4878: 	  $array[0]='Array reference error';
                   4879:       }
                   4880:       return (\@array, $string);
                   4881:   }
                   4882: 
                   4883:   $string =~ s/^__ARRAY_REF__//;
                   4884: 
                   4885:   while($string !~ /^__END_ARRAY_REF__/) {
                   4886:       my $value='';
                   4887:       if($string =~ /^__HASH_REF__/) {
                   4888:           ($value, $string)=&str2hashref($string);
                   4889:           if(defined($value->{'error'})) {
                   4890:               $array[0] ='Array reference error';
                   4891:               return (\@array, $string);
                   4892:           }
                   4893:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4894:           ($value, $string)=&str2arrayref($string);
                   4895:           if($value->[0] eq 'Array reference error') {
                   4896:               $array[0] ='Array reference error';
                   4897:               return (\@array, $string);
                   4898:           }
                   4899:       } else {
                   4900: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4901:       }
                   4902:       $string =~ s/^&//;
                   4903: 
                   4904:       push(@array, $value);
1.191     harris41 4905:   }
1.265     albertel 4906: 
                   4907:   $string =~ s/^__END_ARRAY_REF__//;
                   4908: 
                   4909:   return (\@array, $string);
1.168     albertel 4910: }
                   4911: 
1.167     albertel 4912: # -------------------------------------------------------------------Temp Store
                   4913: 
1.168     albertel 4914: sub tmpreset {
                   4915:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4916:   if (!$symb) {
                   4917:     $symb=&symbread();
1.620     albertel 4918:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4919:   }
                   4920:   $symb=escape($symb);
                   4921: 
1.620     albertel 4922:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4923:   $namespace=~s/\//\_/g;
                   4924:   $namespace=~s/\W//g;
                   4925: 
1.620     albertel 4926:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4927:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4928:   if ($domain eq 'public' && $stuname eq 'public') {
                   4929:       $stuname=$ENV{'REMOTE_ADDR'};
                   4930:   }
1.1117    foxr     4931:   my $path=LONCAPA::tempdir();
1.168     albertel 4932:   my %hash;
                   4933:   if (tie(%hash,'GDBM_File',
                   4934: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4935: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4936:     foreach my $key (keys(%hash)) {
1.180     albertel 4937:       if ($key=~ /:$symb/) {
1.168     albertel 4938: 	delete($hash{$key});
                   4939:       }
                   4940:     }
                   4941:   }
                   4942: }
                   4943: 
1.167     albertel 4944: sub tmpstore {
1.168     albertel 4945:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4946: 
                   4947:   if (!$symb) {
                   4948:     $symb=&symbread();
1.620     albertel 4949:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4950:   }
                   4951:   $symb=escape($symb);
                   4952: 
                   4953:   if (!$namespace) {
                   4954:     # I don't think we would ever want to store this for a course.
                   4955:     # it seems this will only be used if we don't have a course.
1.620     albertel 4956:     #$namespace=$env{'request.course.id'};
1.168     albertel 4957:     #if (!$namespace) {
1.620     albertel 4958:       $namespace=$env{'request.state'};
1.168     albertel 4959:     #}
                   4960:   }
                   4961:   $namespace=~s/\//\_/g;
                   4962:   $namespace=~s/\W//g;
1.620     albertel 4963:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4964:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4965:   if ($domain eq 'public' && $stuname eq 'public') {
                   4966:       $stuname=$ENV{'REMOTE_ADDR'};
                   4967:   }
1.168     albertel 4968:   my $now=time;
                   4969:   my %hash;
1.1117    foxr     4970:   my $path=LONCAPA::tempdir();
1.168     albertel 4971:   if (tie(%hash,'GDBM_File',
                   4972: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4973: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4974:     $hash{"version:$symb"}++;
                   4975:     my $version=$hash{"version:$symb"};
                   4976:     my $allkeys=''; 
                   4977:     foreach my $key (keys(%$storehash)) {
                   4978:       $allkeys.=$key.':';
1.591     albertel 4979:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4980:     }
                   4981:     $hash{"$version:$symb:timestamp"}=$now;
                   4982:     $allkeys.='timestamp';
                   4983:     $hash{"$version:keys:$symb"}=$allkeys;
                   4984:     if (untie(%hash)) {
                   4985:       return 'ok';
                   4986:     } else {
                   4987:       return "error:$!";
                   4988:     }
                   4989:   } else {
                   4990:     return "error:$!";
                   4991:   }
                   4992: }
1.167     albertel 4993: 
1.168     albertel 4994: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4995: 
1.168     albertel 4996: sub tmprestore {
                   4997:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4998: 
1.168     albertel 4999:   if (!$symb) {
                   5000:     $symb=&symbread();
1.620     albertel 5001:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5002:   }
                   5003:   $symb=escape($symb);
                   5004: 
1.620     albertel 5005:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5006: 
1.620     albertel 5007:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5008:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5009:   if ($domain eq 'public' && $stuname eq 'public') {
                   5010:       $stuname=$ENV{'REMOTE_ADDR'};
                   5011:   }
1.168     albertel 5012:   my %returnhash;
                   5013:   $namespace=~s/\//\_/g;
                   5014:   $namespace=~s/\W//g;
                   5015:   my %hash;
1.1117    foxr     5016:   my $path=LONCAPA::tempdir();
1.168     albertel 5017:   if (tie(%hash,'GDBM_File',
                   5018: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5019: 	  &GDBM_READER(),0640)) {
1.168     albertel 5020:     my $version=$hash{"version:$symb"};
                   5021:     $returnhash{'version'}=$version;
                   5022:     my $scope;
                   5023:     for ($scope=1;$scope<=$version;$scope++) {
                   5024:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5025:       my @keys=split(/:/,$vkeys);
                   5026:       my $key;
                   5027:       $returnhash{"$scope:keys"}=$vkeys;
                   5028:       foreach $key (@keys) {
1.591     albertel 5029: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5030: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5031:       }
                   5032:     }
1.168     albertel 5033:     if (!(untie(%hash))) {
                   5034:       return "error:$!";
                   5035:     }
                   5036:   } else {
                   5037:     return "error:$!";
                   5038:   }
                   5039:   return %returnhash;
1.167     albertel 5040: }
                   5041: 
1.9       www      5042: # ----------------------------------------------------------------------- Store
                   5043: 
                   5044: sub store {
1.1172.2.64  raeburn  5045:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5046:     my $home='';
                   5047: 
1.168     albertel 5048:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5049: 
1.213     www      5050:     $symb=&symbclean($symb);
1.122     albertel 5051:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5052: 
1.620     albertel 5053:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5054:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5055: 
                   5056:     &devalidate($symb,$stuname,$domain);
1.109     www      5057: 
                   5058:     $symb=escape($symb);
1.187     www      5059:     if (!$namespace) { 
1.620     albertel 5060:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5061:           return ''; 
                   5062:        } 
                   5063:     }
1.620     albertel 5064:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5065: 
                   5066:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5067:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5068: 
1.12      www      5069:     my $namevalue='';
1.800     albertel 5070:     foreach my $key (keys(%$storehash)) {
                   5071:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5072:     }
1.12      www      5073:     $namevalue=~s/\&$//;
1.187     www      5074:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5075:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5076: }
                   5077: 
1.47      www      5078: # -------------------------------------------------------------- Critical Store
                   5079: 
                   5080: sub cstore {
1.1172.2.64  raeburn  5081:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5082:     my $home='';
                   5083: 
1.168     albertel 5084:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5085: 
1.213     www      5086:     $symb=&symbclean($symb);
1.122     albertel 5087:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5088: 
1.620     albertel 5089:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5090:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5091: 
                   5092:     &devalidate($symb,$stuname,$domain);
1.109     www      5093: 
                   5094:     $symb=escape($symb);
1.187     www      5095:     if (!$namespace) { 
1.620     albertel 5096:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5097:           return ''; 
                   5098:        } 
                   5099:     }
1.620     albertel 5100:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5101: 
                   5102:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5103:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5104: 
1.47      www      5105:     my $namevalue='';
1.800     albertel 5106:     foreach my $key (keys(%$storehash)) {
                   5107:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5108:     }
1.47      www      5109:     $namevalue=~s/\&$//;
1.187     www      5110:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5111:     return critical
1.1172.2.64  raeburn  5112:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5113: }
                   5114: 
1.9       www      5115: # --------------------------------------------------------------------- Restore
                   5116: 
                   5117: sub restore {
1.124     www      5118:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5119:     my $home='';
                   5120: 
1.168     albertel 5121:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5122: 
1.122     albertel 5123:     if (!$symb) {
1.1172.2.26  raeburn  5124:         return if ($namespace eq 'courserequests');
                   5125:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5126:     } else {
1.1172.2.26  raeburn  5127:         unless ($namespace eq 'courserequests') {
                   5128:             $symb=&escape(&symbclean($symb));
                   5129:         }
1.122     albertel 5130:     }
1.188     www      5131:     if (!$namespace) { 
1.620     albertel 5132:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5133:           return ''; 
                   5134:        } 
                   5135:     }
1.620     albertel 5136:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5137:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5138:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5139:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5140: 
1.12      www      5141:     my %returnhash=();
1.800     albertel 5142:     foreach my $line (split(/\&/,$answer)) {
                   5143: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5144:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5145:     }
1.75      www      5146:     my $version;
                   5147:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5148:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5149:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5150:        }
1.75      www      5151:     }
1.13      www      5152:     return %returnhash;
1.34      www      5153: }
                   5154: 
                   5155: # ---------------------------------------------------------- Course Description
1.1118    foxr     5156: #
                   5157: #  
1.34      www      5158: 
                   5159: sub coursedescription {
1.731     albertel 5160:     my ($courseid,$args)=@_;
1.34      www      5161:     $courseid=~s/^\///;
1.49      www      5162:     $courseid=~s/\_/\//g;
1.34      www      5163:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5164:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5165:     my $normalid=$cdomain.'_'.$cnum;
                   5166:     # need to always cache even if we get errors otherwise we keep 
                   5167:     # trying and trying and trying to get the course description.
                   5168:     my %envhash=();
                   5169:     my %returnhash=();
1.731     albertel 5170:     
                   5171:     my $expiretime=600;
                   5172:     if ($env{'request.course.id'} eq $normalid) {
                   5173: 	$expiretime=120;
                   5174:     }
                   5175: 
                   5176:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5177:     if (!$args->{'freshen_cache'}
                   5178: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5179: 	foreach my $key (keys(%env)) {
                   5180: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5181: 	    my ($setting) = $1;
                   5182: 	    $returnhash{$setting} = $env{$key};
                   5183: 	}
                   5184: 	return %returnhash;
                   5185:     }
                   5186: 
1.1118    foxr     5187:     # get the data again
                   5188: 
1.731     albertel 5189:     if (!$args->{'one_time'}) {
                   5190: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5191:     }
1.811     albertel 5192: 
1.34      www      5193:     if ($chome ne 'no_host') {
1.302     albertel 5194:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5195:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5196: 	   my $username = $env{'user.name'}; # Defult username
                   5197: 	   if(defined $args->{'user'}) {
                   5198: 	       $username = $args->{'user'};
                   5199: 	   }
1.129     albertel 5200:            $returnhash{'home'}= $chome;
                   5201: 	   $returnhash{'domain'} = $cdomain;
                   5202: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5203:            if (!defined($returnhash{'type'})) {
                   5204:                $returnhash{'type'} = 'Course';
                   5205:            }
1.130     albertel 5206:            while (my ($name,$value) = each %returnhash) {
1.53      www      5207:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5208:            }
1.270     www      5209:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5210:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5211: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5212:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5213:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5214:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5215:        }
                   5216:     }
1.731     albertel 5217:     if (!$args->{'one_time'}) {
1.949     raeburn  5218: 	&appenv(\%envhash);
1.731     albertel 5219:     }
1.302     albertel 5220:     return %returnhash;
1.461     www      5221: }
                   5222: 
1.1080    raeburn  5223: sub update_released_required {
                   5224:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5225:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5226:         $cid = $env{'request.course.id'};
                   5227:         $cdom = $env{'course.'.$cid.'.domain'};
                   5228:         $cnum = $env{'course.'.$cid.'.num'};
                   5229:         $chome = $env{'course.'.$cid.'.home'};
                   5230:     }
                   5231:     if ($needsrelease) {
                   5232:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5233:         my $needsupdate;
                   5234:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5235:             $needsupdate = 1;
                   5236:         } else {
                   5237:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5238:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5239:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5240:                 $needsupdate = 1;
                   5241:             }
                   5242:         }
                   5243:         if ($needsupdate) {
                   5244:             my %needshash = (
                   5245:                              'internal.releaserequired' => $needsrelease,
                   5246:                             );
                   5247:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5248:             if ($putresult eq 'ok') {
                   5249:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5250:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5251:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5252:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5253:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5254:                 }
                   5255:             }
                   5256:         }
                   5257:     }
                   5258:     return;
                   5259: }
                   5260: 
1.461     www      5261: # -------------------------------------------------See if a user is privileged
                   5262: 
                   5263: sub privileged {
1.1172.2.23  raeburn  5264:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5265:     my $now = time;
1.1172.2.23  raeburn  5266:     my $roles;
                   5267:     if (ref($possroles) eq 'ARRAY') {
                   5268:         $roles = $possroles;
                   5269:     } else {
                   5270:         $roles = ['dc','su'];
                   5271:     }
                   5272:     if (ref($possdomains) eq 'ARRAY') {
                   5273:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5274:         foreach my $dom (@{$possdomains}) {
                   5275:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5276:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5277:                 foreach my $role (@{$roles}) {
                   5278:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5279:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5280:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5281:                             return 1 unless (($end && $end < $now) ||
                   5282:                                              ($start && $start > $now));
                   5283:                         }
                   5284:                     }
                   5285:                 }
                   5286:             }
                   5287:         }
                   5288:     } else {
                   5289:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5290:         my $now = time;
1.1170    droeschl 5291: 
1.1172.2.58  raeburn  5292:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5293:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5294:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5295:                 return 1 unless ($tend && $tend < $now)
                   5296:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5297:             }
1.1172.2.23  raeburn  5298:         }
                   5299:     }
1.461     www      5300:     return 0;
1.9       www      5301: }
1.1       albertel 5302: 
1.1172.2.23  raeburn  5303: sub privileged_by_domain {
                   5304:     my ($domains,$roles) = @_;
                   5305:     my %privileged = ();
                   5306:     my $cachetime = 60*60*24;
                   5307:     my $now = time;
                   5308:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5309:         return %privileged;
                   5310:     }
                   5311:     foreach my $dom (@{$domains}) {
                   5312:         next if (ref($privileged{$dom}) eq 'HASH');
                   5313:         my $needroles;
                   5314:         foreach my $role (@{$roles}) {
                   5315:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5316:             if (defined($cached)) {
                   5317:                 if (ref($result) eq 'HASH') {
                   5318:                     $privileged{$dom}{$role} = $result;
                   5319:                 }
                   5320:             } else {
                   5321:                 $needroles = 1;
                   5322:             }
                   5323:         }
                   5324:         if ($needroles) {
                   5325:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5326:             $privileged{$dom} = {};
                   5327:             foreach my $server (keys(%dompersonnel)) {
                   5328:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5329:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5330:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5331:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5332:                         next if ($end && $end < $now);
                   5333:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5334:                             $dompersonnel{$server}{$item};
                   5335:                     }
                   5336:                 }
                   5337:             }
                   5338:             if (ref($privileged{$dom}) eq 'HASH') {
                   5339:                 foreach my $role (@{$roles}) {
                   5340:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5341:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5342:                     } else {
                   5343:                         my %hash = ();
                   5344:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5345:                     }
                   5346:                 }
                   5347:             }
                   5348:         }
                   5349:     }
                   5350:     return %privileged;
                   5351: }
                   5352: 
1.103     harris41 5353: # -------------------------------------------------------- Get user privileges
1.11      www      5354: 
                   5355: sub rolesinit {
1.1169    droeschl 5356:     my ($domain, $username) = @_;
                   5357:     my %userroles = ('user.login.time' => time);
                   5358:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5359: 
                   5360:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5361:     # also, blocking can be triggered by an activating timer
                   5362:     # it's saved in the user's %env.
                   5363:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5364:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5365:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5366:         %timerintchk, %timerintenv);
                   5367: 
1.1162    raeburn  5368:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5369:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5370:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5371:     }
1.1169    droeschl 5372: 
1.1162    raeburn  5373:     foreach my $key (keys(%timerinterval)) {
                   5374:         my ($cid,$rest) = split(/\0/,$key);
                   5375:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5376:     }
1.1169    droeschl 5377: 
1.11      www      5378:     my %allroles=();
1.1162    raeburn  5379:     my %allgroups=();
1.11      www      5380: 
1.1172.2.58  raeburn  5381:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5382:         my $role = $rolesdump{$area};
                   5383:         $area =~ s/\_\w\w$//;
                   5384: 
                   5385:         my ($trole, $tend, $tstart, $group_privs);
                   5386: 
                   5387:         if ($role =~ /^cr/) {
                   5388:         # Custom role, defined by a user 
                   5389:         # e.g., user.role.cr/msu/smith/mynewrole
                   5390:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5391:                 $trole = $1;
                   5392:                 ($tend, $tstart) = split('_', $2);
                   5393:             } else {
                   5394:                 $trole = $role;
                   5395:             }
                   5396:         } elsif ($role =~ m|^gr/|) {
                   5397:         # Role of member in a group, defined within a course/community
                   5398:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5399:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5400:             next if $tstart eq '-1';
                   5401:             ($trole, $group_privs) = split(/\//, $trole);
                   5402:             $group_privs = &unescape($group_privs);
                   5403:         } else {
                   5404:         # Just a normal role, defined in roles.tab
                   5405:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5406:         }
                   5407: 
                   5408:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5409:                  $username);
                   5410:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5411: 
                   5412:         # role expired or not available yet?
                   5413:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5414:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5415: 
                   5416:         next if $area eq '' or $trole eq '';
                   5417: 
                   5418:         my $spec = "$trole.$area";
                   5419:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5420: 
                   5421:         if ($trole =~ /^cr\//) {
                   5422:         # Custom role, defined by a user
                   5423:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5424:         } elsif ($trole eq 'gr') {
                   5425:         # Role of a member in a group, defined within a course/community
                   5426:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5427:             next;
                   5428:         } else {
                   5429:         # Normal role, defined in roles.tab
                   5430:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5431:         }
                   5432: 
                   5433:         my $cid = $tdomain.'_'.$trest;
                   5434:         unless ($firstaccchk{$cid}) {
                   5435:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5436:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5437:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5438:                         $coursetimerstarts{$cid}{$item}; 
                   5439:                 }
                   5440:             }
                   5441:             $firstaccchk{$cid} = 1;
                   5442:         }
                   5443:         unless ($timerintchk{$cid}) {
                   5444:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5445:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5446:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5447:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5448:                 }
1.12      www      5449:             }
1.1169    droeschl 5450:             $timerintchk{$cid} = 1;
1.191     harris41 5451:         }
1.11      www      5452:     }
1.1169    droeschl 5453: 
                   5454:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5455:         \%allroles, \%allgroups);
                   5456:     $env{'user.adv'} = $userroles{'user.adv'};
                   5457: 
1.1162    raeburn  5458:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5459: }
                   5460: 
1.567     raeburn  5461: sub set_arearole {
1.1172.2.19  raeburn  5462:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5463:     unless ($nolog) {
1.567     raeburn  5464: # log the associated role with the area
1.1172.2.19  raeburn  5465:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5466:     }
1.743     albertel 5467:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5468: }
                   5469: 
                   5470: sub custom_roleprivs {
                   5471:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5472:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5473:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5474:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5475:         my ($rdummy,$roledef)=
                   5476:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5477:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5478:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5479:             if (defined($syspriv)) {
1.1043    raeburn  5480:                 if ($trest =~ /^$match_community$/) {
                   5481:                     $syspriv =~ s/bre\&S//; 
                   5482:                 }
1.567     raeburn  5483:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5484:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5485:             }
                   5486:             if ($tdomain ne '') {
                   5487:                 if (defined($dompriv)) {
                   5488:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5489:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5490:                 }
                   5491:                 if (($trest ne '') && (defined($coursepriv))) {
                   5492:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5493:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5494:                 }
                   5495:             }
                   5496:         }
                   5497:     }
                   5498: }
                   5499: 
1.678     raeburn  5500: sub group_roleprivs {
                   5501:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5502:     my $access = 1;
                   5503:     my $now = time;
                   5504:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5505:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5506:     if ($access) {
1.811     albertel 5507:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5508:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5509:     }
                   5510: }
1.567     raeburn  5511: 
                   5512: sub standard_roleprivs {
                   5513:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5514:     if (defined($pr{$trole.':s'})) {
                   5515:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5516:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5517:     }
                   5518:     if ($tdomain ne '') {
                   5519:         if (defined($pr{$trole.':d'})) {
                   5520:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5521:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5522:         }
                   5523:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5524:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5525:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5526:         }
                   5527:     }
                   5528: }
                   5529: 
                   5530: sub set_userprivs {
1.1064    raeburn  5531:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5532:     my $author=0;
                   5533:     my $adv=0;
1.678     raeburn  5534:     my %grouproles = ();
                   5535:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5536:         my @groupkeys; 
1.1000    raeburn  5537:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5538:             push(@groupkeys,$role);
                   5539:         }
                   5540:         if (ref($groups_roles) eq 'HASH') {
                   5541:             foreach my $key (keys(%{$groups_roles})) {
                   5542:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5543:                     push(@groupkeys,$key);
                   5544:                 }
                   5545:             }
                   5546:         }
                   5547:         if (@groupkeys > 0) {
                   5548:             foreach my $role (@groupkeys) {
                   5549:                 my ($trole,$area,$sec,$extendedarea);
                   5550:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5551:                     $trole = $1;
                   5552:                     $area = $2;
                   5553:                     $sec = $3;
                   5554:                     $extendedarea = $area.$sec;
                   5555:                     if (exists($$allgroups{$area})) {
                   5556:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5557:                             my $spec = $trole.'.'.$extendedarea;
                   5558:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5559:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5560:                         }
1.678     raeburn  5561:                     }
                   5562:                 }
                   5563:             }
                   5564:         }
                   5565:     }
1.800     albertel 5566:     foreach my $group (keys(%grouproles)) {
                   5567:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5568:     }
1.800     albertel 5569:     foreach my $role (keys(%{$allroles})) {
                   5570:         my %thesepriv;
1.941     raeburn  5571:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5572:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5573:             if ($item ne '') {
                   5574:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5575:                 if ($restrictions eq '') {
                   5576:                     $thesepriv{$privilege}='F';
                   5577:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5578:                     $thesepriv{$privilege}.=$restrictions;
                   5579:                 }
                   5580:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5581:             }
                   5582:         }
                   5583:         my $thesestr='';
1.1104    raeburn  5584:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5585: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5586: 	}
                   5587:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5588:     }
                   5589:     return ($author,$adv);
                   5590: }
                   5591: 
1.994     raeburn  5592: sub role_status {
1.1104    raeburn  5593:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5594:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  5595:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5596:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5597:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  5598:             $$where = '/'.$two;
1.994     raeburn  5599:             $$trolecode=$$role.'.'.$$where;
                   5600:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5601:             $$tstatus='is';
1.1104    raeburn  5602:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5603:                 $$tstatus='future';
1.1034    raeburn  5604:                 if ($$tstart<$now) {
                   5605:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5606:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5607:                             my (%allroles,%allgroups,$group_privs,
                   5608:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5609:                             my %userroles = (
                   5610:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5611:                             );
1.1064    raeburn  5612:                             @rolecodes = ('cm'); 
1.1002    raeburn  5613:                             my $spec=$$role.'.'.$$where;
                   5614:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5615:                             if ($$role =~ /^cr\//) {
                   5616:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5617:                                 push(@rolecodes,'cr');
1.1002    raeburn  5618:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5619:                                 push(@rolecodes,$$role);
1.1002    raeburn  5620:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5621:                                                     $env{'user.name'});
1.1064    raeburn  5622:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5623:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5624:                                 $group_privs = &unescape($group_privs);
                   5625:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5626:                                 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  5627:                                 &get_groups_roles($tdomain,$trest,
                   5628:                                                   \%course_roles,\@rolecodes,
                   5629:                                                   \%groups_roles);
1.1002    raeburn  5630:                             } else {
1.1064    raeburn  5631:                                 push(@rolecodes,$$role);
1.1002    raeburn  5632:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5633:                             }
1.1064    raeburn  5634:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5635:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5636:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5637:                         }
                   5638:                     }
1.1034    raeburn  5639:                     $$tstatus = 'is';
1.1002    raeburn  5640:                 }
1.994     raeburn  5641:             }
                   5642:             if ($$tend) {
1.1104    raeburn  5643:                 if ($$tend<$update) {
1.994     raeburn  5644:                     $$tstatus='expired';
                   5645:                 } elsif ($$tend<$now) {
                   5646:                     $$tstatus='will_not';
                   5647:                 }
                   5648:             }
                   5649:         }
                   5650:     }
                   5651: }
                   5652: 
1.1104    raeburn  5653: sub get_groups_roles {
                   5654:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5655:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5656:                   (ref($rolecodes) eq 'ARRAY') && 
                   5657:                   (ref($groups_roles) eq 'HASH')); 
                   5658:     if (keys(%{$cdom_courseroles}) > 0) {
                   5659:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5660:         if ($cdom ne '' && $cnum ne '') {
                   5661:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5662:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5663:                     my $crsrole = $1;
                   5664:                     my $crssec = $2;
                   5665:                     if ($crsrole =~ /^cr/) {
                   5666:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5667:                             push(@{$rolecodes},'cr');
                   5668:                         }
                   5669:                     } else {
                   5670:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5671:                             push(@{$rolecodes},$crsrole);
                   5672:                         }
                   5673:                     }
                   5674:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5675:                     if ($crssec ne '') {
                   5676:                         $rolekey .= "/$crssec";
                   5677:                     }
                   5678:                     $rolekey .= './';
                   5679:                     $groups_roles->{$rolekey} = $rolecodes;
                   5680:                 }
                   5681:             }
                   5682:         }
                   5683:     }
                   5684:     return;
                   5685: }
                   5686: 
                   5687: sub delete_env_groupprivs {
                   5688:     my ($where,$courseroles,$possroles) = @_;
                   5689:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5690:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5691:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5692:         %{$courseroles->{$udom}} =
                   5693:             &get_my_roles('','','userroles',['active'],
                   5694:                           $possroles,[$udom],1);
                   5695:     }
                   5696:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5697:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5698:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5699:             my $area = '/'.$cdom.'/'.$cnum;
                   5700:             my $privkey = "user.priv.$crsrole.$area";
                   5701:             if ($crssec ne '') {
                   5702:                 $privkey .= '/'.$crssec;
                   5703:             }
                   5704:             $privkey .= ".$area/$group";
                   5705:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5706:         }
                   5707:     }
                   5708:     return;
                   5709: }
                   5710: 
1.994     raeburn  5711: sub check_adhoc_privs {
1.1104    raeburn  5712:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5713:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9  raeburn  5714:     my $setprivs;
1.994     raeburn  5715:     if ($env{$cckey}) {
                   5716:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5717:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5718:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5719:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5720:             $setprivs = 1;
1.994     raeburn  5721:         }
                   5722:     } else {
1.1088    raeburn  5723:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9  raeburn  5724:         $setprivs = 1;
1.994     raeburn  5725:     }
1.1172.2.9  raeburn  5726:     return $setprivs;
1.994     raeburn  5727: }
                   5728: 
                   5729: sub set_adhoc_privileges {
                   5730: # role can be cc or ca
1.1088    raeburn  5731:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5732:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5733:     my $spec = $role.'.'.$area;
                   5734:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  5735:                                   $env{'user.name'},1);
1.994     raeburn  5736:     my %ccrole = ();
                   5737:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5738:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5739:     &appenv(\%userroles,[$role,'cm']);
                   5740:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5741:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5742:         &appenv( {'request.role'        => $spec,
                   5743:                   'request.role.domain' => $dcdom,
                   5744:                   'request.course.sec'  => ''
                   5745:                  }
                   5746:                );
                   5747:         my $tadv=0;
                   5748:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5749:         &appenv({'request.role.adv'    => $tadv});
                   5750:     }
1.994     raeburn  5751: }
                   5752: 
1.12      www      5753: # --------------------------------------------------------------- get interface
                   5754: 
                   5755: sub get {
1.131     albertel 5756:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5757:    my $items='';
1.800     albertel 5758:    foreach my $item (@$storearr) {
                   5759:        $items.=&escape($item).'&';
1.191     harris41 5760:    }
1.12      www      5761:    $items=~s/\&$//;
1.620     albertel 5762:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5763:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5764:    my $uhome=&homeserver($uname,$udomain);
                   5765: 
1.133     albertel 5766:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5767:    my @pairs=split(/\&/,$rep);
1.273     albertel 5768:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5769:      return @pairs;
                   5770:    }
1.15      www      5771:    my %returnhash=();
1.42      www      5772:    my $i=0;
1.800     albertel 5773:    foreach my $item (@$storearr) {
                   5774:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5775:       $i++;
1.191     harris41 5776:    }
1.15      www      5777:    return %returnhash;
1.27      www      5778: }
                   5779: 
                   5780: # --------------------------------------------------------------- del interface
                   5781: 
                   5782: sub del {
1.133     albertel 5783:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5784:    my $items='';
1.800     albertel 5785:    foreach my $item (@$storearr) {
                   5786:        $items.=&escape($item).'&';
1.191     harris41 5787:    }
1.984     neumanie 5788: 
1.27      www      5789:    $items=~s/\&$//;
1.620     albertel 5790:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5791:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5792:    my $uhome=&homeserver($uname,$udomain);
                   5793:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5794: }
                   5795: 
                   5796: # -------------------------------------------------------------- dump interface
                   5797: 
1.1172.2.22  raeburn  5798: sub unserialize {
                   5799:     my ($rep, $escapedkeys) = @_;
                   5800: 
                   5801:     return {} if $rep =~ /^error/;
                   5802: 
                   5803:     my %returnhash=();
                   5804:     foreach my $item (split(/\&/,$rep)) {
                   5805:         my ($key, $value) = split(/=/, $item, 2);
                   5806:         $key = unescape($key) unless $escapedkeys;
                   5807:         next if $key =~ /^error: 2 /;
                   5808:         $returnhash{$key} = &thaw_unescape($value);
                   5809:     }
                   5810:     return \%returnhash;
                   5811: }
                   5812: 
                   5813: # see Lond::dump_with_regexp
                   5814: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5815: sub dump {
1.1172.2.22  raeburn  5816:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5817:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5818:     if (!$uname) { $uname=$env{'user.name'}; }
                   5819:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5820: 
1.1172.2.55  raeburn  5821:     if ($regexp) {
                   5822:         $regexp=&escape($regexp);
                   5823:     } else {
                   5824:         $regexp='.';
                   5825:     }
1.1172.2.22  raeburn  5826:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   5827:         # user is hosted on this machine
1.1172.2.55  raeburn  5828:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  5829:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  5830:         return %{&unserialize($reply, $escapedkeys)};
                   5831:     }
1.1166    raeburn  5832:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5833:     my @pairs=split(/\&/,$rep);
                   5834:     my %returnhash=();
1.1098    foxr     5835:     if (!($rep =~ /^error/ )) {
                   5836: 	foreach my $item (@pairs) {
                   5837: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  5838:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     5839: 	    next if ($key =~ /^error: 2 /);
                   5840: 	    $returnhash{$key}=&thaw_unescape($value);
                   5841: 	}
1.755     albertel 5842:     }
                   5843:     return %returnhash;
1.407     www      5844: }
                   5845: 
1.1098    foxr     5846: 
1.717     albertel 5847: # --------------------------------------------------------- dumpstore interface
                   5848: 
                   5849: sub dumpstore {
                   5850:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  5851:    # same as dump but keys must be escaped. They may contain colon separated
                   5852:    # lists of values that may themself contain colons (e.g. symbs).
                   5853:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5854: }
                   5855: 
1.407     www      5856: # -------------------------------------------------------------- keys interface
                   5857: 
                   5858: sub getkeys {
                   5859:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5860:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5861:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5862:    my $uhome=&homeserver($uname,$udomain);
                   5863:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5864:    my @keyarray=();
1.800     albertel 5865:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5866:       next if ($key =~ /^error: 2 /);
1.800     albertel 5867:       push(@keyarray,&unescape($key));
1.407     www      5868:    }
                   5869:    return @keyarray;
1.318     matthew  5870: }
                   5871: 
1.319     matthew  5872: # --------------------------------------------------------------- currentdump
                   5873: sub currentdump {
1.328     matthew  5874:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5875:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5876:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5877:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5878:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  5879:    my $rep;
                   5880: 
                   5881:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5882:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   5883:                    $courseid)));
                   5884:    } else {
                   5885:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5886:    }
                   5887: 
1.318     matthew  5888:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5889:    #
1.318     matthew  5890:    my %returnhash=();
1.319     matthew  5891:    #
                   5892:    if ($rep eq "unknown_cmd") { 
                   5893:        # an old lond will not know currentdump
                   5894:        # Do a dump and make it look like a currentdump
1.822     albertel 5895:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5896:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5897:        my %hash = @tmp;
                   5898:        @tmp=();
1.424     matthew  5899:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5900:    } else {
                   5901:        my @pairs=split(/\&/,$rep);
1.800     albertel 5902:        foreach my $pair (@pairs) {
                   5903:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5904:            my ($symb,$param) = split(/:/,$key);
                   5905:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5906:                                                         &thaw_unescape($value);
1.319     matthew  5907:        }
1.191     harris41 5908:    }
1.12      www      5909:    return %returnhash;
1.424     matthew  5910: }
                   5911: 
                   5912: sub convert_dump_to_currentdump{
                   5913:     my %hash = %{shift()};
                   5914:     my %returnhash;
                   5915:     # Code ripped from lond, essentially.  The only difference
                   5916:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5917:     # we might run in to problems with parameter names =~ /^v\./
                   5918:     while (my ($key,$value) = each(%hash)) {
                   5919:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5920: 	$symb  = &unescape($symb);
                   5921: 	$param = &unescape($param);
1.424     matthew  5922:         next if ($v eq 'version' || $symb eq 'keys');
                   5923:         next if (exists($returnhash{$symb}) &&
                   5924:                  exists($returnhash{$symb}->{$param}) &&
                   5925:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5926:         $returnhash{$symb}->{$param}=$value;
                   5927:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5928:     }
                   5929:     #
                   5930:     # Remove all of the keys in the hashes which keep track of
                   5931:     # the version of the parameter.
                   5932:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5933:         # use a foreach because we are going to delete from the hash.
                   5934:         foreach my $key (keys(%$param_hash)) {
                   5935:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5936:         }
                   5937:     }
                   5938:     return \%returnhash;
1.12      www      5939: }
                   5940: 
1.627     albertel 5941: # ------------------------------------------------------ critical inc interface
                   5942: 
                   5943: sub cinc {
                   5944:     return &inc(@_,'critical');
                   5945: }
                   5946: 
1.449     matthew  5947: # --------------------------------------------------------------- inc interface
                   5948: 
                   5949: sub inc {
1.627     albertel 5950:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5951:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5952:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5953:     my $uhome=&homeserver($uname,$udomain);
                   5954:     my $items='';
                   5955:     if (! ref($store)) {
                   5956:         # got a single value, so use that instead
                   5957:         $items = &escape($store).'=&';
                   5958:     } elsif (ref($store) eq 'SCALAR') {
                   5959:         $items = &escape($$store).'=&';        
                   5960:     } elsif (ref($store) eq 'ARRAY') {
                   5961:         $items = join('=&',map {&escape($_);} @{$store});
                   5962:     } elsif (ref($store) eq 'HASH') {
                   5963:         while (my($key,$value) = each(%{$store})) {
                   5964:             $items.= &escape($key).'='.&escape($value).'&';
                   5965:         }
                   5966:     }
                   5967:     $items=~s/\&$//;
1.627     albertel 5968:     if ($critical) {
                   5969: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5970:     } else {
                   5971: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5972:     }
1.449     matthew  5973: }
                   5974: 
1.12      www      5975: # --------------------------------------------------------------- put interface
                   5976: 
                   5977: sub put {
1.134     albertel 5978:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5979:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5980:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5981:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5982:    my $items='';
1.800     albertel 5983:    foreach my $item (keys(%$storehash)) {
                   5984:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5985:    }
1.12      www      5986:    $items=~s/\&$//;
1.134     albertel 5987:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5988: }
                   5989: 
1.631     albertel 5990: # ------------------------------------------------------------ newput interface
                   5991: 
                   5992: sub newput {
                   5993:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5994:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5995:    if (!$uname) { $uname=$env{'user.name'}; }
                   5996:    my $uhome=&homeserver($uname,$udomain);
                   5997:    my $items='';
                   5998:    foreach my $key (keys(%$storehash)) {
                   5999:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6000:    }
                   6001:    $items=~s/\&$//;
                   6002:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6003: }
                   6004: 
                   6005: # ---------------------------------------------------------  putstore interface
                   6006: 
1.524     raeburn  6007: sub putstore {
1.1172.2.59  raeburn  6008:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6009:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6010:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6011:    my $uhome=&homeserver($uname,$udomain);
                   6012:    my $items='';
1.715     albertel 6013:    foreach my $key (keys(%$storehash)) {
                   6014:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6015:    }
1.715     albertel 6016:    $items=~s/\&$//;
1.716     albertel 6017:    my $esc_symb=&escape($symb);
                   6018:    my $esc_v=&escape($version);
1.715     albertel 6019:    my $reply =
1.716     albertel 6020:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6021: 	      $uhome);
1.1172.2.59  raeburn  6022:    if (($tolog) && ($reply eq 'ok')) {
                   6023:        my $namevalue='';
                   6024:        foreach my $key (keys(%{$storehash})) {
                   6025:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6026:        }
                   6027:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6028:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6029:                      '&version='.$esc_v.
                   6030:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6031:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6032:    }
1.715     albertel 6033:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6034:        # gfall back to way things use to be done
1.715     albertel 6035:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6036: 			    $uname);
1.524     raeburn  6037:    }
1.715     albertel 6038:    return $reply;
                   6039: }
                   6040: 
                   6041: sub old_putstore {
1.716     albertel 6042:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6043:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6044:     if (!$uname) { $uname=$env{'user.name'}; }
                   6045:     my $uhome=&homeserver($uname,$udomain);
                   6046:     my %newstorehash;
1.800     albertel 6047:     foreach my $item (keys(%$storehash)) {
                   6048: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6049: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6050:     }
                   6051:     my $items='';
                   6052:     my %allitems = ();
1.800     albertel 6053:     foreach my $item (keys(%newstorehash)) {
                   6054: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6055: 	    my $key = $1.':keys:'.$2;
                   6056: 	    $allitems{$key} .= $3.':';
                   6057: 	}
1.800     albertel 6058: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6059:     }
1.800     albertel 6060:     foreach my $item (keys(%allitems)) {
                   6061: 	$allitems{$item} =~ s/\:$//;
                   6062: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6063:     }
                   6064:     $items=~s/\&$//;
                   6065:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6066: }
                   6067: 
1.47      www      6068: # ------------------------------------------------------ critical put interface
                   6069: 
                   6070: sub cput {
1.134     albertel 6071:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6072:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6073:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6074:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6075:    my $items='';
1.800     albertel 6076:    foreach my $item (keys(%$storehash)) {
                   6077:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6078:    }
1.47      www      6079:    $items=~s/\&$//;
1.134     albertel 6080:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6081: }
                   6082: 
                   6083: # -------------------------------------------------------------- eget interface
                   6084: 
                   6085: sub eget {
1.133     albertel 6086:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6087:    my $items='';
1.800     albertel 6088:    foreach my $item (@$storearr) {
                   6089:        $items.=&escape($item).'&';
1.191     harris41 6090:    }
1.12      www      6091:    $items=~s/\&$//;
1.620     albertel 6092:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6093:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6094:    my $uhome=&homeserver($uname,$udomain);
                   6095:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6096:    my @pairs=split(/\&/,$rep);
                   6097:    my %returnhash=();
1.42      www      6098:    my $i=0;
1.800     albertel 6099:    foreach my $item (@$storearr) {
                   6100:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6101:       $i++;
1.191     harris41 6102:    }
1.12      www      6103:    return %returnhash;
                   6104: }
                   6105: 
1.667     albertel 6106: # ------------------------------------------------------------ tmpput interface
                   6107: sub tmpput {
1.802     raeburn  6108:     my ($storehash,$server,$context)=@_;
1.667     albertel 6109:     my $items='';
1.800     albertel 6110:     foreach my $item (keys(%$storehash)) {
                   6111: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6112:     }
                   6113:     $items=~s/\&$//;
1.802     raeburn  6114:     if (defined($context)) {
                   6115:         $items .= ':'.&escape($context);
                   6116:     }
1.667     albertel 6117:     return &reply("tmpput:$items",$server);
                   6118: }
                   6119: 
                   6120: # ------------------------------------------------------------ tmpget interface
                   6121: sub tmpget {
1.688     albertel 6122:     my ($token,$server)=@_;
                   6123:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6124:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6125:     my %returnhash;
                   6126:     foreach my $item (split(/\&/,$rep)) {
                   6127: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6128:         next if ($key =~ /^error: 2 /);
1.667     albertel 6129: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6130:     }
                   6131:     return %returnhash;
                   6132: }
                   6133: 
1.1113    raeburn  6134: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6135: sub tmpdel {
                   6136:     my ($token,$server)=@_;
                   6137:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6138:     return &reply("tmpdel:$token",$server);
                   6139: }
                   6140: 
1.1172.2.13  raeburn  6141: # ------------------------------------------------------------ get_timebased_id
                   6142: 
                   6143: sub get_timebased_id {
                   6144:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6145:         $maxtries) = @_;
                   6146:     my ($newid,$error,$dellock);
                   6147:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6148:         return ('','ok','invalid call to get suffix');
                   6149:     }
                   6150: 
                   6151: # set defaults for any optional args for which values were not supplied
                   6152:     if ($who eq '') {
                   6153:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6154:     }
                   6155:     if (!$locktries) {
                   6156:         $locktries = 3;
                   6157:     }
                   6158:     if (!$maxtries) {
                   6159:         $maxtries = 10;
                   6160:     }
                   6161: 
                   6162:     if (($cdom eq '') || ($cnum eq '')) {
                   6163:         if ($env{'request.course.id'}) {
                   6164:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6165:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6166:         }
                   6167:         if (($cdom eq '') || ($cnum eq '')) {
                   6168:             return ('','ok','call to get suffix not in course context');
                   6169:         }
                   6170:     }
                   6171: 
                   6172: # construct locking item
                   6173:     my $lockhash = {
                   6174:                       $prefix."\0".'locked_'.$keyid => $who,
                   6175:                    };
                   6176:     my $tries = 0;
                   6177: 
                   6178: # attempt to get lock on nohist_$namespace file
                   6179:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6180:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6181:         $tries ++;
                   6182:         sleep 1;
                   6183:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6184:     }
                   6185: 
                   6186: # attempt to get unique identifier, based on current timestamp
                   6187:     if ($gotlock eq 'ok') {
                   6188:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6189:         my $id = time;
                   6190:         $newid = $id;
1.1172.2.56  raeburn  6191:         if ($idtype eq 'addcode') {
                   6192:             $newid .= &sixnum_code();
                   6193:         }
1.1172.2.13  raeburn  6194:         my $idtries = 0;
                   6195:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6196:             if ($idtype eq 'concat') {
                   6197:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6198:             } elsif ($idtype eq 'addcode') {
                   6199:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6200:             } else {
                   6201:                 $newid ++;
                   6202:             }
                   6203:             $idtries ++;
                   6204:         }
                   6205:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6206:             my %new_item =  (
                   6207:                               $prefix."\0".$newid => $who,
                   6208:                             );
                   6209:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6210:                                                  $cdom,$cnum);
                   6211:             if ($putresult ne 'ok') {
                   6212:                 undef($newid);
                   6213:                 $error = 'error saving new item: '.$putresult;
                   6214:             }
                   6215:         } else {
1.1172.2.56  raeburn  6216:              undef($newid);
1.1172.2.13  raeburn  6217:              $error = ('error: no unique suffix available for the new item ');
                   6218:         }
                   6219: #  remove lock
                   6220:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6221:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6222:     } else {
                   6223:         $error = "error: could not obtain lockfile\n";
                   6224:         $dellock = 'ok';
1.1172.2.58  raeburn  6225:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6226:             $dellock = 'nolock';
                   6227:         }
1.1172.2.13  raeburn  6228:     }
                   6229:     return ($newid,$dellock,$error);
                   6230: }
                   6231: 
1.1172.2.56  raeburn  6232: sub sixnum_code {
                   6233:     my $code;
                   6234:     for (0..6) {
                   6235:         $code .= int( rand(9) );
                   6236:     }
                   6237:     return $code;
                   6238: }
                   6239: 
1.765     albertel 6240: # -------------------------------------------------- portfolio access checking
                   6241: 
                   6242: sub portfolio_access {
1.1172.2.77  raeburn  6243:     my ($requrl,$clientip) = @_;
1.765     albertel 6244:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  6245:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6246:     if ($result) {
                   6247:         my %setters;
                   6248:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6249:             my ($startblock,$endblock) =
                   6250:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6251:             if ($startblock && $endblock) {
                   6252:                 return 'B';
                   6253:             }
                   6254:         } else {
                   6255:             my ($startblock,$endblock) =
                   6256:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6257:             if ($startblock && $endblock) {
                   6258:                 return 'B';
                   6259:             }
                   6260:         }
                   6261:     }
1.765     albertel 6262:     if ($result eq 'ok') {
1.766     albertel 6263:        return 'F';
1.765     albertel 6264:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6265:        return 'A';
1.765     albertel 6266:     }
1.766     albertel 6267:     return '';
1.765     albertel 6268: }
                   6269: 
                   6270: sub get_portfolio_access {
1.1172.2.77  raeburn  6271:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6272: 
                   6273:     if (!ref($access_hash)) {
                   6274: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6275: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6276: 						   $file_name);
                   6277: 	$access_hash = $access_controls{$file_name};
                   6278:     }
                   6279: 
1.1172.2.77  raeburn  6280:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6281:     my $now = time;
                   6282:     if (ref($access_hash) eq 'HASH') {
                   6283:         foreach my $key (keys(%{$access_hash})) {
                   6284:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6285:             if ($start > $now) {
                   6286:                 next;
                   6287:             }
                   6288:             if ($end && $end<$now) {
                   6289:                 next;
                   6290:             }
                   6291:             if ($scope eq 'public') {
                   6292:                 $public = $key;
                   6293:                 last;
                   6294:             } elsif ($scope eq 'guest') {
                   6295:                 $guest = $key;
                   6296:             } elsif ($scope eq 'domains') {
                   6297:                 push(@domains,$key);
                   6298:             } elsif ($scope eq 'users') {
                   6299:                 push(@users,$key);
                   6300:             } elsif ($scope eq 'course') {
                   6301:                 push(@courses,$key);
                   6302:             } elsif ($scope eq 'group') {
                   6303:                 push(@groups,$key);
1.1172.2.77  raeburn  6304:             } elsif ($scope eq 'ip') {
                   6305:                 push(@ips,$key);
1.765     albertel 6306:             }
                   6307:         }
                   6308:         if ($public) {
                   6309:             return 'ok';
1.1172.2.77  raeburn  6310:         } elsif (@ips > 0) {
                   6311:             my $allowed;
                   6312:             foreach my $ipkey (@ips) {
                   6313:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6314:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6315:                         $allowed = 1;
                   6316:                         last;
                   6317:                     }
                   6318:                 }
                   6319:             }
                   6320:             if ($allowed) {
                   6321:                 return 'ok';
                   6322:             }
1.765     albertel 6323:         }
                   6324:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6325:             if ($guest) {
                   6326:                 return $guest;
                   6327:             }
                   6328:         } else {
                   6329:             if (@domains > 0) {
                   6330:                 foreach my $domkey (@domains) {
                   6331:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6332:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6333:                             return 'ok';
                   6334:                         }
                   6335:                     }
                   6336:                 }
                   6337:             }
                   6338:             if (@users > 0) {
                   6339:                 foreach my $userkey (@users) {
1.865     raeburn  6340:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6341:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6342:                             if (ref($item) eq 'HASH') {
                   6343:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6344:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6345:                                     return 'ok';
                   6346:                                 }
                   6347:                             }
                   6348:                         }
                   6349:                     } 
1.765     albertel 6350:                 }
                   6351:             }
                   6352:             my %roleshash;
                   6353:             my @courses_and_groups = @courses;
                   6354:             push(@courses_and_groups,@groups); 
                   6355:             if (@courses_and_groups > 0) {
                   6356:                 my (%allgroups,%allroles); 
                   6357:                 my ($start,$end,$role,$sec,$group);
                   6358:                 foreach my $envkey (%env) {
1.1060    raeburn  6359:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6360:                         my $cid = $2.'_'.$3; 
                   6361:                         if ($1 eq 'gr') {
                   6362:                             $group = $4;
                   6363:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6364:                         } else {
                   6365:                             if ($4 eq '') {
                   6366:                                 $sec = 'none';
                   6367:                             } else {
                   6368:                                 $sec = $4;
                   6369:                             }
                   6370:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6371:                         }
1.811     albertel 6372:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6373:                         my $cid = $2.'_'.$3;
                   6374:                         if ($4 eq '') {
                   6375:                             $sec = 'none';
                   6376:                         } else {
                   6377:                             $sec = $4;
                   6378:                         }
                   6379:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6380:                     }
                   6381:                 }
                   6382:                 if (keys(%allroles) == 0) {
                   6383:                     return;
                   6384:                 }
                   6385:                 foreach my $key (@courses_and_groups) {
                   6386:                     my %content = %{$$access_hash{$key}};
                   6387:                     my $cnum = $content{'number'};
                   6388:                     my $cdom = $content{'domain'};
                   6389:                     my $cid = $cdom.'_'.$cnum;
                   6390:                     if (!exists($allroles{$cid})) {
                   6391:                         next;
                   6392:                     }    
                   6393:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6394:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6395:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6396:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6397:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6398:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6399:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6400:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6401:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6402:                                         if (grep/^all$/,@sections) {
                   6403:                                             return 'ok';
                   6404:                                         } else {
                   6405:                                             if (grep/^$sec$/,@sections) {
                   6406:                                                 return 'ok';
                   6407:                                             }
                   6408:                                         }
                   6409:                                     }
                   6410:                                 }
                   6411:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6412:                                     if (grep/^none$/,@groups) {
                   6413:                                         return 'ok';
                   6414:                                     }
                   6415:                                 } else {
                   6416:                                     if (grep/^all$/,@groups) {
                   6417:                                         return 'ok';
                   6418:                                     } 
                   6419:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6420:                                         if (grep/^$group$/,@groups) {
                   6421:                                             return 'ok';
                   6422:                                         }
                   6423:                                     }
                   6424:                                 } 
                   6425:                             }
                   6426:                         }
                   6427:                     }
                   6428:                 }
                   6429:             }
                   6430:             if ($guest) {
                   6431:                 return $guest;
                   6432:             }
                   6433:         }
                   6434:     }
                   6435:     return;
                   6436: }
                   6437: 
                   6438: sub course_group_datechecker {
                   6439:     my ($dates,$now,$status) = @_;
                   6440:     my ($start,$end) = split(/\./,$dates);
                   6441:     if (!$start && !$end) {
                   6442:         return 'ok';
                   6443:     }
                   6444:     if (grep/^active$/,@{$status}) {
                   6445:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6446:             return 'ok';
                   6447:         }
                   6448:     }
                   6449:     if (grep/^previous$/,@{$status}) {
                   6450:         if ($end > $now ) {
                   6451:             return 'ok';
                   6452:         }
                   6453:     }
                   6454:     if (grep/^future$/,@{$status}) {
                   6455:         if ($start > $now) {
                   6456:             return 'ok';
                   6457:         }
                   6458:     }
                   6459:     return; 
                   6460: }
                   6461: 
                   6462: sub parse_portfolio_url {
                   6463:     my ($url) = @_;
                   6464: 
                   6465:     my ($type,$udom,$unum,$group,$file_name);
                   6466:     
1.823     albertel 6467:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6468: 	$type = 1;
                   6469:         $udom = $1;
                   6470:         $unum = $2;
                   6471:         $file_name = $3;
1.823     albertel 6472:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6473: 	$type = 2;
                   6474:         $udom = $1;
                   6475:         $unum = $2;
                   6476:         $group = $3;
                   6477:         $file_name = $3.'/'.$4;
                   6478:     }
                   6479:     if (wantarray) {
                   6480: 	return ($type,$udom,$unum,$file_name,$group);
                   6481:     }
                   6482:     return $type;
                   6483: }
                   6484: 
                   6485: sub is_portfolio_url {
                   6486:     my ($url) = @_;
                   6487:     return scalar(&parse_portfolio_url($url));
                   6488: }
                   6489: 
1.798     raeburn  6490: sub is_portfolio_file {
                   6491:     my ($file) = @_;
1.820     raeburn  6492:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6493:         return 1;
                   6494:     }
                   6495:     return;
                   6496: }
                   6497: 
1.976     raeburn  6498: sub usertools_access {
1.1084    raeburn  6499:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6500:     my ($access,%tools);
                   6501:     if ($context eq '') {
                   6502:         $context = 'tools';
                   6503:     }
                   6504:     if ($context eq 'requestcourses') {
                   6505:         %tools = (
                   6506:                       official   => 1,
                   6507:                       unofficial => 1,
1.1006    raeburn  6508:                       community  => 1,
1.1172.2.37  raeburn  6509:                       textbook   => 1,
1.985     raeburn  6510:                  );
1.1172.2.9  raeburn  6511:     } elsif ($context eq 'requestauthor') {
                   6512:         %tools = (
                   6513:                       requestauthor => 1,
                   6514:                  );
1.985     raeburn  6515:     } else {
                   6516:         %tools = (
                   6517:                       aboutme   => 1,
                   6518:                       blog      => 1,
1.1172.2.6  raeburn  6519:                       webdav    => 1,
1.985     raeburn  6520:                       portfolio => 1,
                   6521:                  );
                   6522:     }
1.976     raeburn  6523:     return if (!defined($tools{$tool}));
                   6524: 
1.1172.2.35  raeburn  6525:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6526:         $udom = $env{'user.domain'};
                   6527:         $uname = $env{'user.name'};
                   6528:     }
                   6529: 
1.978     raeburn  6530:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6531:         if ($action ne 'reload') {
1.985     raeburn  6532:             if ($context eq 'requestcourses') {
                   6533:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6534:             } elsif ($context eq 'requestauthor') {
                   6535:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6536:             } else {
                   6537:                 return $env{'environment.availabletools.'.$tool};
                   6538:             }
                   6539:         }
1.976     raeburn  6540:     }
                   6541: 
1.1172.2.9  raeburn  6542:     my ($toolstatus,$inststatus,$envkey);
                   6543:     if ($context eq 'requestauthor') {
                   6544:         $envkey = $context;
                   6545:     } else {
                   6546:         $envkey = $context.'.'.$tool;
                   6547:     }
1.976     raeburn  6548: 
1.985     raeburn  6549:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6550:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6551:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6552:         $inststatus = $env{'environment.inststatus'};
                   6553:     } else {
1.1084    raeburn  6554:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6555:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6556:             $inststatus = $userenvref->{'inststatus'};
                   6557:         } else {
1.1172.2.9  raeburn  6558:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6559:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6560:             $inststatus = $userenv{'inststatus'};
                   6561:         }
1.976     raeburn  6562:     }
                   6563: 
                   6564:     if ($toolstatus ne '') {
                   6565:         if ($toolstatus) {
                   6566:             $access = 1;
                   6567:         } else {
                   6568:             $access = 0;
                   6569:         }
                   6570:         return $access;
                   6571:     }
                   6572: 
1.1084    raeburn  6573:     my ($is_adv,%domdef);
                   6574:     if (ref($is_advref) eq 'HASH') {
                   6575:         $is_adv = $is_advref->{'is_adv'};
                   6576:     } else {
                   6577:         $is_adv = &is_advanced_user($udom,$uname);
                   6578:     }
                   6579:     if (ref($domdefref) eq 'HASH') {
                   6580:         %domdef = %{$domdefref};
                   6581:     } else {
                   6582:         %domdef = &get_domain_defaults($udom);
                   6583:     }
1.976     raeburn  6584:     if (ref($domdef{$tool}) eq 'HASH') {
                   6585:         if ($is_adv) {
                   6586:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6587:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6588:                     $access = 1;
                   6589:                 } else {
                   6590:                     $access = 0;
                   6591:                 }
                   6592:                 return $access;
                   6593:             }
                   6594:         }
                   6595:         if ($inststatus ne '') {
                   6596:             my ($hasaccess,$hasnoaccess);
                   6597:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6598:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6599:                     if ($domdef{$tool}{$affiliation}) {
                   6600:                         $hasaccess = 1;
                   6601:                     } else {
                   6602:                         $hasnoaccess = 1;
                   6603:                     }
                   6604:                 }
                   6605:             }
                   6606:             if ($hasaccess || $hasnoaccess) {
                   6607:                 if ($hasaccess) {
                   6608:                     $access = 1;
                   6609:                 } elsif ($hasnoaccess) {
                   6610:                     $access = 0; 
                   6611:                 }
                   6612:                 return $access;
                   6613:             }
                   6614:         } else {
                   6615:             if ($domdef{$tool}{'default'} ne '') {
                   6616:                 if ($domdef{$tool}{'default'}) {
                   6617:                     $access = 1;
                   6618:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6619:                     $access = 0;
                   6620:                 }
                   6621:                 return $access;
                   6622:             }
                   6623:         }
                   6624:     } else {
1.1172.2.6  raeburn  6625:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6626:             $access = 1;
                   6627:         } else {
                   6628:             $access = 0;
                   6629:         }
1.976     raeburn  6630:         return $access;
                   6631:     }
                   6632: }
                   6633: 
1.1050    raeburn  6634: sub is_course_owner {
                   6635:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6636:     if (($udom eq '') || ($uname eq '')) {
                   6637:         $udom = $env{'user.domain'};
                   6638:         $uname = $env{'user.name'};
                   6639:     }
                   6640:     unless (($udom eq '') || ($uname eq '')) {
                   6641:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6642:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6643:                 return 1;
                   6644:             } else {
                   6645:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6646:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6647:                     return 1;
                   6648:                 }
                   6649:             }
                   6650:         }
                   6651:     }
                   6652:     return;
                   6653: }
                   6654: 
1.976     raeburn  6655: sub is_advanced_user {
                   6656:     my ($udom,$uname) = @_;
1.1085    raeburn  6657:     if ($udom ne '' && $uname ne '') {
                   6658:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6659:             if (wantarray) {
                   6660:                 return ($env{'user.adv'},$env{'user.author'});
                   6661:             } else {
                   6662:                 return $env{'user.adv'};
                   6663:             }
1.1085    raeburn  6664:         }
                   6665:     }
1.976     raeburn  6666:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6667:     my %allroles;
1.1128    raeburn  6668:     my ($is_adv,$is_author);
1.976     raeburn  6669:     foreach my $role (keys(%roleshash)) {
                   6670:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6671:         my $area = '/'.$tdomain.'/'.$trest;
                   6672:         if ($sec ne '') {
                   6673:             $area .= '/'.$sec;
                   6674:         }
                   6675:         if (($area ne '') && ($trole ne '')) {
                   6676:             my $spec=$trole.'.'.$area;
                   6677:             if ($trole =~ /^cr\//) {
                   6678:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6679:             } elsif ($trole ne 'gr') {
                   6680:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6681:             }
1.1128    raeburn  6682:             if ($trole eq 'au') {
                   6683:                 $is_author = 1;
                   6684:             }
1.976     raeburn  6685:         }
                   6686:     }
                   6687:     foreach my $role (keys(%allroles)) {
                   6688:         last if ($is_adv);
                   6689:         foreach my $item (split(/:/,$allroles{$role})) {
                   6690:             if ($item ne '') {
                   6691:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6692:                 if ($privilege eq 'adv') {
                   6693:                     $is_adv = 1;
                   6694:                     last;
                   6695:                 }
                   6696:             }
                   6697:         }
                   6698:     }
1.1128    raeburn  6699:     if (wantarray) {
                   6700:         return ($is_adv,$is_author);
                   6701:     }
1.976     raeburn  6702:     return $is_adv;
                   6703: }
1.798     raeburn  6704: 
1.1035    raeburn  6705: sub check_can_request {
1.1036    raeburn  6706:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6707:     my $canreq = 0;
                   6708:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6709:     my @options = ('approval','validate','autolimit');
                   6710:     my $optregex = join('|',@options);
                   6711:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6712:         foreach my $type (@{$types}) {
                   6713:             if (&usertools_access($env{'user.name'},
                   6714:                                   $env{'user.domain'},
                   6715:                                   $type,undef,'requestcourses')) {
                   6716:                 $canreq ++;
1.1036    raeburn  6717:                 if (ref($request_domains) eq 'HASH') {
                   6718:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6719:                 }
1.1035    raeburn  6720:                 if ($dom eq $env{'user.domain'}) {
                   6721:                     $can_request->{$type} = 1;
                   6722:                 }
                   6723:             }
                   6724:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6725:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6726:                 if (@curr > 0) {
1.1036    raeburn  6727:                     foreach my $item (@curr) {
                   6728:                         if (ref($request_domains) eq 'HASH') {
                   6729:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6730:                             if ($otherdom ne '') {
                   6731:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6732:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6733:                                         push(@{$request_domains->{$type}},$otherdom);
                   6734:                                     }
                   6735:                                 } else {
                   6736:                                     push(@{$request_domains->{$type}},$otherdom);
                   6737:                                 }
                   6738:                             }
                   6739:                         }
                   6740:                     }
                   6741:                     unless($dom eq $env{'user.domain'}) {
                   6742:                         $canreq ++;
1.1035    raeburn  6743:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6744:                             $can_request->{$type} = 1;
                   6745:                         }
                   6746:                     }
                   6747:                 }
                   6748:             }
                   6749:         }
                   6750:     }
                   6751:     return $canreq;
                   6752: }
                   6753: 
1.341     www      6754: # ---------------------------------------------- Custom access rule evaluation
                   6755: 
                   6756: sub customaccess {
                   6757:     my ($priv,$uri)=@_;
1.807     albertel 6758:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6759:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6760:     $udom = &LONCAPA::clean_domain($udom);
                   6761:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6762:     my $access=0;
1.800     albertel 6763:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6764: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6765: 	if ($type eq 'user') {
                   6766: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6767: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6768: 		if ($tdom) {
                   6769: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6770: 		}
1.896     albertel 6771: 		if ($tuname) {
                   6772: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6773: 		}
                   6774: 		$access=($effect eq 'allow');
                   6775: 		last;
                   6776: 	    }
                   6777: 	} else {
                   6778: 	    if ($role) {
                   6779: 		if ($role ne $urole) { next; }
                   6780: 	    }
                   6781: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6782: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6783: 		if ($tdom) {
                   6784: 		    if ($tdom ne $udom) { next; }
                   6785: 		}
                   6786: 		if ($tcrs) {
                   6787: 		    if ($tcrs ne $ucrs) { next; }
                   6788: 		}
                   6789: 		if ($tsec) {
                   6790: 		    if ($tsec ne $usec) { next; }
                   6791: 		}
                   6792: 		$access=($effect eq 'allow');
                   6793: 		last;
                   6794: 	    }
                   6795: 	    if ($realm eq '' && $role eq '') {
                   6796: 		$access=($effect eq 'allow');
                   6797: 	    }
1.402     bowersj2 6798: 	}
1.341     www      6799:     }
                   6800:     return $access;
                   6801: }
                   6802: 
1.103     harris41 6803: # ------------------------------------------------- Check for a user privilege
1.12      www      6804: 
                   6805: sub allowed {
1.1172.2.65  raeburn  6806:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6807:     my $ver_orguri=$uri;
1.439     www      6808:     $uri=&deversion($uri);
1.152     www      6809:     my $orguri=$uri;
1.52      www      6810:     $uri=&declutter($uri);
1.809     raeburn  6811: 
1.810     raeburn  6812:     if ($priv eq 'evb') {
                   6813: # Evade communication block restrictions for specified role in a course
                   6814:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6815:             return $1;
                   6816:         } else {
                   6817:             return;
                   6818:         }
                   6819:     }
                   6820: 
1.620     albertel 6821:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6822: # Free bre access to adm and meta resources
1.775     albertel 6823:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6824: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6825: 	&& ($priv eq 'bre')) {
1.14      www      6826: 	return 'F';
1.159     www      6827:     }
                   6828: 
1.545     banghart 6829: # Free bre access to user's own portfolio contents
1.714     raeburn  6830:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6831:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6832: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6833:         my %setters;
                   6834:         my ($startblock,$endblock) = 
                   6835:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6836:         if ($startblock && $endblock) {
                   6837:             return 'B';
                   6838:         } else {
                   6839:             return 'F';
                   6840:         }
1.545     banghart 6841:     }
                   6842: 
1.762     raeburn  6843: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6844:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6845:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6846:         if (exists($env{'request.course.id'})) {
                   6847:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6848:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6849:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6850:                 my $courseprivid=$env{'request.course.id'};
                   6851:                 $courseprivid=~s/\_/\//;
                   6852:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6853:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6854:                     return $1; 
1.762     raeburn  6855:                 } else {
                   6856:                     if ($env{'request.course.sec'}) {
                   6857:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6858:                     }
                   6859:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6860:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6861:                         return $2;
                   6862:                     }
1.714     raeburn  6863:                 }
                   6864:             }
                   6865:         }
                   6866:     }
                   6867: 
1.159     www      6868: # Free bre to public access
                   6869: 
                   6870:     if ($priv eq 'bre') {
1.238     www      6871:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6872: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6873:            return 'F'; 
                   6874:         }
1.238     www      6875:         if ($copyright eq 'priv') {
                   6876:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6877: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6878: 		return '';
                   6879:             }
                   6880:         }
                   6881:         if ($copyright eq 'domain') {
                   6882:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6883: 	    unless (($env{'user.domain'} eq $1) ||
                   6884:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6885: 		return '';
                   6886:             }
1.262     matthew  6887:         }
1.620     albertel 6888:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6889:             # Library role, so allow browsing of resources in this domain.
                   6890:             return 'F';
1.238     www      6891:         }
1.341     www      6892:         if ($copyright eq 'custom') {
                   6893: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6894:         }
1.14      www      6895:     }
1.264     matthew  6896:     # Domain coordinator is trying to create a course
1.620     albertel 6897:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6898:         # uri is the requested domain in this case.
                   6899:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6900:         # a role of dc for the domain in question.
1.620     albertel 6901:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6902:     }
1.29      www      6903: 
1.52      www      6904:     my $thisallowed='';
                   6905:     my $statecond=0;
                   6906:     my $courseprivid='';
                   6907: 
1.1039    raeburn  6908:     my $ownaccess;
1.1043    raeburn  6909:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6910:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6911:         if ($uri eq '') {
                   6912:             $ownaccess = 1;
                   6913:         } else {
                   6914:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6915:                 my $udom = $env{'user.domain'};
                   6916:                 my $uname = $env{'user.name'};
                   6917:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6918:                     $ownaccess = 1;
1.1040    raeburn  6919:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6920:                     unless ($uri =~ m{\.\./}) {
                   6921:                         $ownaccess = 1;
                   6922:                     }
                   6923:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6924:                     my $now = time;
                   6925:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6926:                         my $adom = $1;
                   6927:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6928:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6929:                                 my ($start,$end) = split('.',$env{$key});
                   6930:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6931:                                     $ownaccess = 1;
                   6932:                                     last;
                   6933:                                 }
                   6934:                             }
                   6935:                         }
                   6936:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6937:                         my $adom = $1;
                   6938:                         my $aname = $2;
1.1042    raeburn  6939:                         foreach my $role ('ca','aa') { 
                   6940:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6941:                                 my ($start,$end) =
                   6942:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6943:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6944:                                     $ownaccess = 1;
                   6945:                                     last;
                   6946:                                 }
1.1039    raeburn  6947:                             }
                   6948:                         }
                   6949:                     }
                   6950:                 }
                   6951:             }
                   6952:         }
                   6953:     }
                   6954: 
1.52      www      6955: # Course
                   6956: 
1.620     albertel 6957:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6958:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6959:             $thisallowed.=$1;
                   6960:         }
1.52      www      6961:     }
1.29      www      6962: 
1.52      www      6963: # Domain
                   6964: 
1.620     albertel 6965:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6966:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6967:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6968:             $thisallowed.=$1;
                   6969:         }
1.12      www      6970:     }
1.52      www      6971: 
1.1141    raeburn  6972: # User who is not author or co-author might still be able to edit
                   6973: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6974:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6975:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6976:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6977:             $thisallowed.=$1;
                   6978:         }
                   6979:     }
                   6980: 
1.52      www      6981: # Course: uri itself is a course
1.66      www      6982:     my $courseuri=$uri;
                   6983:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6984:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6985: 
1.620     albertel 6986:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6987:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6988:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6989:             $thisallowed.=$1;
                   6990:         }
1.12      www      6991:     }
1.29      www      6992: 
1.665     albertel 6993: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6994: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6995:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6996: 	$thisallowed='';
1.671     raeburn  6997:         my ($match)=&is_on_map($uri);
                   6998:         if ($match) {
                   6999:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7000:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7001:                 my $value = $1;
                   7002:                 if ($noblockcheck) {
                   7003:                     $thisallowed.=$value;
1.1162    raeburn  7004:                 } else {
1.1172.2.65  raeburn  7005:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7006:                     if (@blockers > 0) {
                   7007:                         $thisallowed = 'B';
                   7008:                     } else {
                   7009:                         $thisallowed.=$value;
                   7010:                     }
1.1162    raeburn  7011:                 }
1.671     raeburn  7012:             }
                   7013:         } else {
1.705     albertel 7014:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7015:             if ($refuri) {
                   7016:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7017:                     $thisallowed='F';
1.671     raeburn  7018:                 } else {
                   7019:                     $refuri=&declutter($refuri);
                   7020:                     my ($match) = &is_on_map($refuri);
                   7021:                     if ($match) {
1.1172.2.65  raeburn  7022:                         if ($noblockcheck) {
1.1162    raeburn  7023:                             $thisallowed='F';
1.1172.2.65  raeburn  7024:                         } else {
                   7025:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7026:                             if (@blockers > 0) {
                   7027:                                 $thisallowed = 'B';
                   7028:                             } else {
                   7029:                                 $thisallowed='F';
                   7030:                             }
1.1162    raeburn  7031:                         }
1.671     raeburn  7032:                     }
1.669     raeburn  7033:                 }
1.671     raeburn  7034:             }
                   7035:         }
1.314     www      7036:     }
1.492     albertel 7037: 
1.766     albertel 7038:     if ($priv eq 'bre'
                   7039: 	&& $thisallowed ne 'F' 
                   7040: 	&& $thisallowed ne '2'
                   7041: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7042: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7043:     }
                   7044:     
1.52      www      7045: # Full access at system, domain or course-wide level? Exit.
1.29      www      7046:     if ($thisallowed=~/F/) {
                   7047: 	return 'F';
                   7048:     }
                   7049: 
1.52      www      7050: # If this is generating or modifying users, exit with special codes
1.29      www      7051: 
1.643     www      7052:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7053: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7054: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7055: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7056: 	    unless ($auname) { return $thisallowed; }
                   7057: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7058: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7059: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7060: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7061: 	}
1.52      www      7062: 	return $thisallowed;
                   7063:     }
                   7064: #
1.103     harris41 7065: # Gathered so far: system, domain and course wide privileges
1.52      www      7066: #
                   7067: # Course: See if uri or referer is an individual resource that is part of 
                   7068: # the course
                   7069: 
1.620     albertel 7070:     if ($env{'request.course.id'}) {
1.232     www      7071: 
1.620     albertel 7072:        $courseprivid=$env{'request.course.id'};
                   7073:        if ($env{'request.course.sec'}) {
                   7074:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7075:        }
                   7076:        $courseprivid=~s/\_/\//;
                   7077:        my $checkreferer=1;
1.232     www      7078:        my ($match,$cond)=&is_on_map($uri);
                   7079:        if ($match) {
                   7080:            $statecond=$cond;
1.620     albertel 7081:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7082:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7083:                my $value = $1;
                   7084:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7085:                    if ($noblockcheck) {
1.1162    raeburn  7086:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7087:                    } else {
                   7088:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7089:                        if (@blockers > 0) {
                   7090:                            $thisallowed = 'B';
                   7091:                        } else {
                   7092:                            $thisallowed.=$value;
                   7093:                        }
1.1162    raeburn  7094:                    }
                   7095:                } else {
                   7096:                    $thisallowed.=$value;
                   7097:                }
1.52      www      7098:                $checkreferer=0;
                   7099:            }
1.29      www      7100:        }
1.83      www      7101:        
1.148     www      7102:        if ($checkreferer) {
1.620     albertel 7103: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7104:             unless ($refuri) {
1.800     albertel 7105:                 foreach my $key (keys(%env)) {
                   7106: 		    if ($key=~/^httpref\..*\*/) {
                   7107: 			my $pattern=$key;
1.156     www      7108:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7109:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7110:                         $pattern=~s/\//\\\//g;
1.152     www      7111:                         if ($orguri=~/$pattern/) {
1.800     albertel 7112: 			    $refuri=$env{$key};
1.148     www      7113:                         }
                   7114:                     }
1.191     harris41 7115:                 }
1.148     www      7116:             }
1.232     www      7117: 
1.148     www      7118:          if ($refuri) { 
1.152     www      7119: 	  $refuri=&declutter($refuri);
1.232     www      7120:           my ($match,$cond)=&is_on_map($refuri);
                   7121:             if ($match) {
                   7122:               my $refstatecond=$cond;
1.620     albertel 7123:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7124:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7125:                   my $value = $1;
                   7126:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7127:                       if ($noblockcheck) {
1.1162    raeburn  7128:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7129:                       } else {
                   7130:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7131:                           if (@blockers > 0) {
                   7132:                               $thisallowed = 'B';
                   7133:                           } else {
                   7134:                               $thisallowed.=$value;
                   7135:                           }
1.1162    raeburn  7136:                       }
                   7137:                   } else {
                   7138:                       $thisallowed.=$value;
                   7139:                   }
1.53      www      7140:                   $uri=$refuri;
                   7141:                   $statecond=$refstatecond;
1.52      www      7142:               }
                   7143:           }
1.148     www      7144:         }
1.29      www      7145:        }
1.52      www      7146:    }
1.29      www      7147: 
1.52      www      7148: #
1.103     harris41 7149: # Gathered now: all privileges that could apply, and condition number
1.52      www      7150: # 
                   7151: #
                   7152: # Full or no access?
                   7153: #
1.29      www      7154: 
1.52      www      7155:     if ($thisallowed=~/F/) {
                   7156: 	return 'F';
                   7157:     }
1.29      www      7158: 
1.52      www      7159:     unless ($thisallowed) {
                   7160:         return '';
                   7161:     }
1.29      www      7162: 
1.52      www      7163: # Restrictions exist, deal with them
                   7164: #
                   7165: #   C:according to course preferences
                   7166: #   R:according to resource settings
                   7167: #   L:unless locked
                   7168: #   X:according to user session state
                   7169: #
                   7170: 
                   7171: # Possibly locked functionality, check all courses
1.54      www      7172: # Locks might take effect only after 10 minutes cache expiration for other
                   7173: # courses, and 2 minutes for current course
1.52      www      7174: 
                   7175:     my $envkey;
                   7176:     if ($thisallowed=~/L/) {
1.1000    raeburn  7177:         foreach $envkey (keys(%env)) {
1.54      www      7178:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7179:                my $courseid=$2;
                   7180:                my $roleid=$1.'.'.$2;
1.92      www      7181:                $courseid=~s/^\///;
1.54      www      7182:                my $expiretime=600;
1.620     albertel 7183:                if ($env{'request.role'} eq $roleid) {
1.54      www      7184: 		  $expiretime=120;
                   7185:                }
                   7186: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7187:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7188:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7189: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7190:                }
1.620     albertel 7191:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7192:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7193: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7194:                        &log($env{'user.domain'},$env{'user.name'},
                   7195:                             $env{'user.home'},
1.57      www      7196:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7197:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7198:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7199: 		       return '';
                   7200:                    }
                   7201:                }
1.620     albertel 7202:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7203:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7204: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7205:                        &log($env{'user.domain'},$env{'user.name'},
                   7206:                             $env{'user.home'},
1.57      www      7207:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7208:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7209:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7210: 		       return '';
                   7211:                    }
                   7212:                }
                   7213: 	   }
1.29      www      7214:        }
1.52      www      7215:     }
                   7216:    
                   7217: #
                   7218: # Rest of the restrictions depend on selected course
                   7219: #
                   7220: 
1.620     albertel 7221:     unless ($env{'request.course.id'}) {
1.766     albertel 7222: 	if ($thisallowed eq 'A') {
                   7223: 	    return 'A';
1.814     raeburn  7224:         } elsif ($thisallowed eq 'B') {
                   7225:             return 'B';
1.766     albertel 7226: 	} else {
                   7227: 	    return '1';
                   7228: 	}
1.52      www      7229:     }
1.29      www      7230: 
1.52      www      7231: #
                   7232: # Now user is definitely in a course
                   7233: #
1.53      www      7234: 
                   7235: 
                   7236: # Course preferences
                   7237: 
                   7238:    if ($thisallowed=~/C/) {
1.620     albertel 7239:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7240:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7241:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7242: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7243: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7244: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7245: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7246: 			$env{'request.course.id'});
                   7247: 	   }
1.237     www      7248:            return '';
                   7249:        }
                   7250: 
1.620     albertel 7251:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7252: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7253: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7254: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7255: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7256: 			$env{'request.course.id'});
                   7257: 	   }
1.54      www      7258:            return '';
                   7259:        }
1.53      www      7260:    }
                   7261: 
                   7262: # Resource preferences
                   7263: 
                   7264:    if ($thisallowed=~/R/) {
1.620     albertel 7265:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7266:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7267: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7268: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7269: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7270: 	   }
                   7271: 	   return '';
1.54      www      7272:        }
1.53      www      7273:    }
1.30      www      7274: 
1.246     www      7275: # Restricted by state or randomout?
1.30      www      7276: 
1.52      www      7277:    if ($thisallowed=~/X/) {
1.620     albertel 7278:       if ($env{'acc.randomout'}) {
1.579     albertel 7279: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7280:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7281:             return ''; 
                   7282:          }
1.247     www      7283:       }
                   7284:       if (&condval($statecond)) {
1.52      www      7285: 	 return '2';
                   7286:       } else {
                   7287:          return '';
                   7288:       }
                   7289:    }
1.30      www      7290: 
1.766     albertel 7291:     if ($thisallowed eq 'A') {
                   7292: 	return 'A';
1.814     raeburn  7293:     } elsif ($thisallowed eq 'B') {
                   7294:         return 'B';
1.766     albertel 7295:     }
1.52      www      7296:    return 'F';
1.232     www      7297: }
1.1162    raeburn  7298: 
1.1172.2.13  raeburn  7299: # ------------------------------------------- Check construction space access
                   7300: 
                   7301: sub constructaccess {
                   7302:     my ($url,$setpriv)=@_;
                   7303: 
                   7304: # We do not allow editing of previous versions of files
                   7305:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7306: 
                   7307: # Get username and domain from URL
                   7308:     my ($ownername,$ownerdomain,$ownerhome);
                   7309: 
                   7310:     ($ownerdomain,$ownername) =
                   7311:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7312: 
                   7313: # The URL does not really point to any authorspace, forget it
                   7314:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7315: 
                   7316: # Now we need to see if the user has access to the authorspace of
                   7317: # $ownername at $ownerdomain
                   7318: 
                   7319:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7320: # Real author for this?
                   7321:        $ownerhome = $env{'user.home'};
                   7322:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7323:           return ($ownername,$ownerdomain,$ownerhome);
                   7324:        }
                   7325:     } else {
                   7326: # Co-author for this?
                   7327:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7328:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7329:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7330:             return ($ownername,$ownerdomain,$ownerhome);
                   7331:         }
                   7332:     }
                   7333: 
                   7334: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7335: # we might as well leave
                   7336:    unless ($setpriv) { return ''; }
                   7337: 
                   7338: # Backdoor access?
                   7339:     my $allowed=&allowed('eco',$ownerdomain);
                   7340: # Nope
                   7341:     unless ($allowed) { return ''; }
                   7342: # Looks like we may have access, but could be locked by the owner of the construction space
                   7343:     if ($allowed eq 'U') {
                   7344:         my %blocked=&get('environment',['domcoord.author'],
                   7345:                          $ownerdomain,$ownername);
                   7346: # Is blocked by owner
                   7347:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7348:     }
                   7349:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7350: # Grant temporary access
                   7351:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7352:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7353:         if (!$update) { $update = $then; }
                   7354:         my $refresh=$env{'user.refresh.time'};
                   7355:         if (!$refresh) { $refresh = $update; }
                   7356:         my $now = time;
                   7357:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7358:                            $now,'ca','constructaccess');
                   7359:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7360:         return($ownername,$ownerdomain,$ownerhome);
                   7361:     }
                   7362: # No business here
                   7363:     return '';
                   7364: }
                   7365: 
1.1172.2.66  raeburn  7366: # ----------------------------------------------------------- Content Blocking
                   7367: 
                   7368: {
                   7369: # Caches for faster Course Contents display where content blocking
                   7370: # is in operation (i.e., interval param set) for timed quiz.
                   7371: #
                   7372: # User for whom data are being temporarily cached.
                   7373: my $cacheduser='';
                   7374: # Cached blockers for this user (a hash of blocking items).
                   7375: my %cachedblockers=();
                   7376: # When the data were last cached.
                   7377: my $cachedlast='';
                   7378: 
                   7379: sub load_all_blockers {
                   7380:     my ($uname,$udom,$blocks)=@_;
                   7381:     if (($uname ne '') && ($udom ne '')) {
                   7382:         if (($cacheduser eq $uname.':'.$udom) &&
                   7383:             (abs($cachedlast-time)<5)) {
                   7384:             return;
                   7385:         }
                   7386:     }
                   7387:     $cachedlast=time;
                   7388:     $cacheduser=$uname.':'.$udom;
                   7389:     %cachedblockers = &get_commblock_resources($blocks);
                   7390: }
                   7391: 
1.1162    raeburn  7392: sub get_comm_blocks {
                   7393:     my ($cdom,$cnum) = @_;
                   7394:     if ($cdom eq '' || $cnum eq '') {
                   7395:         return unless ($env{'request.course.id'});
                   7396:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7397:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7398:     }
                   7399:     my %commblocks;
                   7400:     my $hashid=$cdom.'_'.$cnum;
                   7401:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7402:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7403:         %commblocks = %{$blocksref};
                   7404:     } else {
                   7405:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7406:         my $cachetime = 600;
                   7407:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7408:     }
                   7409:     return %commblocks;
                   7410: }
                   7411: 
1.1172.2.66  raeburn  7412: sub get_commblock_resources {
                   7413:     my ($blocks) = @_;
                   7414:     my %blockers = ();
                   7415:     return %blockers unless ($env{'request.course.id'});
                   7416:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7417:     my %commblocks;
                   7418:     if (ref($blocks) eq 'HASH') {
                   7419:         %commblocks = %{$blocks};
                   7420:     } else {
                   7421:         %commblocks = &get_comm_blocks();
                   7422:     }
1.1172.2.66  raeburn  7423:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  7424:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  7425:     return %blockers unless (ref($navmap));
                   7426:     my $now = time;
1.1162    raeburn  7427:     foreach my $block (keys(%commblocks)) {
                   7428:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7429:             my ($start,$end) = ($1,$2);
                   7430:             if ($start <= $now && $end >= $now) {
                   7431:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7432:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7433:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  7434:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7435:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  7436:                             }
                   7437:                         }
                   7438:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  7439:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7440:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7441:                             }
                   7442:                         }
                   7443:                     }
                   7444:                 }
                   7445:             }
                   7446:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7447:             my $item = $1;
1.1163    raeburn  7448:             my @to_test;
1.1162    raeburn  7449:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7450:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  7451:                     my @interval;
                   7452:                     my $type = 'map';
                   7453:                     if ($item eq 'course') {
                   7454:                         $type = 'course';
                   7455:                         @interval=&EXT("resource.0.interval");
                   7456:                     } else {
                   7457:                         if ($item =~ /___\d+___/) {
                   7458:                             $type = 'resource';
                   7459:                             @interval=&EXT("resource.0.interval",$item);
                   7460:                             if (ref($navmap)) {
                   7461:                                 my $res = $navmap->getBySymb($item);
                   7462:                                 push(@to_test,$res);
                   7463:                             }
1.1162    raeburn  7464:                         } else {
1.1172.2.66  raeburn  7465:                             my $mapsymb = &symbread($item,1);
                   7466:                             if ($mapsymb) {
                   7467:                                 if (ref($navmap)) {
                   7468:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7469:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7470:                                     foreach my $res (@to_test) {
                   7471:                                         my $symb = $res->symb();
                   7472:                                         next if ($symb eq $mapsymb);
                   7473:                                         if ($symb ne '') {
                   7474:                                             @interval=&EXT("resource.0.interval",$symb);
                   7475:                                             if ($interval[1] eq 'map') {
                   7476:                                                 last;
1.1162    raeburn  7477:                                             }
                   7478:                                         }
                   7479:                                     }
                   7480:                                 }
                   7481:                             }
                   7482:                         }
1.1172.2.66  raeburn  7483:                     }
                   7484:                     if ($interval[0] =~ /^\d+$/) {
                   7485:                         my $first_access;
                   7486:                         if ($type eq 'resource') {
                   7487:                             $first_access=&get_first_access($interval[1],$item);
                   7488:                         } elsif ($type eq 'map') {
                   7489:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7490:                         } else {
                   7491:                             $first_access=&get_first_access($interval[1]);
                   7492:                         }
                   7493:                         if ($first_access) {
                   7494:                             my $timesup = $first_access+$interval[0];
                   7495:                             if ($timesup > $now) {
                   7496:                                 my $activeblock;
                   7497:                                 foreach my $res (@to_test) {
                   7498:                                     if ($res->answerable()) {
                   7499:                                         $activeblock = 1;
                   7500:                                         last;
                   7501:                                     }
                   7502:                                 }
                   7503:                                 if ($activeblock) {
                   7504:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7505:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7506:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7507:                                          }
                   7508:                                     }
                   7509:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7510:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7511:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7512:                                         }
1.1162    raeburn  7513:                                     }
                   7514:                                 }
                   7515:                             }
                   7516:                         }
                   7517:                     }
                   7518:                 }
                   7519:             }
                   7520:         }
                   7521:     }
1.1172.2.66  raeburn  7522:     return %blockers;
1.1162    raeburn  7523: }
                   7524: 
1.1172.2.66  raeburn  7525: sub has_comm_blocking {
                   7526:     my ($priv,$symb,$uri,$blocks) = @_;
                   7527:     my @blockers;
                   7528:     return unless ($env{'request.course.id'});
                   7529:     return unless ($priv eq 'bre');
                   7530:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7531:     return if ($env{'request.state'} eq 'construct');
                   7532:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7533:     return unless (keys(%cachedblockers) > 0);
                   7534:     my (%possibles,@symbs);
                   7535:     if (!$symb) {
                   7536:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7537:     }
1.1172.2.66  raeburn  7538:     if ($symb) {
                   7539:         @symbs = ($symb);
                   7540:     } elsif (keys(%possibles)) {
                   7541:         @symbs = keys(%possibles);
                   7542:     }
                   7543:     my $noblock;
                   7544:     foreach my $symb (@symbs) {
                   7545:         last if ($noblock);
                   7546:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7547:         foreach my $block (keys(%cachedblockers)) {
                   7548:             if ($block =~ /^firstaccess____(.+)$/) {
                   7549:                 my $item = $1;
                   7550:                 if (($item eq $map) || ($item eq $symb)) {
                   7551:                     $noblock = 1;
                   7552:                     last;
                   7553:                 }
1.1162    raeburn  7554:             }
1.1172.2.66  raeburn  7555:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7556:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7557:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7558:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7559:                             push(@blockers,$block);
                   7560:                         }
                   7561:                     }
                   7562:                 }
                   7563:             }
                   7564:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7565:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7566:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7567:                         push(@blockers,$block);
                   7568:                     }
                   7569:                 }
1.1162    raeburn  7570:             }
                   7571:         }
                   7572:     }
1.1172.2.66  raeburn  7573:     return if ($noblock);
                   7574:     return @blockers;
                   7575: }
1.1162    raeburn  7576: }
                   7577: 
1.1172.2.66  raeburn  7578: # -------------------------------- Deversion and split uri into path an filename
                   7579: 
1.1133    foxr     7580: #
1.1172.2.66  raeburn  7581: #   Removes the version from a URI and
1.1133    foxr     7582: #   splits it in to its filename and path to the filename.
                   7583: #   Seems like File::Basename could have done this more clearly.
                   7584: #   Parameters:
                   7585: #      $uri   - input URI
                   7586: #   Returns:
                   7587: #     Two element list consisting of 
                   7588: #     $pathname  - the URI up to and excluding the trailing /
                   7589: #     $filename  - The part of the URI following the last /
                   7590: #  NOTE:
                   7591: #    Another realization of this is simply:
                   7592: #    use File::Basename;
                   7593: #    ...
                   7594: #    $uri = shift;
                   7595: #    $filename = basename($uri);
                   7596: #    $path     = dirname($uri);
                   7597: #    return ($filename, $path);
                   7598: #
                   7599: #     The implementation below is probably faster however.
                   7600: #
1.710     albertel 7601: sub split_uri_for_cond {
                   7602:     my $uri=&deversion(&declutter(shift));
                   7603:     my @uriparts=split(/\//,$uri);
                   7604:     my $filename=pop(@uriparts);
                   7605:     my $pathname=join('/',@uriparts);
                   7606:     return ($pathname,$filename);
                   7607: }
1.232     www      7608: # --------------------------------------------------- Is a resource on the map?
                   7609: 
                   7610: sub is_on_map {
1.710     albertel 7611:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7612:     #Trying to find the conditional for the file
1.620     albertel 7613:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7614: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7615:     if ($match) {
1.289     bowersj2 7616: 	return (1,$1);
                   7617:     } else {
1.434     www      7618: 	return (0,0);
1.289     bowersj2 7619:     }
1.12      www      7620: }
                   7621: 
1.427     www      7622: # --------------------------------------------------------- Get symb from alias
                   7623: 
                   7624: sub get_symb_from_alias {
                   7625:     my $symb=shift;
                   7626:     my ($map,$resid,$url)=&decode_symb($symb);
                   7627: # Already is a symb
                   7628:     if ($url) { return $symb; }
                   7629: # Must be an alias
                   7630:     my $aliassymb='';
                   7631:     my %bighash;
1.620     albertel 7632:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7633:                             &GDBM_READER(),0640)) {
                   7634:         my $rid=$bighash{'mapalias_'.$symb};
                   7635: 	if ($rid) {
                   7636: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7637: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7638: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7639: 	}
                   7640:         untie %bighash;
                   7641:     }
                   7642:     return $aliassymb;
                   7643: }
                   7644: 
1.12      www      7645: # ----------------------------------------------------------------- Define Role
                   7646: 
                   7647: sub definerole {
                   7648:   if (allowed('mcr','/')) {
                   7649:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7650:     foreach my $role (split(':',$sysrole)) {
                   7651: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7652:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7653:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7654: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7655:                return "refused:s:$crole&$cqual"; 
                   7656:             }
                   7657:         }
1.191     harris41 7658:     }
1.800     albertel 7659:     foreach my $role (split(':',$domrole)) {
                   7660: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7661:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7662:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7663: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7664:                return "refused:d:$crole&$cqual"; 
                   7665:             }
                   7666:         }
1.191     harris41 7667:     }
1.800     albertel 7668:     foreach my $role (split(':',$courole)) {
                   7669: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7670:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7671:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7672: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7673:                return "refused:c:$crole&$cqual"; 
                   7674:             }
                   7675:         }
1.191     harris41 7676:     }
1.620     albertel 7677:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7678:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7679: 	        "rolesdef_$rolename=".
                   7680:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7681:     return reply($command,$env{'user.home'});
1.12      www      7682:   } else {
                   7683:     return 'refused';
                   7684:   }
1.105     harris41 7685: }
                   7686: 
                   7687: # ---------------- Make a metadata query against the network of library servers
                   7688: 
                   7689: sub metadata_query {
1.1172.2.33  raeburn  7690:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7691:     my %rhash;
1.845     albertel 7692:     my %libserv = &all_library();
1.244     matthew  7693:     my @server_list = (defined($server_array) ? @$server_array
                   7694:                                               : keys(%libserv) );
                   7695:     for my $server (@server_list) {
1.1172.2.33  raeburn  7696:         my $domains = '';
                   7697:         if (ref($domains_hash) eq 'HASH') {
                   7698:             $domains = $domains_hash->{$server};    
                   7699:         }
1.118     harris41 7700: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  7701: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7702: 	    $rhash{$server}=$reply;
                   7703: 	}
                   7704: 	else {
                   7705: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  7706: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7707: 			     $server);
                   7708: 	    $rhash{$server}=$reply;
                   7709: 	}
1.112     harris41 7710:     }
1.118     harris41 7711:     return \%rhash;
1.240     www      7712: }
                   7713: 
                   7714: # ----------------------------------------- Send log queries and wait for reply
                   7715: 
                   7716: sub log_query {
                   7717:     my ($uname,$udom,$query,%filters)=@_;
                   7718:     my $uhome=&homeserver($uname,$udom);
                   7719:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7720:     my $uhost=&hostname($uhome);
1.800     albertel 7721:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7722:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7723:                        $uhome);
1.479     albertel 7724:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7725:     return get_query_reply($queryid);
                   7726: }
                   7727: 
1.818     raeburn  7728: # -------------------------- Update MySQL table for portfolio file
                   7729: 
                   7730: sub update_portfolio_table {
1.821     raeburn  7731:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7732:     if ($group ne '') {
                   7733:         $file_name =~s /^\Q$group\E//;
                   7734:     }
1.818     raeburn  7735:     my $homeserver = &homeserver($uname,$udom);
                   7736:     my $queryid=
1.821     raeburn  7737:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7738:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7739:     my $reply = &get_query_reply($queryid);
                   7740:     return $reply;
                   7741: }
                   7742: 
1.899     raeburn  7743: # -------------------------- Update MySQL allusers table
                   7744: 
                   7745: sub update_allusers_table {
                   7746:     my ($uname,$udom,$names) = @_;
                   7747:     my $homeserver = &homeserver($uname,$udom);
                   7748:     my $queryid=
                   7749:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7750:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7751:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7752:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7753:                'generation='.&escape($names->{'generation'}).'%%'.
                   7754:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7755:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7756:     return;
1.899     raeburn  7757: }
                   7758: 
1.508     raeburn  7759: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7760: 
                   7761: sub fetch_enrollment_query {
1.511     raeburn  7762:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  7763:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  7764:     my $maxtries = 1;
1.508     raeburn  7765:     if ($context eq 'automated') {
                   7766:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  7767:         $sleep = 2;
                   7768:         $loopmax = 100;
1.547     raeburn  7769:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7770:     } else {
                   7771:         $homeserver = &homeserver($cnum,$dom);
                   7772:     }
1.838     albertel 7773:     my $host=&hostname($homeserver);
1.506     raeburn  7774:     my $cmd = '';
1.1000    raeburn  7775:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7776:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7777:     }
                   7778:     $cmd =~ s/%%$//;
                   7779:     $cmd = &escape($cmd);
                   7780:     my $query = 'fetchenrollment';
1.620     albertel 7781:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7782:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7783:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7784:         return 'error: '.$queryid;
                   7785:     }
1.1172.2.79  raeburn  7786:     my $reply = &get_query_reply($queryid,$sleep.$loopmax);
1.547     raeburn  7787:     my $tries = 1;
                   7788:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  7789:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  7790:         $tries ++;
                   7791:     }
1.526     raeburn  7792:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7793:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7794:     } else {
1.901     albertel 7795:         my @responses = split(/:/,$reply);
1.515     raeburn  7796:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7797:             foreach my $line (@responses) {
                   7798:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7799:                 $$replyref{$key} = $value;
                   7800:             }
                   7801:         } else {
1.1117    foxr     7802:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7803:             foreach my $line (@responses) {
                   7804:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7805:                 $$replyref{$key} = $value;
                   7806:                 if ($value > 0) {
1.800     albertel 7807:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7808:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7809:                         my $destname = $pathname.'/'.$filename;
                   7810:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7811:                         if ($xml_classlist =~ /^error/) {
                   7812:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7813:                         } else {
1.506     raeburn  7814:                             if ( open(FILE,">$destname") ) {
                   7815:                                 print FILE &unescape($xml_classlist);
                   7816:                                 close(FILE);
1.526     raeburn  7817:                             } else {
                   7818:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7819:                             }
                   7820:                         }
                   7821:                     }
                   7822:                 }
                   7823:             }
                   7824:         }
                   7825:         return 'ok';
                   7826:     }
                   7827:     return 'error';
                   7828: }
                   7829: 
1.242     www      7830: sub get_query_reply {
1.1172.2.79  raeburn  7831:     my ($queryid,$sleep,$loopmax) = @_;
                   7832:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   7833:         $sleep = 0.2;
                   7834:     }
                   7835:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   7836:         $loopmax = 100;
                   7837:     }
1.1117    foxr     7838:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7839:     my $reply='';
1.1172.2.79  raeburn  7840:     for (1..$loopmax) {
                   7841: 	sleep($sleep);
1.240     www      7842:         if (-e $replyfile.'.end') {
1.448     albertel 7843: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7844: 		$reply = join('',<$fh>);
                   7845: 		close($fh);
1.240     www      7846: 	   } else { return 'error: reply_file_error'; }
1.242     www      7847:            return &unescape($reply);
                   7848: 	}
1.240     www      7849:     }
1.242     www      7850:     return 'timeout:'.$queryid;
1.240     www      7851: }
                   7852: 
                   7853: sub courselog_query {
1.241     www      7854: #
                   7855: # possible filters:
                   7856: # url: url or symb
                   7857: # username
                   7858: # domain
                   7859: # action: view, submit, grade
                   7860: # start: timestamp
                   7861: # end: timestamp
                   7862: #
1.240     www      7863:     my (%filters)=@_;
1.620     albertel 7864:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7865:     if ($filters{'url'}) {
                   7866: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7867:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7868:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7869:     }
1.620     albertel 7870:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7871:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7872:     return &log_query($cname,$cdom,'courselog',%filters);
                   7873: }
                   7874: 
                   7875: sub userlog_query {
1.858     raeburn  7876: #
                   7877: # possible filters:
                   7878: # action: log check role
                   7879: # start: timestamp
                   7880: # end: timestamp
                   7881: #
1.240     www      7882:     my ($uname,$udom,%filters)=@_;
                   7883:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7884: }
                   7885: 
1.506     raeburn  7886: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7887: 
                   7888: sub auto_run {
1.508     raeburn  7889:     my ($cnum,$cdom) = @_;
1.876     raeburn  7890:     my $response = 0;
                   7891:     my $settings;
                   7892:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7893:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7894:         $settings = $domconfig{'autoenroll'};
                   7895:         if ($settings->{'run'} eq '1') {
                   7896:             $response = 1;
                   7897:         }
                   7898:     } else {
1.934     raeburn  7899:         my $homeserver;
                   7900:         if (&is_course($cdom,$cnum)) {
                   7901:             $homeserver = &homeserver($cnum,$cdom);
                   7902:         } else {
                   7903:             $homeserver = &domain($cdom,'primary');
                   7904:         }
                   7905:         if ($homeserver ne 'no_host') {
                   7906:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7907:         }
1.876     raeburn  7908:     }
1.506     raeburn  7909:     return $response;
                   7910: }
1.776     albertel 7911: 
1.506     raeburn  7912: sub auto_get_sections {
1.508     raeburn  7913:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7914:     my $homeserver;
                   7915:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7916:         $homeserver = &homeserver($cnum,$cdom);
                   7917:     }
                   7918:     if (!defined($homeserver)) { 
                   7919:         if ($cdom =~ /^$match_domain$/) {
                   7920:             $homeserver = &domain($cdom,'primary');
                   7921:         }
                   7922:     }
                   7923:     my @secs;
                   7924:     if (defined($homeserver)) {
                   7925:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7926:         unless ($response eq 'refused') {
                   7927:             @secs = split(/:/,$response);
                   7928:         }
1.506     raeburn  7929:     }
                   7930:     return @secs;
                   7931: }
1.776     albertel 7932: 
1.506     raeburn  7933: sub auto_new_course {
1.1099    raeburn  7934:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7935:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7936:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7937:     return $response;
                   7938: }
1.776     albertel 7939: 
1.506     raeburn  7940: sub auto_validate_courseID {
1.508     raeburn  7941:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7942:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7943:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7944:     return $response;
                   7945: }
1.776     albertel 7946: 
1.1007    raeburn  7947: sub auto_validate_instcode {
1.1020    raeburn  7948:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7949:     my ($homeserver,$response);
                   7950:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7951:         $homeserver = &homeserver($cnum,$cdom);
                   7952:     }
                   7953:     if (!defined($homeserver)) {
                   7954:         if ($cdom =~ /^$match_domain$/) {
                   7955:             $homeserver = &domain($cdom,'primary');
                   7956:         }
                   7957:     }
1.1065    raeburn  7958:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7959:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  7960:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7961:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7962: }
                   7963: 
1.506     raeburn  7964: sub auto_create_password {
1.873     raeburn  7965:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7966:     my ($homeserver,$response);
1.506     raeburn  7967:     my $create_passwd = 0;
                   7968:     my $authchk = '';
1.873     raeburn  7969:     if ($udom =~ /^$match_domain$/) {
                   7970:         $homeserver = &domain($udom,'primary');
                   7971:     }
                   7972:     if ($homeserver eq '') {
                   7973:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7974:             $homeserver = &homeserver($cnum,$cdom);
                   7975:         }
                   7976:     }
                   7977:     if ($homeserver eq '') {
                   7978:         $authchk = 'nodomain';
1.506     raeburn  7979:     } else {
1.873     raeburn  7980:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7981:         if ($response eq 'refused') {
                   7982:             $authchk = 'refused';
                   7983:         } else {
1.901     albertel 7984:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7985:         }
1.506     raeburn  7986:     }
                   7987:     return ($authparam,$create_passwd,$authchk);
                   7988: }
                   7989: 
1.706     raeburn  7990: sub auto_photo_permission {
                   7991:     my ($cnum,$cdom,$students) = @_;
                   7992:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7993:     my ($outcome,$perm_reqd,$conditions) = 
                   7994: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7995:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7996: 	return (undef,undef);
                   7997:     }
1.706     raeburn  7998:     return ($outcome,$perm_reqd,$conditions);
                   7999: }
                   8000: 
                   8001: sub auto_checkphotos {
                   8002:     my ($uname,$udom,$pid) = @_;
                   8003:     my $homeserver = &homeserver($uname,$udom);
                   8004:     my ($result,$resulttype);
                   8005:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8006: 				   &escape($uname).':'.&escape($pid),
                   8007: 				   $homeserver));
1.709     albertel 8008:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8009: 	return (undef,undef);
                   8010:     }
1.706     raeburn  8011:     if ($outcome) {
                   8012:         ($result,$resulttype) = split(/:/,$outcome);
                   8013:     } 
                   8014:     return ($result,$resulttype);
                   8015: }
                   8016: 
                   8017: sub auto_photochoice {
                   8018:     my ($cnum,$cdom) = @_;
                   8019:     my $homeserver = &homeserver($cnum,$cdom);
                   8020:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8021: 						       &escape($cdom),
                   8022: 						       $homeserver)));
1.709     albertel 8023:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8024: 	return (undef,undef);
                   8025:     }
1.706     raeburn  8026:     return ($update,$comment);
                   8027: }
                   8028: 
                   8029: sub auto_photoupdate {
                   8030:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8031:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8032:     my $host=&hostname($homeserver);
1.706     raeburn  8033:     my $cmd = '';
                   8034:     my $maxtries = 1;
1.800     albertel 8035:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8036:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8037:     }
                   8038:     $cmd =~ s/%%$//;
                   8039:     $cmd = &escape($cmd);
                   8040:     my $query = 'institutionalphotos';
                   8041:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8042:     unless ($queryid=~/^\Q$host\E\_/) {
                   8043:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8044:         return 'error: '.$queryid;
                   8045:     }
                   8046:     my $reply = &get_query_reply($queryid);
                   8047:     my $tries = 1;
                   8048:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8049:         $reply = &get_query_reply($queryid);
                   8050:         $tries ++;
                   8051:     }
                   8052:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8053:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8054:     } else {
                   8055:         my @responses = split(/:/,$reply);
                   8056:         my $outcome = shift(@responses); 
                   8057:         foreach my $item (@responses) {
                   8058:             my ($key,$value) = split(/=/,$item);
                   8059:             $$photo{$key} = $value;
                   8060:         }
                   8061:         return $outcome;
                   8062:     }
                   8063:     return 'error';
                   8064: }
                   8065: 
1.521     raeburn  8066: sub auto_instcode_format {
1.793     albertel 8067:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8068: 	$cat_order) = @_;
1.521     raeburn  8069:     my $courses = '';
1.772     raeburn  8070:     my @homeservers;
1.521     raeburn  8071:     if ($caller eq 'global') {
1.841     albertel 8072: 	my %servers = &get_servers($codedom,'library');
                   8073: 	foreach my $tryserver (keys(%servers)) {
                   8074: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8075: 		push(@homeservers,$tryserver);
                   8076: 	    }
1.584     raeburn  8077:         }
1.1022    raeburn  8078:     } elsif ($caller eq 'requests') {
                   8079:         if ($codedom =~ /^$match_domain$/) {
                   8080:             my $chome = &domain($codedom,'primary');
                   8081:             unless ($chome eq 'no_host') {
                   8082:                 push(@homeservers,$chome);
                   8083:             }
                   8084:         }
1.521     raeburn  8085:     } else {
1.772     raeburn  8086:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8087:     }
1.793     albertel 8088:     foreach my $code (keys(%{$instcodes})) {
                   8089:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8090:     }
                   8091:     chop($courses);
1.772     raeburn  8092:     my $ok_response = 0;
                   8093:     my $response;
                   8094:     while (@homeservers > 0 && $ok_response == 0) {
                   8095:         my $server = shift(@homeservers); 
                   8096:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8097:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8098:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8099: 		split(/:/,$response);
1.772     raeburn  8100:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8101:             push(@{$codetitles},&str2array($codetitles_str));
                   8102:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8103:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8104:             $ok_response = 1;
                   8105:         }
                   8106:     }
                   8107:     if ($ok_response) {
1.521     raeburn  8108:         return 'ok';
1.772     raeburn  8109:     } else {
                   8110:         return $response;
1.521     raeburn  8111:     }
                   8112: }
                   8113: 
1.792     raeburn  8114: sub auto_instcode_defaults {
                   8115:     my ($domain,$returnhash,$code_order) = @_;
                   8116:     my @homeservers;
1.841     albertel 8117: 
                   8118:     my %servers = &get_servers($domain,'library');
                   8119:     foreach my $tryserver (keys(%servers)) {
                   8120: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8121: 	    push(@homeservers,$tryserver);
                   8122: 	}
1.792     raeburn  8123:     }
1.841     albertel 8124: 
1.792     raeburn  8125:     my $response;
1.841     albertel 8126:     foreach my $server (@homeservers) {
1.792     raeburn  8127:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8128:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8129: 	
                   8130: 	foreach my $pair (split(/\&/,$response)) {
                   8131: 	    my ($name,$value)=split(/\=/,$pair);
                   8132: 	    if ($name eq 'code_order') {
                   8133: 		@{$code_order} = split(/\&/,&unescape($value));
                   8134: 	    } else {
                   8135: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8136: 	    }
                   8137: 	}
                   8138: 	return 'ok';
1.792     raeburn  8139:     }
1.841     albertel 8140: 
                   8141:     return $response;
1.1003    raeburn  8142: }
                   8143: 
                   8144: sub auto_possible_instcodes {
1.1007    raeburn  8145:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8146:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8147:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8148:         return;
                   8149:     }
1.1003    raeburn  8150:     my (@homeservers,$uhome);
                   8151:     if (defined(&domain($domain,'primary'))) {
                   8152:         $uhome=&domain($domain,'primary');
                   8153:         push(@homeservers,&domain($domain,'primary'));
                   8154:     } else {
                   8155:         my %servers = &get_servers($domain,'library');
                   8156:         foreach my $tryserver (keys(%servers)) {
                   8157:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8158:                 push(@homeservers,$tryserver);
                   8159:             }
                   8160:         }
                   8161:     }
                   8162:     my $response;
                   8163:     foreach my $server (@homeservers) {
                   8164:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8165:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8166:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8167:             split(':',$response);
                   8168:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8169:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8170:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8171:             my ($name,$value)=split('=',$item);
                   8172:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8173:         }
                   8174:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8175:             my ($name,$value)=split('=',$item);
                   8176:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8177:         }
                   8178:         return 'ok';
                   8179:     }
                   8180:     return $response;
                   8181: }
1.792     raeburn  8182: 
1.1010    raeburn  8183: sub auto_courserequest_checks {
                   8184:     my ($dom) = @_;
1.1020    raeburn  8185:     my ($homeserver,%validations);
                   8186:     if ($dom =~ /^$match_domain$/) {
                   8187:         $homeserver = &domain($dom,'primary');
                   8188:     }
                   8189:     unless ($homeserver eq 'no_host') {
                   8190:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8191:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8192:             my @items = split(/&/,$response);
                   8193:             foreach my $item (@items) {
                   8194:                 my ($key,$value) = split('=',$item);
                   8195:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8196:             }
                   8197:         }
                   8198:     }
1.1010    raeburn  8199:     return %validations; 
                   8200: }
                   8201: 
1.1020    raeburn  8202: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8203:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8204:     my ($homeserver,$response);
                   8205:     if ($dom =~ /^$match_domain$/) {
                   8206:         $homeserver = &domain($dom,'primary');
                   8207:     }
1.1172.2.43  raeburn  8208:     unless ($homeserver eq 'no_host') {
                   8209:         my $customdata;
                   8210:         if (ref($custominfo) eq 'HASH') {
                   8211:             $customdata = &freeze_escape($custominfo);
                   8212:         }
1.1020    raeburn  8213:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8214:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8215:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8216:                                     $customdata,$homeserver));
1.1020    raeburn  8217:     }
                   8218:     return $response;
                   8219: }
                   8220: 
1.777     albertel 8221: sub auto_validate_class_sec {
1.918     raeburn  8222:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8223:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8224:     my $ownerlist;
                   8225:     if (ref($owners) eq 'ARRAY') {
                   8226:         $ownerlist = join(',',@{$owners});
                   8227:     } else {
                   8228:         $ownerlist = $owners;
                   8229:     }
1.773     raeburn  8230:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8231:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8232:     return $response;
                   8233: }
                   8234: 
1.1172.2.38  raeburn  8235: sub auto_crsreq_update {
                   8236:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8237:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8238:     my ($homeserver,%crsreqresponse);
                   8239:     if ($cdom =~ /^$match_domain$/) {
                   8240:         $homeserver = &domain($cdom,'primary');
                   8241:     }
                   8242:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8243:         my $info;
                   8244:         if (ref($inbound) eq 'HASH') {
                   8245:             $info = &freeze_escape($inbound);
                   8246:         }
                   8247:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8248:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8249:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8250:                             &escape($title).':'.&escape($code).':'.
                   8251:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8252:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8253:             my @items = split(/&/,$response);
                   8254:             foreach my $item (@items) {
                   8255:                 my ($key,$value) = split('=',$item);
                   8256:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8257:             }
                   8258:         }
                   8259:     }
                   8260:     return \%crsreqresponse;
                   8261: }
                   8262: 
1.1172.2.78  raeburn  8263: sub auto_export_grades {
                   8264:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8265:     my ($homeserver,%exportresponse);
                   8266:     if ($cdom =~ /^$match_domain$/) {
                   8267:         $homeserver = &domain($cdom,'primary');
                   8268:     }
                   8269:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8270:         my $info;
                   8271:         if (ref($inforef) eq 'HASH') {
                   8272:             $info = &freeze_escape($inforef);
                   8273:         }
                   8274:         if (ref($gradesref) eq 'HASH') {
                   8275:             my $grades = &freeze_escape($gradesref);
                   8276:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8277:                                 $info.':'.$grades,$homeserver);
                   8278:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8279:                 my @items = split(/&/,$response);
                   8280:                 foreach my $item (@items) {
                   8281:                     my ($key,$value) = split('=',$item);
                   8282:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8283:                 }
                   8284:             }
                   8285:         }
                   8286:     }
                   8287:     return \%exportresponse;
                   8288: }
                   8289: 
1.1172.2.68  raeburn  8290: sub check_instcode_cloning {
                   8291:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8292:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8293:         return;
                   8294:     }
                   8295:     my $canclone;
                   8296:     if (@{$code_order} > 0) {
                   8297:         my $instcoderegexp ='^';
                   8298:         my @clonecodes = split(/\&/,$cloner);
                   8299:         foreach my $item (@{$code_order}) {
                   8300:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8301:                 foreach my $pair (@clonecodes) {
                   8302:                     my ($key,$val) = split(/\=/,$pair,2);
                   8303:                     $val = &unescape($val);
                   8304:                     if ($key eq $item) {
                   8305:                         $instcoderegexp .= '('.$val.')';
                   8306:                         last;
                   8307:                     }
                   8308:                 }
                   8309:             } else {
                   8310:                 $instcoderegexp .= $codedefaults->{$item};
                   8311:             }
                   8312:         }
                   8313:         $instcoderegexp .= '$';
                   8314:         my (@from,@to);
                   8315:         eval {
                   8316:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8317:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8318:         };
                   8319:         if ((@from > 0) && (@to > 0)) {
                   8320:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8321:             if (!@diffs) {
                   8322:                 $canclone = 1;
                   8323:             }
                   8324:         }
                   8325:     }
                   8326:     return $canclone;
                   8327: }
                   8328: 
                   8329: sub default_instcode_cloning {
                   8330:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8331:     my (%codedefaults,@code_order,$canclone);
                   8332:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8333:         %codedefaults = %{$codedefaultsref};
                   8334:         @code_order = @{$codeorderref};
                   8335:     } elsif ($clonedom) {
                   8336:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8337:     }
                   8338:     if (($domdefclone) && (@code_order)) {
                   8339:         my @clonecodes = split(/\+/,$domdefclone);
                   8340:         my $instcoderegexp ='^';
                   8341:         foreach my $item (@code_order) {
                   8342:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8343:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8344:             } else {
                   8345:                 $instcoderegexp .= $codedefaults{$item};
                   8346:             }
                   8347:         }
                   8348:         $instcoderegexp .= '$';
                   8349:         my (@from,@to);
                   8350:         eval {
                   8351:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8352:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8353:         };
                   8354:         if ((@from > 0) && (@to > 0)) {
                   8355:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8356:             if (!@diffs) {
                   8357:                 $canclone = 1;
                   8358:             }
                   8359:         }
                   8360:     }
                   8361:     return $canclone;
                   8362: }
                   8363: 
1.679     raeburn  8364: # ------------------------------------------------------- Course Group routines
                   8365: 
                   8366: sub get_coursegroups {
1.809     raeburn  8367:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8368:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8369: }
                   8370: 
1.679     raeburn  8371: sub modify_coursegroup {
                   8372:     my ($cdom,$cnum,$groupsettings) = @_;
                   8373:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8374: }
                   8375: 
1.809     raeburn  8376: sub toggle_coursegroup_status {
                   8377:     my ($cdom,$cnum,$group,$action) = @_;
                   8378:     my ($from_namespace,$to_namespace);
                   8379:     if ($action eq 'delete') {
                   8380:         $from_namespace = 'coursegroups';
                   8381:         $to_namespace = 'deleted_groups';
                   8382:     } else {
                   8383:         $from_namespace = 'deleted_groups';
                   8384:         $to_namespace = 'coursegroups';
                   8385:     }
                   8386:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8387:     if (my $tmp = &error(%curr_group)) {
                   8388:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8389:         return ('read error',$tmp);
                   8390:     } else {
                   8391:         my %savedsettings = %curr_group; 
1.809     raeburn  8392:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8393:         my $deloutcome;
                   8394:         if ($result eq 'ok') {
1.809     raeburn  8395:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8396:         } else {
                   8397:             return ('write error',$result);
                   8398:         }
                   8399:         if ($deloutcome eq 'ok') {
                   8400:             return 'ok';
                   8401:         } else {
                   8402:             return ('delete error',$deloutcome);
                   8403:         }
                   8404:     }
                   8405: }
                   8406: 
1.679     raeburn  8407: sub modify_group_roles {
1.957     raeburn  8408:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8409:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8410:     my $role = 'gr/'.&escape($userprivs);
                   8411:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8412:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8413:     if ($result eq 'ok') {
                   8414:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8415:     }
1.679     raeburn  8416:     return $result;
                   8417: }
                   8418: 
                   8419: sub modify_coursegroup_membership {
                   8420:     my ($cdom,$cnum,$membership) = @_;
                   8421:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8422:     return $result;
                   8423: }
                   8424: 
1.682     raeburn  8425: sub get_active_groups {
                   8426:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8427:     my $now = time;
                   8428:     my %groups = ();
                   8429:     foreach my $key (keys(%env)) {
1.811     albertel 8430:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8431:             my ($start,$end) = split(/\./,$env{$key});
                   8432:             if (($end!=0) && ($end<$now)) { next; }
                   8433:             if (($start!=0) && ($start>$now)) { next; }
                   8434:             if ($1 eq $cdom && $2 eq $cnum) {
                   8435:                 $groups{$3} = $env{$key} ;
                   8436:             }
                   8437:         }
                   8438:     }
                   8439:     return %groups;
                   8440: }
                   8441: 
1.683     raeburn  8442: sub get_group_membership {
                   8443:     my ($cdom,$cnum,$group) = @_;
                   8444:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8445: }
                   8446: 
                   8447: sub get_users_groups {
                   8448:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8449:     my @usersgroups;
1.683     raeburn  8450:     my $cachetime=1800;
                   8451: 
                   8452:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8453:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8454:     if (defined($cached)) {
1.734     albertel 8455:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8456:     } else {  
                   8457:         $grouplist = '';
1.816     raeburn  8458:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8459:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8460:         my $access_end = $env{'course.'.$courseid.
                   8461:                               '.default_enrollment_end_date'};
                   8462:         my $now = time;
                   8463:         foreach my $key (keys(%roleshash)) {
                   8464:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8465:                 my $group = $1;
                   8466:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8467:                     my $start = $2;
                   8468:                     my $end = $1;
                   8469:                     if ($start == -1) { next; } # deleted from group
                   8470:                     if (($start!=0) && ($start>$now)) { next; }
                   8471:                     if (($end!=0) && ($end<$now)) {
                   8472:                         if ($access_end && $access_end < $now) {
                   8473:                             if ($access_end - $end < 86400) {
                   8474:                                 push(@usersgroups,$group);
1.733     raeburn  8475:                             }
                   8476:                         }
1.817     raeburn  8477:                         next;
1.733     raeburn  8478:                     }
1.817     raeburn  8479:                     push(@usersgroups,$group);
1.683     raeburn  8480:                 }
                   8481:             }
                   8482:         }
1.817     raeburn  8483:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8484:         $grouplist = join(':',@usersgroups);
                   8485:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8486:     }
1.733     raeburn  8487:     return @usersgroups;
1.683     raeburn  8488: }
                   8489: 
                   8490: sub devalidate_getgroups_cache {
                   8491:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8492:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8493: 
1.683     raeburn  8494:     my $hashid="$udom:$uname:$courseid";
                   8495:     &devalidate_cache_new('getgroups',$hashid);
                   8496: }
                   8497: 
1.12      www      8498: # ------------------------------------------------------------------ Plain Text
                   8499: 
                   8500: sub plaintext {
1.988     raeburn  8501:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8502:     if ($short =~ m{^cr/}) {
1.758     albertel 8503: 	return (split('/',$short))[-1];
                   8504:     }
1.742     raeburn  8505:     if (!defined($cid)) {
                   8506:         $cid = $env{'request.course.id'};
                   8507:     }
                   8508:     my %rolenames = (
1.1008    raeburn  8509:                       Course    => 'std',
                   8510:                       Community => 'alt1',
1.742     raeburn  8511:                     );
1.1037    raeburn  8512:     if ($cid ne '') {
                   8513:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8514:             unless ($forcedefault) {
                   8515:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8516:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8517:                 return &Apache::lonlocal::mt($roletext);
                   8518:             }
                   8519:         }
                   8520:     }
                   8521:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8522:         (defined($rolenames{$type})) && 
                   8523:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8524:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8525:     } elsif ($cid ne '') {
                   8526:         my $crstype = $env{'course.'.$cid.'.type'};
                   8527:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8528:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8529:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8530:         }
1.742     raeburn  8531:     }
1.1037    raeburn  8532:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8533: }
                   8534: 
                   8535: # ----------------------------------------------------------------- Assign Role
                   8536: 
                   8537: sub assignrole {
1.957     raeburn  8538:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8539:         $context)=@_;
1.21      www      8540:     my $mrole;
                   8541:     if ($role =~ /^cr\//) {
1.393     www      8542:         my $cwosec=$url;
1.811     albertel 8543:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8544: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8545:            my $refused = 1;
                   8546:            if ($context eq 'requestcourses') {
                   8547:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8548:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8549:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8550:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8551:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8552:                            if ($crsenv{'internal.courseowner'} eq
                   8553:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8554:                                $refused = '';
                   8555:                            }
                   8556:                        }
                   8557:                    }
                   8558:                }
                   8559:            }
                   8560:            if ($refused) {
                   8561:                &logthis('Refused custom assignrole: '.
                   8562:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8563:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8564:                return 'refused';
                   8565:            }
1.104     www      8566:         }
1.21      www      8567:         $mrole='cr';
1.678     raeburn  8568:     } elsif ($role =~ /^gr\//) {
                   8569:         my $cwogrp=$url;
1.811     albertel 8570:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8571:         unless (&allowed('mdg',$cwogrp)) {
                   8572:             &logthis('Refused group assignrole: '.
                   8573:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8574:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8575:             return 'refused';
                   8576:         }
                   8577:         $mrole='gr';
1.21      www      8578:     } else {
1.82      www      8579:         my $cwosec=$url;
1.811     albertel 8580:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8581:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8582:             my $refused;
                   8583:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8584:                 if (!(&allowed('c'.$role,$url))) {
                   8585:                     $refused = 1;
                   8586:                 }
                   8587:             } else {
                   8588:                 $refused = 1;
                   8589:             }
1.947     raeburn  8590:             if ($refused) {
1.1045    raeburn  8591:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8592:                 if (!$selfenroll && $context eq 'course') {
                   8593:                     my %crsenv;
                   8594:                     if ($role eq 'cc' || $role eq 'co') {
                   8595:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8596:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8597:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8598:                                 if ($crsenv{'internal.courseowner'} eq 
                   8599:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8600:                                     $refused = '';
                   8601:                                 }
                   8602:                             }
                   8603:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8604:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8605:                                 if ($crsenv{'internal.courseowner'} eq 
                   8606:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8607:                                     $refused = '';
                   8608:                                 }
                   8609:                             }
                   8610:                         }
                   8611:                     }
                   8612:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8613:                     $refused = '';
1.1017    raeburn  8614:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8615:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8616:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8617:                         my $wrongcc;
                   8618:                         if ($cnum =~ /^$match_community$/) {
                   8619:                             $wrongcc = 1 if ($role eq 'cc');
                   8620:                         } else {
                   8621:                             $wrongcc = 1 if ($role eq 'co');
                   8622:                         }
                   8623:                         unless ($wrongcc) {
                   8624:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8625:                             if ($crsenv{'internal.courseowner'} eq 
                   8626:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8627:                                 $refused = '';
                   8628:                             }
1.1017    raeburn  8629:                         }
                   8630:                     }
1.1172.2.9  raeburn  8631:                 } elsif ($context eq 'requestauthor') {
                   8632:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8633:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8634:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8635:                             $refused = '';
                   8636:                         } else {
                   8637:                             my %domdefaults = &get_domain_defaults($udom);
                   8638:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8639:                                 my $checkbystatus;
                   8640:                                 if ($env{'user.adv'}) {
                   8641:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8642:                                     if ($disposition eq 'automatic') {
                   8643:                                         $refused = '';
                   8644:                                     } elsif ($disposition eq '') {
                   8645:                                         $checkbystatus = 1;
                   8646:                                     }
                   8647:                                 } else {
                   8648:                                     $checkbystatus = 1;
                   8649:                                 }
                   8650:                                 if ($checkbystatus) {
                   8651:                                     if ($env{'environment.inststatus'}) {
                   8652:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8653:                                         foreach my $type (@inststatuses) {
                   8654:                                             if (($type ne '') &&
                   8655:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8656:                                                 $refused = '';
                   8657:                                             }
                   8658:                                         }
                   8659:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8660:                                         $refused = '';
                   8661:                                     }
                   8662:                                 }
                   8663:                             }
                   8664:                         }
                   8665:                     }
1.1017    raeburn  8666:                 }
                   8667:                 if ($refused) {
1.947     raeburn  8668:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8669:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8670: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8671:                     return 'refused';
                   8672:                 }
1.932     raeburn  8673:             }
1.1131    raeburn  8674:         } elsif ($role eq 'au') {
                   8675:             if ($url ne '/'.$udom.'/') {
                   8676:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8677:                          ' to assign author role for '.$uname.':'.$udom.
                   8678:                          ' in domain: '.$url.' refused (wrong domain).');
                   8679:                 return 'refused';
                   8680:             }
1.104     www      8681:         }
1.21      www      8682:         $mrole=$role;
                   8683:     }
1.620     albertel 8684:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8685:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8686:     if ($end) { $command.='_'.$end; }
1.21      www      8687:     if ($start) {
                   8688: 	if ($end) { 
1.81      www      8689:            $command.='_'.$start; 
1.21      www      8690:         } else {
1.81      www      8691:            $command.='_0_'.$start;
1.21      www      8692:         }
                   8693:     }
1.739     raeburn  8694:     my $origstart = $start;
                   8695:     my $origend = $end;
1.957     raeburn  8696:     my $delflag;
1.357     www      8697: # actually delete
                   8698:     if ($deleteflag) {
1.373     www      8699: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8700: # modify command to delete the role
1.620     albertel 8701:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8702:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8703: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8704: # set start and finish to negative values for userrolelog
                   8705:            $start=-1;
                   8706:            $end=-1;
1.957     raeburn  8707:            $delflag = 1;
1.357     www      8708:         }
                   8709:     }
                   8710: # send command
1.349     www      8711:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8712: # log new user role if status is ok
1.349     www      8713:     if ($answer eq 'ok') {
1.663     raeburn  8714: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  8715:         if (($role eq 'cc') || ($role eq 'in') ||
                   8716:             ($role eq 'ep') || ($role eq 'ad') ||
                   8717:             ($role eq 'ta') || ($role eq 'st') ||
                   8718:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8719:             ($role eq 'co')) {
1.1172.2.13  raeburn  8720: # for course roles, perform group memberships changes triggered by role change.
                   8721:             unless ($role =~ /^gr/) {
                   8722:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8723:                                                  $origstart,$selfenroll,$context);
                   8724:             }
1.1172.2.9  raeburn  8725:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8726:                            $selfenroll,$context);
                   8727:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8728:                  ($role eq 'au') || ($role eq 'dc')) {
                   8729:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8730:                            $context);
                   8731:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8732:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8733:                              $context);
                   8734:         }
1.1053    raeburn  8735:         if ($role eq 'cc') {
                   8736:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8737:         }
1.349     www      8738:     }
                   8739:     return $answer;
1.169     harris41 8740: }
                   8741: 
1.1053    raeburn  8742: sub autoupdate_coowners {
                   8743:     my ($url,$end,$start,$uname,$udom) = @_;
                   8744:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8745:     if (($cdom ne '') && ($cnum ne '')) {
                   8746:         my $now = time;
                   8747:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8748:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8749:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8750:             my $instcode = $coursehash{'internal.coursecode'};
                   8751:             if ($instcode ne '') {
1.1056    raeburn  8752:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8753:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8754:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8755:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8756:                         if ($result eq 'valid') {
                   8757:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8758:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8759:                                     push(@newcoowners,$coowner);
                   8760:                                 }
                   8761:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8762:                                     push(@newcoowners,$uname.':'.$udom);
                   8763:                                 }
                   8764:                                 @newcoowners = sort(@newcoowners);
                   8765:                             } else {
                   8766:                                 push(@newcoowners,$uname.':'.$udom);
                   8767:                             }
                   8768:                         } else {
                   8769:                             if ($coursehash{'internal.co-owners'}) {
                   8770:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8771:                                     unless ($coowner eq $uname.':'.$udom) {
                   8772:                                         push(@newcoowners,$coowner);
                   8773:                                     }
                   8774:                                 }
                   8775:                                 unless (@newcoowners > 0) {
                   8776:                                     $delcoowners = 1;
                   8777:                                     $coowners = '';
                   8778:                                 }
                   8779:                             }
                   8780:                         }
                   8781:                         if (@newcoowners || $delcoowners) {
                   8782:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8783:                                             $delcoowners,@newcoowners);
                   8784:                         }
                   8785:                     }
                   8786:                 }
                   8787:             }
                   8788:         }
                   8789:     }
                   8790: }
                   8791: 
                   8792: sub store_coowners {
                   8793:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8794:     my $cid = $cdom.'_'.$cnum;
                   8795:     my ($coowners,$delresult,$putresult);
                   8796:     if (@newcoowners) {
                   8797:         $coowners = join(',',@newcoowners);
                   8798:         my %coownershash = (
                   8799:                             'internal.co-owners' => $coowners,
                   8800:                            );
                   8801:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8802:         if ($putresult eq 'ok') {
                   8803:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8804:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8805:             }
                   8806:         }
                   8807:     }
                   8808:     if ($delcoowners) {
                   8809:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8810:         if ($delresult eq 'ok') {
                   8811:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8812:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8813:             }
                   8814:         }
                   8815:     }
                   8816:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8817:         my %crsinfo =
                   8818:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8819:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8820:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8821:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8822:         }
                   8823:     }
                   8824: }
                   8825: 
1.169     harris41 8826: # -------------------------------------------------- Modify user authentication
1.197     www      8827: # Overrides without validation
                   8828: 
1.169     harris41 8829: sub modifyuserauth {
                   8830:     my ($udom,$uname,$umode,$upass)=@_;
                   8831:     my $uhome=&homeserver($uname,$udom);
1.197     www      8832:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8833:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8834:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8835:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8836:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8837: 		     &escape($upass),$uhome);
1.620     albertel 8838:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8839:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8840:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8841:     &log($udom,,$uname,$uhome,
1.620     albertel 8842:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8843:                                      $env{'user.name'}.', '.$umode.
1.197     www      8844:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8845:     unless ($reply eq 'ok') {
1.197     www      8846:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8847: 	return 'error: '.$reply;
                   8848:     }   
1.170     harris41 8849:     return 'ok';
1.80      www      8850: }
                   8851: 
1.81      www      8852: # --------------------------------------------------------------- Modify a user
1.80      www      8853: 
1.81      www      8854: sub modifyuser {
1.206     matthew  8855:     my ($udom,    $uname, $uid,
                   8856:         $umode,   $upass, $first,
                   8857:         $middle,  $last,  $gene,
1.1058    raeburn  8858:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8859:     $udom= &LONCAPA::clean_domain($udom);
                   8860:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8861:     my $showcandelete = 'none';
                   8862:     if (ref($candelete) eq 'ARRAY') {
                   8863:         if (@{$candelete} > 0) {
                   8864:             $showcandelete = join(', ',@{$candelete});
                   8865:         }
                   8866:     }
1.81      www      8867:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8868:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8869: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8870:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8871:                                      ' desiredhome not specified'). 
1.620     albertel 8872:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8873:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8874:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8875:     my $newuser;
                   8876:     if ($uhome eq 'no_host') {
                   8877:         $newuser = 1;
                   8878:     }
1.80      www      8879: # ----------------------------------------------------------------- Create User
1.406     albertel 8880:     if (($uhome eq 'no_host') && 
                   8881: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8882:         my $unhome='';
1.844     albertel 8883:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8884:             $unhome = $desiredhome;
1.620     albertel 8885: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8886: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8887:         } else { # load balancing routine for determining $unhome
1.81      www      8888:             my $loadm=10000000;
1.841     albertel 8889: 	    my %servers = &get_servers($udom,'library');
                   8890: 	    foreach my $tryserver (keys(%servers)) {
                   8891: 		my $answer=reply('load',$tryserver);
                   8892: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8893: 		    $loadm=$answer;
                   8894: 		    $unhome=$tryserver;
                   8895: 		}
1.80      www      8896: 	    }
                   8897:         }
                   8898:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8899: 	    return 'error: unable to find a home server for '.$uname.
                   8900:                    ' in domain '.$udom;
1.80      www      8901:         }
                   8902:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8903:                          &escape($upass),$unhome);
                   8904: 	unless ($reply eq 'ok') {
                   8905:             return 'error: '.$reply;
                   8906:         }   
1.230     stredwic 8907:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8908:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8909: 	    return 'error: unable verify users home machine.';
1.80      www      8910:         }
1.209     matthew  8911:     }   # End of creation of new user
1.80      www      8912: # ---------------------------------------------------------------------- Add ID
                   8913:     if ($uid) {
                   8914:        $uid=~tr/A-Z/a-z/;
                   8915:        my %uidhash=&idrget($udom,$uname);
1.196     www      8916:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8917:          && (!$forceid)) {
1.80      www      8918: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8919: 	      return 'error: user id "'.$uid.'" does not match '.
                   8920:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8921:           }
                   8922:        } else {
                   8923: 	  &idput($udom,($uname => $uid));
                   8924:        }
                   8925:     }
                   8926: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8927:     my @tmp=&get('environment',
1.899     raeburn  8928: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8929:                     'permanentemail','inststatus'],
1.134     albertel 8930: 		   $udom,$uname);
1.1075    raeburn  8931:     my (%names,%oldnames);
1.313     matthew  8932:     if ($tmp[0] =~ m/^error:.*/) { 
                   8933:         %names=(); 
                   8934:     } else {
                   8935:         %names = @tmp;
1.1075    raeburn  8936:         %oldnames = %names;
1.313     matthew  8937:     }
1.388     www      8938: #
1.1058    raeburn  8939: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8940: # of users did not contain them), do not overwrite existing values
                   8941: # unless field is in $candelete array ref.  
                   8942: #
                   8943: 
                   8944:     my @fields = ('firstname','middlename','lastname','generation',
                   8945:                   'permanentemail','id');
                   8946:     my %newvalues;
                   8947:     if (ref($candelete) eq 'ARRAY') {
                   8948:         foreach my $field (@fields) {
                   8949:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8950:                 if ($field eq 'firstname') {
                   8951:                     $names{$field} = $first;
                   8952:                 } elsif ($field eq 'middlename') {
                   8953:                     $names{$field} = $middle;
                   8954:                 } elsif ($field eq 'lastname') {
                   8955:                     $names{$field} = $last;
                   8956:                 } elsif ($field eq 'generation') { 
                   8957:                     $names{$field} = $gene;
                   8958:                 } elsif ($field eq 'permanentemail') {
                   8959:                     $names{$field} = $email;
                   8960:                 } elsif ($field eq 'id') {
                   8961:                     $names{$field}  = $uid;
                   8962:                 }
                   8963:             }
                   8964:         }
                   8965:     }
1.388     www      8966:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8967:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8968:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8969:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8970:     if ($email) {
                   8971:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8972:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8973:     }
1.899     raeburn  8974:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8975:     if (defined($inststatus)) {
                   8976:         $names{'inststatus'} = '';
                   8977:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8978:         if (ref($usertypes) eq 'HASH') {
                   8979:             my @okstatuses; 
                   8980:             foreach my $item (split(/:/,$inststatus)) {
                   8981:                 if (defined($usertypes->{$item})) {
                   8982:                     push(@okstatuses,$item);  
                   8983:                 }
                   8984:             }
                   8985:             if (@okstatuses) {
                   8986:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8987:             }
                   8988:         }
                   8989:     }
1.1075    raeburn  8990:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8991:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8992:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8993:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8994:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8995:     } else {
                   8996:         $logmsg .= ' during self creation';
                   8997:     }
1.1075    raeburn  8998:     my $changed;
                   8999:     if ($newuser) {
                   9000:         $changed = 1;
                   9001:     } else {
                   9002:         foreach my $field (@fields) {
                   9003:             if ($names{$field} ne $oldnames{$field}) {
                   9004:                 $changed = 1;
                   9005:                 last;
                   9006:             }
                   9007:         }
                   9008:     }
                   9009:     unless ($changed) {
                   9010:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9011:         &logthis($logmsg);
                   9012:         return 'ok';
                   9013:     }
                   9014:     my $reply = &put('environment', \%names, $udom,$uname);
                   9015:     if ($reply ne 'ok') { 
                   9016:         return 'error: '.$reply;
                   9017:     }
1.1087    raeburn  9018:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9019:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9020:     }
1.1075    raeburn  9021:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9022:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9023:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9024:     &logthis($logmsg);
1.134     albertel 9025:     return 'ok';
1.80      www      9026: }
                   9027: 
1.81      www      9028: # -------------------------------------------------------------- Modify student
1.80      www      9029: 
1.81      www      9030: sub modifystudent {
                   9031:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9032:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9033:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9034:     if (!$cid) {
1.620     albertel 9035: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9036: 	    return 'not_in_class';
                   9037: 	}
1.80      www      9038:     }
                   9039: # --------------------------------------------------------------- Make the user
1.81      www      9040:     my $reply=&modifyuser
1.209     matthew  9041: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9042:          $desiredhome,$email,$inststatus);
1.80      www      9043:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9044:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9045:     # student's environment
1.297     matthew  9046:     $uid = undef if (!$forceid);
1.455     albertel 9047:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9048: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9049:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9050:     return $reply;
                   9051: }
                   9052: 
                   9053: sub modify_student_enrollment {
1.1172.2.23  raeburn  9054:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9055:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9056:     my ($cdom,$cnum,$chome);
                   9057:     if (!$cid) {
1.620     albertel 9058: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9059: 	    return 'not_in_class';
                   9060: 	}
1.620     albertel 9061: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9062: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9063:     } else {
                   9064: 	($cdom,$cnum)=split(/_/,$cid);
                   9065:     }
1.620     albertel 9066:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9067:     if (!$chome) {
1.457     raeburn  9068: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9069:     }
1.455     albertel 9070:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9071:     # Make sure the user exists
1.81      www      9072:     my $uhome=&homeserver($uname,$udom);
                   9073:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9074: 	return 'error: no such user';
                   9075:     }
1.297     matthew  9076:     # Get student data if we were not given enough information
                   9077:     if (!defined($first)  || $first  eq '' || 
                   9078:         !defined($last)   || $last   eq '' || 
                   9079:         !defined($uid)    || $uid    eq '' || 
                   9080:         !defined($middle) || $middle eq '' || 
                   9081:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9082:         # They did not supply us with enough data to enroll the student, so
                   9083:         # we need to pick up more information.
1.297     matthew  9084:         my %tmp = &get('environment',
1.294     matthew  9085:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9086:                        ,$udom,$uname);
                   9087: 
1.800     albertel 9088:         #foreach my $key (keys(%tmp)) {
                   9089:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9090:         #}
1.294     matthew  9091:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9092:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9093:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9094:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9095:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9096:     }
1.556     albertel 9097:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9098:     my $user = "$uname:$udom";
                   9099:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9100:     my $reply=cput('classlist',
1.1148    raeburn  9101: 		   {$user => 
1.1172.2.76  raeburn  9102: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9103: 		   $cdom,$cnum);
1.1148    raeburn  9104:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9105:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9106:     } else { 
1.81      www      9107: 	return 'error: '.$reply;
                   9108:     }
1.297     matthew  9109:     # Add student role to user
1.83      www      9110:     my $uurl='/'.$cid;
1.81      www      9111:     $uurl=~s/\_/\//g;
                   9112:     if ($usec) {
                   9113: 	$uurl.='/'.$usec;
                   9114:     }
1.1148    raeburn  9115:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9116:                              $selfenroll,$context);
                   9117:     if ($result ne 'ok') {
                   9118:         if ($old_entry{$user} ne '') {
                   9119:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9120:         } else {
                   9121:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9122:         }
                   9123:     }
                   9124:     return $result; 
1.21      www      9125: }
                   9126: 
1.556     albertel 9127: sub format_name {
                   9128:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9129:     my $name;
                   9130:     if ($first ne 'lastname') {
                   9131: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9132:     } else {
                   9133: 	if ($lastname=~/\S/) {
                   9134: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9135: 	    $name=~s/\s+,/,/;
                   9136: 	} else {
                   9137: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9138: 	}
                   9139:     }
                   9140:     $name=~s/^\s+//;
                   9141:     $name=~s/\s+$//;
                   9142:     $name=~s/\s+/ /g;
                   9143:     return $name;
                   9144: }
                   9145: 
1.84      www      9146: # ------------------------------------------------- Write to course preferences
                   9147: 
                   9148: sub writecoursepref {
                   9149:     my ($courseid,%prefs)=@_;
                   9150:     $courseid=~s/^\///;
                   9151:     $courseid=~s/\_/\//g;
                   9152:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9153:     my $chome=homeserver($cnum,$cdomain);
                   9154:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9155: 	return 'error: no such course';
                   9156:     }
                   9157:     my $cstring='';
1.800     albertel 9158:     foreach my $pref (keys(%prefs)) {
                   9159: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9160:     }
1.84      www      9161:     $cstring=~s/\&$//;
                   9162:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9163: }
                   9164: 
                   9165: # ---------------------------------------------------------- Make/modify course
                   9166: 
                   9167: sub createcourse {
1.741     raeburn  9168:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9169:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9170:     $url=&declutter($url);
                   9171:     my $cid='';
1.1028    raeburn  9172:     if ($context eq 'requestcourses') {
                   9173:         my $can_create = 0;
                   9174:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9175:         if ($udom eq $ownerdom) {
                   9176:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9177:                                   $context)) {
                   9178:                 $can_create = 1;
                   9179:             }
                   9180:         } else {
                   9181:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9182:                                            $category);
                   9183:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9184:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9185:                 if (@curr > 0) {
                   9186:                     my @options = qw(approval validate autolimit);
                   9187:                     my $optregex = join('|',@options);
                   9188:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9189:                         $can_create = 1;
                   9190:                     }
                   9191:                 }
                   9192:             }
                   9193:         }
                   9194:         if ($can_create) {
                   9195:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9196:                 unless (&allowed('ccc',$udom)) {
                   9197:                     return 'refused'; 
                   9198:                 }
1.1017    raeburn  9199:             }
                   9200:         } else {
                   9201:             return 'refused';
                   9202:         }
1.1028    raeburn  9203:     } elsif (!&allowed('ccc',$udom)) {
                   9204:         return 'refused';
1.84      www      9205:     }
1.1011    raeburn  9206: # --------------------------------------------------------------- Get Unique ID
                   9207:     my $uname;
                   9208:     if ($cnum =~ /^$match_courseid$/) {
                   9209:         my $chome=&homeserver($cnum,$udom,'true');
                   9210:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9211:             $uname = $cnum;
                   9212:         } else {
1.1038    raeburn  9213:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9214:         }
                   9215:     } else {
1.1038    raeburn  9216:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9217:     }
                   9218:     return $uname if ($uname =~ /^error/);
                   9219: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9220:     if (!defined($course_server)) {
                   9221:         if (defined(&domain($udom,'primary'))) {
                   9222:             $course_server = &domain($udom,'primary');
                   9223:         } else {
                   9224:             $course_server = $env{'user.home'}; 
                   9225:         }
                   9226:     }
                   9227:     my %host_servers =
                   9228:         &Apache::lonnet::get_servers($udom,'library');
                   9229:     unless ($host_servers{$course_server}) {
                   9230:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9231:     }
1.84      www      9232: # ------------------------------------------------------------- Make the course
                   9233:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9234:                       $course_server);
1.84      www      9235:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9236:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9237:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9238: 	return 'error: no such course';
                   9239:     }
1.271     www      9240: # ----------------------------------------------------------------- Course made
1.516     raeburn  9241: # log existence
1.1029    raeburn  9242:     my $now = time;
1.918     raeburn  9243:     my $newcourse = {
                   9244:                     $udom.'_'.$uname => {
1.921     raeburn  9245:                                      description => $description,
                   9246:                                      inst_code   => $inst_code,
                   9247:                                      owner       => $course_owner,
                   9248:                                      type        => $crstype,
1.1029    raeburn  9249:                                      creator     => $env{'user.name'}.':'.
                   9250:                                                     $env{'user.domain'},
                   9251:                                      created     => $now,
                   9252:                                      context     => $context,
1.918     raeburn  9253:                                                 },
                   9254:                     };
1.921     raeburn  9255:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9256: # set toplevel url
1.271     www      9257:     my $topurl=$url;
                   9258:     unless ($nonstandard) {
                   9259: # ------------------------------------------ For standard courses, make top url
                   9260:         my $mapurl=&clutter($url);
1.278     www      9261:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9262:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9263: <map>
                   9264: <resource id="1" type="start"></resource>
                   9265: <resource id="2" src="$mapurl"></resource>
                   9266: <resource id="3" type="finish"></resource>
                   9267: <link index="1" from="1" to="2"></link>
                   9268: <link index="2" from="2" to="3"></link>
                   9269: </map>
                   9270: ENDINITMAP
                   9271:         $topurl=&declutter(
1.638     albertel 9272:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9273:                           );
                   9274:     }
                   9275: # ----------------------------------------------------------- Write preferences
1.84      www      9276:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9277:                      ('description'              => $description,
                   9278:                       'url'                      => $topurl,
                   9279:                       'internal.creator'         => $env{'user.name'}.':'.
                   9280:                                                     $env{'user.domain'},
                   9281:                       'internal.created'         => $now,
                   9282:                       'internal.creationcontext' => $context)
                   9283:                     );
1.84      www      9284:     return '/'.$udom.'/'.$uname;
                   9285: }
                   9286: 
1.1011    raeburn  9287: # ------------------------------------------------------------------- Create ID
                   9288: sub generate_coursenum {
1.1038    raeburn  9289:     my ($udom,$crstype) = @_;
1.1011    raeburn  9290:     my $domdesc = &domain($udom);
                   9291:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9292:     my $first;
                   9293:     if ($crstype eq 'Community') {
                   9294:         $first = '0';
                   9295:     } else {
                   9296:         $first = int(1+rand(9)); 
                   9297:     } 
                   9298:     my $uname=$first.
1.1011    raeburn  9299:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9300:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9301:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9302: # ----------------------------------------------- Make sure that does not exist
                   9303:     my $uhome=&homeserver($uname,$udom,'true');
                   9304:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9305:         if ($crstype eq 'Community') {
                   9306:             $first = '0';
                   9307:         } else {
                   9308:             $first = int(1+rand(9));
                   9309:         }
                   9310:         $uname=$first.
1.1011    raeburn  9311:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9312:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9313:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9314:         $uhome=&homeserver($uname,$udom,'true');
                   9315:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9316:             return 'error: unable to generate unique course-ID';
                   9317:         }
                   9318:     }
                   9319:     return $uname;
                   9320: }
                   9321: 
1.813     albertel 9322: sub is_course {
1.1167    droeschl 9323:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9324:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9325: 
                   9326:     return unless $cdom and $cnum;
                   9327: 
                   9328:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9329:         '.');
                   9330: 
1.1172.2.23  raeburn  9331:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9332:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9333: }
                   9334: 
1.1015    raeburn  9335: sub store_userdata {
                   9336:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9337:     my $result;
1.1016    raeburn  9338:     if ($datakey ne '') {
1.1013    raeburn  9339:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9340:             if ($udom eq '' || $uname eq '') {
                   9341:                 $udom = $env{'user.domain'};
                   9342:                 $uname = $env{'user.name'};
                   9343:             }
                   9344:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9345:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9346:                 $result = 'error: no_host';
                   9347:             } else {
                   9348:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9349:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9350: 
                   9351:                 my $namevalue='';
                   9352:                 foreach my $key (keys(%{$storehash})) {
                   9353:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9354:                 }
                   9355:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9356:                 unless ($namespace eq 'courserequests') {
                   9357:                     $datakey = &escape($datakey);
                   9358:                 }
1.1105    raeburn  9359:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9360:                                   $namevalue,$uhome);
1.1013    raeburn  9361:             }
                   9362:         } else {
                   9363:             $result = 'error: data to store was not a hash reference'; 
                   9364:         }
                   9365:     } else {
                   9366:         $result= 'error: invalid requestkey'; 
                   9367:     }
                   9368:     return $result;
                   9369: }
                   9370: 
1.21      www      9371: # ---------------------------------------------------------- Assign Custom Role
                   9372: 
                   9373: sub assigncustomrole {
1.957     raeburn  9374:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9375:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9376:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9377: }
                   9378: 
                   9379: # ----------------------------------------------------------------- Revoke Role
                   9380: 
                   9381: sub revokerole {
1.957     raeburn  9382:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9383:     my $now=time;
1.965     raeburn  9384:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9385: }
                   9386: 
                   9387: # ---------------------------------------------------------- Revoke Custom Role
                   9388: 
                   9389: sub revokecustomrole {
1.957     raeburn  9390:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9391:     my $now=time;
1.357     www      9392:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9393:            $deleteflag,$selfenroll,$context);
1.17      www      9394: }
                   9395: 
1.533     banghart 9396: # ------------------------------------------------------------ Disk usage
1.535     albertel 9397: sub diskusage {
1.955     raeburn  9398:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9399:     $directorypath =~ s/\/$//;
                   9400:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9401:                        .&escape($getpropath).':'.&escape($uname).':'
                   9402:                        .&escape($udom),homeserver($uname,$udom));
                   9403:     if ($listing eq 'unknown_cmd') {
                   9404:         if ($getpropath) {
                   9405:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9406:         }
                   9407:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9408:     }
1.514     albertel 9409:     return $listing;
1.512     banghart 9410: }
                   9411: 
1.566     banghart 9412: sub is_locked {
1.1096    raeburn  9413:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9414:     my @check;
                   9415:     my $is_locked;
1.1093    raeburn  9416:     push (@check,$file_name);
1.613     albertel 9417:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9418: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9419:     my ($tmp)=keys(%locked);
                   9420:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9421:     
1.566     banghart 9422:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9423:         $is_locked = 'false';
                   9424:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9425:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9426:                $is_locked = 'true';
1.1096    raeburn  9427:                if (ref($which) eq 'ARRAY') {
                   9428:                    push(@{$which},$entry);
                   9429:                } else {
                   9430:                    last;
                   9431:                }
1.745     raeburn  9432:            }
                   9433:        }
1.566     banghart 9434:     } else {
                   9435:         $is_locked = 'false';
                   9436:     }
1.1093    raeburn  9437:     return $is_locked;
1.566     banghart 9438: }
                   9439: 
1.759     albertel 9440: sub declutter_portfile {
                   9441:     my ($file) = @_;
1.833     albertel 9442:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9443:     return $file;
                   9444: }
                   9445: 
1.559     banghart 9446: # ------------------------------------------------------------- Mark as Read Only
                   9447: 
                   9448: sub mark_as_readonly {
                   9449:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9450:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9451:     my ($tmp)=keys(%current_permissions);
                   9452:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9453:     foreach my $file (@{$files}) {
1.759     albertel 9454: 	$file = &declutter_portfile($file);
1.561     banghart 9455:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9456:     }
1.613     albertel 9457:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9458:     return;
                   9459: }
                   9460: 
1.572     banghart 9461: # ------------------------------------------------------------Save Selected Files
                   9462: 
                   9463: sub save_selected_files {
                   9464:     my ($user, $path, @files) = @_;
                   9465:     my $filename = $user."savedfiles";
1.573     banghart 9466:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9467:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9468:     foreach my $file (@files) {
1.620     albertel 9469:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9470:     }
                   9471:     foreach my $file (@other_files) {
1.574     banghart 9472:         print (OUT $file."\n");
1.572     banghart 9473:     }
1.574     banghart 9474:     close (OUT);
1.572     banghart 9475:     return 'ok';
                   9476: }
                   9477: 
1.574     banghart 9478: sub clear_selected_files {
                   9479:     my ($user) = @_;
                   9480:     my $filename = $user."savedfiles";
1.1117    foxr     9481:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9482:     print (OUT undef);
                   9483:     close (OUT);
                   9484:     return ("ok");    
                   9485: }
                   9486: 
1.572     banghart 9487: sub files_in_path {
                   9488:     my ($user, $path) = @_;
                   9489:     my $filename = $user."savedfiles";
                   9490:     my %return_files;
1.1117    foxr     9491:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9492:     while (my $line_in = <IN>) {
1.574     banghart 9493:         chomp ($line_in);
                   9494:         my @paths_and_file = split (m!/!, $line_in);
                   9495:         my $file_part = pop (@paths_and_file);
                   9496:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9497:         $path_part.='/';
                   9498:         my $path_and_file = $path_part.$file_part;
                   9499:         if ($path_part eq $path) {
                   9500:             $return_files{$file_part}= 'selected';
                   9501:         }
                   9502:     }
1.574     banghart 9503:     close (IN);
                   9504:     return (\%return_files);
1.572     banghart 9505: }
                   9506: 
                   9507: # called in portfolio select mode, to show files selected NOT in current directory
                   9508: sub files_not_in_path {
                   9509:     my ($user, $path) = @_;
                   9510:     my $filename = $user."savedfiles";
                   9511:     my @return_files;
                   9512:     my $path_part;
1.1117    foxr     9513:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9514:     while (my $line = <IN>) {
1.572     banghart 9515:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9516:         my @paths_and_file = split(m|/|, $line);
                   9517:         my $file_part = pop(@paths_and_file);
                   9518:         chomp($file_part);
                   9519:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9520:         $path_part .= '/';
                   9521:         my $path_and_file = $path_part.$file_part;
                   9522:         if ($path_part ne $path) {
1.800     albertel 9523:             push(@return_files, ($path_and_file));
1.572     banghart 9524:         }
                   9525:     }
1.800     albertel 9526:     close(OUT);
1.574     banghart 9527:     return (@return_files);
1.572     banghart 9528: }
                   9529: 
1.745     raeburn  9530: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9531: 
1.745     raeburn  9532: sub get_portfile_permissions {
                   9533:     my ($domain,$user) = @_;
1.613     albertel 9534:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9535:     my ($tmp)=keys(%current_permissions);
                   9536:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9537:     return \%current_permissions;
                   9538: }
                   9539: 
                   9540: #---------------------------------------------Get portfolio file access controls
                   9541: 
1.749     raeburn  9542: sub get_access_controls {
1.745     raeburn  9543:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9544:     my %access;
                   9545:     my $real_file = $file;
                   9546:     $file =~ s/\.meta$//;
1.745     raeburn  9547:     if (defined($file)) {
1.749     raeburn  9548:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9549:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9550:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9551:             }
                   9552:         }
1.745     raeburn  9553:     } else {
1.749     raeburn  9554:         foreach my $key (keys(%{$current_permissions})) {
                   9555:             if ($key =~ /\0accesscontrol$/) {
                   9556:                 if (defined($group)) {
                   9557:                     if ($key !~ m-^\Q$group\E/-) {
                   9558:                         next;
                   9559:                     }
                   9560:                 }
                   9561:                 my ($fullpath) = split(/\0/,$key);
                   9562:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9563:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9564:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9565:                     }
                   9566:                 }
                   9567:             }
                   9568:         }
                   9569:     }
                   9570:     return %access;
                   9571: }
                   9572: 
                   9573: sub modify_access_controls {
                   9574:     my ($file_name,$changes,$domain,$user)=@_;
                   9575:     my ($outcome,$deloutcome);
                   9576:     my %store_permissions;
                   9577:     my %new_values;
                   9578:     my %new_control;
                   9579:     my %translation;
                   9580:     my @deletions = ();
                   9581:     my $now = time;
                   9582:     if (exists($$changes{'activate'})) {
                   9583:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9584:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9585:             my $numnew = scalar(@newitems);
                   9586:             for (my $i=0; $i<$numnew; $i++) {
                   9587:                 my $newkey = $newitems[$i];
                   9588:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9589:                 if ($newkey =~ /^\d+:/) { 
                   9590:                     $newkey =~ s/^(\d+)/$newid/;
                   9591:                     $translation{$1} = $newid;
                   9592:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9593:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9594:                     $translation{$1} = $newid;
                   9595:                 }
1.749     raeburn  9596:                 $new_values{$file_name."\0".$newkey} = 
                   9597:                                           $$changes{'activate'}{$newitems[$i]};
                   9598:                 $new_control{$newkey} = $now;
                   9599:             }
                   9600:         }
                   9601:     }
                   9602:     my %todelete;
                   9603:     my %changed_items;
                   9604:     foreach my $action ('delete','update') {
                   9605:         if (exists($$changes{$action})) {
                   9606:             if (ref($$changes{$action}) eq 'HASH') {
                   9607:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9608:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9609:                     if ($action eq 'delete') { 
                   9610:                         $todelete{$itemnum} = 1;
                   9611:                     } else {
                   9612:                         $changed_items{$itemnum} = $key;
                   9613:                     }
                   9614:                 }
1.745     raeburn  9615:             }
                   9616:         }
1.749     raeburn  9617:     }
                   9618:     # get lock on access controls for file.
                   9619:     my $lockhash = {
                   9620:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9621:                                                        ':'.$env{'user.domain'},
                   9622:                    }; 
                   9623:     my $tries = 0;
                   9624:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9625:    
1.1172.2.79  raeburn  9626:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9627:         $tries ++;
1.1172.2.79  raeburn  9628:         sleep(0.1);
1.749     raeburn  9629:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9630:     }
                   9631:     if ($gotlock eq 'ok') {
                   9632:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9633:         my ($tmp)=keys(%curr_permissions);
                   9634:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9635:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9636:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9637:             if (ref($curr_controls) eq 'HASH') {
                   9638:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9639:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9640:                     if (defined($todelete{$itemnum})) {
                   9641:                         push(@deletions,$file_name."\0".$control_item);
                   9642:                     } else {
                   9643:                         if (defined($changed_items{$itemnum})) {
                   9644:                             $new_control{$changed_items{$itemnum}} = $now;
                   9645:                             push(@deletions,$file_name."\0".$control_item);
                   9646:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9647:                         } else {
                   9648:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9649:                         }
                   9650:                     }
1.745     raeburn  9651:                 }
                   9652:             }
                   9653:         }
1.970     raeburn  9654:         my ($group);
                   9655:         if (&is_course($domain,$user)) {
                   9656:             ($group,my $file) = split(/\//,$file_name,2);
                   9657:         }
1.749     raeburn  9658:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9659:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9660:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9661:         #  remove lock
                   9662:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9663:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9664:         my $sqlresult =
1.970     raeburn  9665:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9666:                                     $group);
1.749     raeburn  9667:     } else {
                   9668:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9669:     }
1.749     raeburn  9670:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9671: }
                   9672: 
1.827     raeburn  9673: sub make_public_indefinitely {
                   9674:     my ($requrl) = @_;
                   9675:     my $now = time;
                   9676:     my $action = 'activate';
                   9677:     my $aclnum = 0;
                   9678:     if (&is_portfolio_url($requrl)) {
                   9679:         my (undef,$udom,$unum,$file_name,$group) =
                   9680:             &parse_portfolio_url($requrl);
                   9681:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9682:         my %access_controls = &get_access_controls($current_perms,
                   9683:                                                    $group,$file_name);
                   9684:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9685:             my ($num,$scope,$end,$start) = 
                   9686:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9687:             if ($scope eq 'public') {
                   9688:                 if ($start <= $now && $end == 0) {
                   9689:                     $action = 'none';
                   9690:                 } else {
                   9691:                     $action = 'update';
                   9692:                     $aclnum = $num;
                   9693:                 }
                   9694:                 last;
                   9695:             }
                   9696:         }
                   9697:         if ($action eq 'none') {
                   9698:              return 'ok';
                   9699:         } else {
                   9700:             my %changes;
                   9701:             my $newend = 0;
                   9702:             my $newstart = $now;
                   9703:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   9704:             $changes{$action}{$newkey} = {
                   9705:                 type => 'public',
                   9706:                 time => {
                   9707:                     start => $newstart,
                   9708:                     end   => $newend,
                   9709:                 },
                   9710:             };
                   9711:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9712:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   9713:             return $outcome;
                   9714:         }
                   9715:     } else {
                   9716:         return 'invalid';
                   9717:     }
                   9718: }
                   9719: 
1.745     raeburn  9720: #------------------------------------------------------Get Marked as Read Only
                   9721: 
                   9722: sub get_marked_as_readonly {
                   9723:     my ($domain,$user,$what,$group) = @_;
                   9724:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9725:     my @readonly_files;
1.629     banghart 9726:     my $cmp1=$what;
                   9727:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9728:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9729:         if (defined($group)) {
                   9730:             if ($file_name !~ m-^\Q$group\E/-) {
                   9731:                 next;
                   9732:             }
                   9733:         }
1.561     banghart 9734:         if (ref($value) eq "ARRAY"){
                   9735:             foreach my $stored_what (@{$value}) {
1.629     banghart 9736:                 my $cmp2=$stored_what;
1.759     albertel 9737:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9738:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9739:                 }
1.629     banghart 9740:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9741:                     push(@readonly_files, $file_name);
1.745     raeburn  9742:                     last;
1.563     banghart 9743:                 } elsif (!defined($what)) {
                   9744:                     push(@readonly_files, $file_name);
1.745     raeburn  9745:                     last;
1.561     banghart 9746:                 }
                   9747:             }
1.745     raeburn  9748:         }
1.561     banghart 9749:     }
                   9750:     return @readonly_files;
                   9751: }
1.577     banghart 9752: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9753: 
1.577     banghart 9754: sub get_marked_as_readonly_hash {
1.745     raeburn  9755:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9756:     my %readonly_files;
1.745     raeburn  9757:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9758:         if (defined($group)) {
                   9759:             if ($file_name !~ m-^\Q$group\E/-) {
                   9760:                 next;
                   9761:             }
                   9762:         }
1.577     banghart 9763:         if (ref($value) eq "ARRAY"){
                   9764:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9765:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9766:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9767:                         if ($lock_descriptor eq 'graded') {
                   9768:                             $readonly_files{$file_name} = 'graded';
                   9769:                         } elsif ($lock_descriptor eq 'handback') {
                   9770:                             $readonly_files{$file_name} = 'handback';
                   9771:                         } else {
                   9772:                             if (!exists($readonly_files{$file_name})) {
                   9773:                                 $readonly_files{$file_name} = 'locked';
                   9774:                             }
                   9775:                         }
1.745     raeburn  9776:                     }
1.750     banghart 9777:                 } 
1.577     banghart 9778:             }
                   9779:         } 
                   9780:     }
                   9781:     return %readonly_files;
                   9782: }
1.559     banghart 9783: # ------------------------------------------------------------ Unmark as Read Only
                   9784: 
                   9785: sub unmark_as_readonly {
1.629     banghart 9786:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9787:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9788:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9789:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9790:     my $symb_crs = $what;
                   9791:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9792:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9793:     my ($tmp)=keys(%current_permissions);
                   9794:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9795:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9796:     foreach my $file (@readonly_files) {
1.759     albertel 9797: 	my $clean_file = &declutter_portfile($file);
                   9798: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9799: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9800:         my @new_locks;
                   9801:         my @del_keys;
                   9802:         if (ref($current_locks) eq "ARRAY"){
                   9803:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9804:                 my $compare=$locker;
1.749     raeburn  9805:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9806:                     $compare=join('',@{$locker});
1.746     raeburn  9807:                     if ($compare ne $symb_crs) {
                   9808:                         push(@new_locks, $locker);
                   9809:                     }
1.563     banghart 9810:                 }
                   9811:             }
1.650     albertel 9812:             if (scalar(@new_locks) > 0) {
1.563     banghart 9813:                 $current_permissions{$file} = \@new_locks;
                   9814:             } else {
                   9815:                 push(@del_keys, $file);
1.613     albertel 9816:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9817:                 delete($current_permissions{$file});
1.563     banghart 9818:             }
                   9819:         }
1.561     banghart 9820:     }
1.613     albertel 9821:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9822:     return;
                   9823: }
1.512     banghart 9824: 
1.17      www      9825: # ------------------------------------------------------------ Directory lister
                   9826: 
                   9827: sub dirlist {
1.955     raeburn  9828:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9829:     $uri=~s/^\///;
                   9830:     $uri=~s/\/$//;
1.253     stredwic 9831:     my ($udom, $uname);
1.955     raeburn  9832:     if ($getuserdir) {
1.253     stredwic 9833:         $udom = $userdomain;
                   9834:         $uname = $username;
1.955     raeburn  9835:     } else {
                   9836:         (undef,$udom,$uname)=split(/\//,$uri);
                   9837:         if(defined($userdomain)) {
                   9838:             $udom = $userdomain;
                   9839:         }
                   9840:         if(defined($username)) {
                   9841:             $uname = $username;
                   9842:         }
1.253     stredwic 9843:     }
1.955     raeburn  9844:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9845: 
1.955     raeburn  9846:     $dirRoot = $perlvar{'lonDocRoot'};
                   9847:     if (defined($getpropath)) {
                   9848:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9849:         $dirRoot =~ s/\/$//;
1.955     raeburn  9850:     } elsif (defined($getuserdir)) {
                   9851:         my $subdir=$uname.'__';
                   9852:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9853:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9854:                    ."/$udom/$subdir/$uname";
                   9855:     } elsif (defined($alternateRoot)) {
                   9856:         $dirRoot = $alternateRoot;
1.751     banghart 9857:     }
1.253     stredwic 9858: 
                   9859:     if($udom) {
                   9860:         if($uname) {
1.1135    raeburn  9861:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9862:             if ($uhome eq 'no_host') {
                   9863:                 return ([],'no_host');
                   9864:             }
1.955     raeburn  9865:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9866:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9867:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9868:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9869:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9870:             } else {
                   9871:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9872:             }
1.605     matthew  9873:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9874:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9875:                 @listing_results = split(/:/,$listing);
                   9876:             } else {
                   9877:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9878:             }
1.1135    raeburn  9879:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9880:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9881:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9882:                 return ([],$listing);
                   9883:             } else {
                   9884:                 return (\@listing_results);
1.1135    raeburn  9885:             }
1.955     raeburn  9886:         } elsif(!$alternateRoot) {
1.1136    raeburn  9887:             my (%allusers,%listerror);
1.841     albertel 9888: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9889:  	    foreach my $tryserver (keys(%servers)) {
                   9890:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9891:                                   &escape($udom),$tryserver);
                   9892:                 if ($listing eq 'unknown_cmd') {
                   9893: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9894: 				      $udom, $tryserver);
                   9895:                 } else {
                   9896:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9897:                 }
1.841     albertel 9898: 		if ($listing eq 'unknown_cmd') {
                   9899: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9900: 				      $udom, $tryserver);
                   9901: 		    @listing_results = split(/:/,$listing);
                   9902: 		} else {
                   9903: 		    @listing_results =
                   9904: 			map { &unescape($_); } split(/:/,$listing);
                   9905: 		}
1.1136    raeburn  9906:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9907:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9908:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9909:                     $listerror{$tryserver} = $listing;
                   9910:                 } else {
1.841     albertel 9911: 		    foreach my $line (@listing_results) {
                   9912: 			my ($entry) = split(/&/,$line,2);
                   9913: 			$allusers{$entry} = 1;
                   9914: 		    }
                   9915: 		}
1.253     stredwic 9916:             }
1.1136    raeburn  9917:             my @alluserslist=();
1.800     albertel 9918:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9919:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9920:             }
1.1172.2.80  raeburn  9921:             if (!%listerror) {
                   9922:                 # no errors
                   9923:                 return (\@alluserslist);
                   9924:             } elsif (scalar(keys(%servers)) == 1) {
                   9925:                 # one library server, one error
                   9926:                 my ($key) = keys(%listerror);
                   9927:                 return (\@alluserslist, $listerror{$key});
                   9928:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   9929:                 # con_lost indicates that we might miss data from at least one
                   9930:                 # library server
                   9931:                 return (\@alluserslist, 'con_lost');
                   9932:             } else {
                   9933:                 # multiple library servers and no con_lost -> data should be
                   9934:                 # complete.
                   9935:                 return (\@alluserslist);
                   9936:             }
                   9937: 
1.253     stredwic 9938:         } else {
1.1136    raeburn  9939:             return ([],'missing username');
1.253     stredwic 9940:         }
1.955     raeburn  9941:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9942:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9943:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9944:         return (\@all_domains);
1.955     raeburn  9945:     } else {
1.1136    raeburn  9946:         return ([],'missing domain');
1.275     stredwic 9947:     }
                   9948: }
                   9949: 
                   9950: # --------------------------------------------- GetFileTimestamp
                   9951: # This function utilizes dirlist and returns the date stamp for
                   9952: # when it was last modified.  It will also return an error of -1
                   9953: # if an error occurs
                   9954: 
                   9955: sub GetFileTimestamp {
1.955     raeburn  9956:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9957:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9958:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9959:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9960:                                     undef,$getuserdir);
                   9961:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9962:         return -1;
                   9963:     }
                   9964:     if (ref($fileref) eq 'ARRAY') {
                   9965:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9966:         # @stats contains first the filename, then the stat output
                   9967:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9968:     } else {
                   9969:         return -1;
1.253     stredwic 9970:     }
1.26      www      9971: }
                   9972: 
1.712     albertel 9973: sub stat_file {
                   9974:     my ($uri) = @_;
1.787     albertel 9975:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9976: 
1.955     raeburn  9977:     my ($udom,$uname,$file);
1.712     albertel 9978:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   9979: 	($udom,$uname,$file) =
1.811     albertel 9980: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 9981: 	$file = 'userfiles/'.$file;
                   9982:     }
                   9983:     if ($uri =~ m-^/res/-) {
                   9984: 	($udom,$uname) = 
1.807     albertel 9985: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 9986: 	$file = $uri;
                   9987:     }
                   9988: 
                   9989:     if (!$udom || !$uname || !$file) {
                   9990: 	# unable to handle the uri
                   9991: 	return ();
                   9992:     }
1.956     raeburn  9993:     my $getpropath;
                   9994:     if ($file =~ /^userfiles\//) {
                   9995:         $getpropath = 1;
                   9996:     }
1.1136    raeburn  9997:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   9998:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9999:         return ();
                   10000:     } else {
                   10001:         if (ref($listref) eq 'ARRAY') {
                   10002:             my @stats = split('&',$listref->[0]);
                   10003: 	    shift(@stats); #filename is first
                   10004: 	    return @stats;
                   10005:         }
1.712     albertel 10006:     }
                   10007:     return ();
                   10008: }
                   10009: 
1.26      www      10010: # -------------------------------------------------------- Value of a Condition
                   10011: 
1.713     albertel 10012: # gets the value of a specific preevaluated condition
                   10013: #    stored in the string  $env{user.state.<cid>}
                   10014: # or looks up a condition reference in the bighash and if if hasn't
                   10015: # already been evaluated recurses into docondval to get the value of
                   10016: # the condition, then memoizing it to 
                   10017: #   $env{user.state.<cid>.<condition>}
1.40      www      10018: sub directcondval {
                   10019:     my $number=shift;
1.620     albertel 10020:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10021: 	&Apache::lonuserstate::evalstate();
                   10022:     }
1.713     albertel 10023:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10024: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10025:     } elsif ($number =~ /^_/) {
                   10026: 	my $sub_condition;
                   10027: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10028: 		&GDBM_READER(),0640)) {
                   10029: 	    $sub_condition=$bighash{'conditions'.$number};
                   10030: 	    untie(%bighash);
                   10031: 	}
                   10032: 	my $value = &docondval($sub_condition);
1.949     raeburn  10033: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10034: 	return $value;
                   10035:     }
1.620     albertel 10036:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10037:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10038:     } else {
                   10039:        return 2;
                   10040:     }
                   10041: }
                   10042: 
1.713     albertel 10043: # get the collection of conditions for this resource
1.26      www      10044: sub condval {
                   10045:     my $condidx=shift;
1.54      www      10046:     my $allpathcond='';
1.713     albertel 10047:     foreach my $cond (split(/\|/,$condidx)) {
                   10048: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10049: 	    $allpathcond.=
                   10050: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10051: 	}
1.191     harris41 10052:     }
1.54      www      10053:     $allpathcond=~s/\|$//;
1.713     albertel 10054:     return &docondval($allpathcond);
                   10055: }
                   10056: 
                   10057: #evaluates an expression of conditions
                   10058: sub docondval {
                   10059:     my ($allpathcond) = @_;
                   10060:     my $result=0;
                   10061:     if ($env{'request.course.id'}
                   10062: 	&& defined($allpathcond)) {
                   10063: 	my $operand='|';
                   10064: 	my @stack;
                   10065: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10066: 	    if ($chunk eq '(') {
                   10067: 		push @stack,($operand,$result);
                   10068: 	    } elsif ($chunk eq ')') {
                   10069: 		my $before=pop @stack;
                   10070: 		if (pop @stack eq '&') {
                   10071: 		    $result=$result>$before?$before:$result;
                   10072: 		} else {
                   10073: 		    $result=$result>$before?$result:$before;
                   10074: 		}
                   10075: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10076: 		$operand=$chunk;
                   10077: 	    } else {
                   10078: 		my $new=directcondval($chunk);
                   10079: 		if ($operand eq '&') {
                   10080: 		    $result=$result>$new?$new:$result;
                   10081: 		} else {
                   10082: 		    $result=$result>$new?$result:$new;
                   10083: 		}
                   10084: 	    }
                   10085: 	}
1.26      www      10086:     }
                   10087:     return $result;
1.421     albertel 10088: }
                   10089: 
                   10090: # ---------------------------------------------------- Devalidate courseresdata
                   10091: 
                   10092: sub devalidatecourseresdata {
                   10093:     my ($coursenum,$coursedomain)=@_;
                   10094:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10095:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10096: }
                   10097: 
1.763     www      10098: 
1.200     www      10099: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10100: #
                   10101: #  Parameters:
                   10102: #      $coursenum    - Number of the course.
                   10103: #      $coursedomain - Domain at which the course was created.
                   10104: #  Returns:
                   10105: #     A hash of the course parameters along (I think) with timestamps
                   10106: #     and version info.
1.877     foxr     10107: 
1.624     albertel 10108: sub get_courseresdata {
                   10109:     my ($coursenum,$coursedomain)=@_;
1.200     www      10110:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10111:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10112:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10113:     my %dumpreply;
1.417     albertel 10114:     unless (defined($cached)) {
1.624     albertel 10115: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10116: 	$result=\%dumpreply;
1.251     albertel 10117: 	my ($tmp) = keys(%dumpreply);
                   10118: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10119: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10120: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10121: 	    return $tmp;
1.416     albertel 10122: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10123: 	    $result=undef;
1.599     albertel 10124: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10125: 	}
                   10126:     }
1.624     albertel 10127:     return $result;
                   10128: }
                   10129: 
1.633     albertel 10130: sub devalidateuserresdata {
                   10131:     my ($uname,$udom)=@_;
                   10132:     my $hashid="$udom:$uname";
                   10133:     &devalidate_cache_new('userres',$hashid);
                   10134: }
                   10135: 
1.624     albertel 10136: sub get_userresdata {
                   10137:     my ($uname,$udom)=@_;
                   10138:     #most student don\'t have any data set, check if there is some data
                   10139:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10140: 
                   10141:     my $hashid="$udom:$uname";
                   10142:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10143:     if (!defined($cached)) {
                   10144: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10145: 	$result=\%resourcedata;
                   10146: 	&do_cache_new('userres',$hashid,$result,600);
                   10147:     }
                   10148:     my ($tmp)=keys(%$result);
                   10149:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10150: 	return $result;
                   10151:     }
                   10152:     #error 2 occurs when the .db doesn't exist
                   10153:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  10154:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10155: 	    &logthis("<font color=\"blue\">WARNING:".
                   10156: 		     " Trying to get resource data for ".
                   10157: 		     $uname." at ".$udom.": ".
                   10158: 		     $tmp."</font>");
                   10159:         }
1.624     albertel 10160:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10161: 	#&EXT_cache_set($udom,$uname);
                   10162: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10163: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10164:     }
                   10165:     return $tmp;
                   10166: }
1.879     foxr     10167: #----------------------------------------------- resdata - return resource data
                   10168: #  Purpose:
                   10169: #    Return resource data for either users or for a course.
                   10170: #  Parameters:
                   10171: #     $name      - Course/user name.
                   10172: #     $domain    - Name of the domain the user/course is registered on.
                   10173: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   10174: #     @which     - Array of names of resources desired.
                   10175: #  Returns:
                   10176: #     The value of the first reasource in @which that is found in the
                   10177: #     resource hash.
                   10178: #  Exceptional Conditions:
                   10179: #     If the $type passed in is not valid (not the string 'course' or 
                   10180: #     'user', an undefined  reference is returned.
                   10181: #     If none of the resources are found, an undef is returned
1.624     albertel 10182: sub resdata {
                   10183:     my ($name,$domain,$type,@which)=@_;
                   10184:     my $result;
                   10185:     if ($type eq 'course') {
                   10186: 	$result=&get_courseresdata($name,$domain);
                   10187:     } elsif ($type eq 'user') {
                   10188: 	$result=&get_userresdata($name,$domain);
                   10189:     }
                   10190:     if (!ref($result)) { return $result; }    
1.251     albertel 10191:     foreach my $item (@which) {
1.927     albertel 10192: 	if (defined($result->{$item->[0]})) {
                   10193: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10194: 	}
1.250     albertel 10195:     }
1.291     albertel 10196:     return undef;
1.200     www      10197: }
                   10198: 
1.1172.2.31  raeburn  10199: sub get_numsuppfiles {
                   10200:     my ($cnum,$cdom,$ignorecache)=@_;
                   10201:     my $hashid=$cnum.':'.$cdom;
                   10202:     my ($suppcount,$cached);
                   10203:     unless ($ignorecache) {
                   10204:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10205:     }
                   10206:     unless (defined($cached)) {
                   10207:         my $chome=&homeserver($cnum,$cdom);
                   10208:         unless ($chome eq 'no_host') {
                   10209:             ($suppcount,my $errors) = (0,0);
                   10210:             my $suppmap = 'supplemental.sequence';
                   10211:             ($suppcount,$errors) =
                   10212:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10213:         }
                   10214:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10215:     }
                   10216:     return $suppcount;
                   10217: }
                   10218: 
1.379     matthew  10219: #
                   10220: # EXT resource caching routines
                   10221: #
                   10222: 
                   10223: sub clear_EXT_cache_status {
1.383     albertel 10224:     &delenv('cache.EXT.');
1.379     matthew  10225: }
                   10226: 
                   10227: sub EXT_cache_status {
                   10228:     my ($target_domain,$target_user) = @_;
1.383     albertel 10229:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10230:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10231:         # We know already the user has no data
                   10232:         return 1;
                   10233:     } else {
                   10234:         return 0;
                   10235:     }
                   10236: }
                   10237: 
                   10238: sub EXT_cache_set {
                   10239:     my ($target_domain,$target_user) = @_;
1.383     albertel 10240:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10241:     #&appenv({$cachename => time});
1.379     matthew  10242: }
                   10243: 
1.28      www      10244: # --------------------------------------------------------- Value of a Variable
1.58      www      10245: sub EXT {
1.715     albertel 10246: 
1.1172.2.28  raeburn  10247:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10248:     unless ($varname) { return ''; }
1.218     albertel 10249:     #get real user name/domain, courseid and symb
                   10250:     my $courseid;
1.359     albertel 10251:     my $publicuser;
1.427     www      10252:     if ($symbparm) {
                   10253: 	$symbparm=&get_symb_from_alias($symbparm);
                   10254:     }
1.218     albertel 10255:     if (!($uname && $udom)) {
1.790     albertel 10256:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10257:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10258:     } else {
1.620     albertel 10259: 	$courseid=$env{'request.course.id'};
1.218     albertel 10260:     }
1.48      www      10261:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10262:     my $rest;
1.320     albertel 10263:     if (defined($therest[0])) {
1.48      www      10264:        $rest=join('.',@therest);
                   10265:     } else {
                   10266:        $rest='';
                   10267:     }
1.320     albertel 10268: 
1.57      www      10269:     my $qualifierrest=$qualifier;
                   10270:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10271:     my $spacequalifierrest=$space;
                   10272:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10273:     if ($realm eq 'user') {
1.48      www      10274: # --------------------------------------------------------------- user.resource
                   10275: 	if ($space eq 'resource') {
1.651     albertel 10276: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10277: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10278: 		 &&
1.744     albertel 10279: 		 ($symbparm eq &symbread()) ) {	
                   10280: 		# if we are in the middle of processing the resource the
                   10281: 		# get the value we are planning on committing
                   10282:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10283:                     return $Apache::lonhomework::results{$qualifierrest};
                   10284:                 } else {
                   10285:                     return $Apache::lonhomework::history{$qualifierrest};
                   10286:                 }
1.335     albertel 10287: 	    } else {
1.359     albertel 10288: 		my %restored;
1.620     albertel 10289: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10290: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10291: 		} else {
                   10292: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10293: 		}
1.335     albertel 10294: 		return $restored{$qualifierrest};
                   10295: 	    }
1.48      www      10296: # ----------------------------------------------------------------- user.access
                   10297:         } elsif ($space eq 'access') {
1.218     albertel 10298: 	    # FIXME - not supporting calls for a specific user
1.48      www      10299:             return &allowed($qualifier,$rest);
                   10300: # ------------------------------------------ user.preferences, user.environment
                   10301:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10302: 	    if (($uname eq $env{'user.name'}) &&
                   10303: 		($udom eq $env{'user.domain'})) {
                   10304: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10305: 	    } else {
1.359     albertel 10306: 		my %returnhash;
                   10307: 		if (!$publicuser) {
                   10308: 		    %returnhash=&userenvironment($udom,$uname,
                   10309: 						 $qualifierrest);
                   10310: 		}
1.218     albertel 10311: 		return $returnhash{$qualifierrest};
                   10312: 	    }
1.48      www      10313: # ----------------------------------------------------------------- user.course
                   10314:         } elsif ($space eq 'course') {
1.218     albertel 10315: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10316:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10317: # ------------------------------------------------------------------- user.role
                   10318:         } elsif ($space eq 'role') {
1.218     albertel 10319: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10320:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10321:             if ($qualifier eq 'value') {
                   10322: 		return $role;
                   10323:             } elsif ($qualifier eq 'extent') {
                   10324:                 return $where;
                   10325:             }
                   10326: # ----------------------------------------------------------------- user.domain
                   10327:         } elsif ($space eq 'domain') {
1.218     albertel 10328:             return $udom;
1.48      www      10329: # ------------------------------------------------------------------- user.name
                   10330:         } elsif ($space eq 'name') {
1.218     albertel 10331:             return $uname;
1.48      www      10332: # ---------------------------------------------------- Any other user namespace
1.29      www      10333:         } else {
1.359     albertel 10334: 	    my %reply;
                   10335: 	    if (!$publicuser) {
                   10336: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10337: 	    }
                   10338: 	    return $reply{$qualifierrest};
1.48      www      10339:         }
1.236     www      10340:     } elsif ($realm eq 'query') {
                   10341: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10342:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10343: 						[$spacequalifierrest]);
1.620     albertel 10344: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10345:    } elsif ($realm eq 'request') {
1.48      www      10346: # ------------------------------------------------------------- request.browser
                   10347:         if ($space eq 'browser') {
1.1145    bisitz   10348:             return $env{'browser.'.$qualifier};
1.57      www      10349: # ------------------------------------------------------------ request.filename
                   10350:         } else {
1.620     albertel 10351:             return $env{'request.'.$spacequalifierrest};
1.29      www      10352:         }
1.28      www      10353:     } elsif ($realm eq 'course') {
1.48      www      10354: # ---------------------------------------------------------- course.description
1.620     albertel 10355:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10356:     } elsif ($realm eq 'resource') {
1.165     www      10357: 
1.620     albertel 10358: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10359: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10360: 	}
1.693     albertel 10361: 
1.1172.2.30  raeburn  10362:         if ($qualifier eq '') {
                   10363: 	    if ($space eq 'title') {
                   10364: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10365: 	        return &gettitle($symbparm);
                   10366: 	    }
1.693     albertel 10367: 	
1.1172.2.30  raeburn  10368: 	    if ($space eq 'map') {
                   10369: 	        my ($map) = &decode_symb($symbparm);
                   10370: 	        return &symbread($map);
                   10371: 	    }
                   10372:             if ($space eq 'maptitle') {
                   10373:                 my ($map) = &decode_symb($symbparm);
                   10374:                 return &gettitle($map);
                   10375:             }
                   10376: 	    if ($space eq 'filename') {
                   10377: 	        if ($symbparm) {
                   10378: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10379: 	        }
                   10380: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10381: 	    }
1.1172.2.30  raeburn  10382: 
                   10383:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10384:                 if ($space eq 'visibleparts') {
                   10385:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10386:                     my $item;
                   10387:                     if (ref($navmap)) {
                   10388:                         my $res = $navmap->getBySymb($symbparm);
                   10389:                         my $parts = $res->parts();
                   10390:                         if (ref($parts) eq 'ARRAY') {
                   10391:                             $item = join(',',@{$parts});
                   10392:                         }
                   10393:                         undef($navmap);
                   10394:                     }
                   10395:                     return $item;
                   10396:                 }
                   10397:             }
                   10398:         }
1.693     albertel 10399: 
                   10400: 	my ($section, $group, @groups);
1.593     albertel 10401: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10402:         if (($courseid eq '') && ($cid)) {
                   10403:             $courseid = $cid;
                   10404:         }
                   10405: 	if (($symbparm && $courseid) && 
                   10406: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10407: 
1.218     albertel 10408: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10409: 
1.60      www      10410: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10411: 	    my $symbp=$symbparm;
1.735     albertel 10412: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10413: 
                   10414: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10415: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10416: 
1.620     albertel 10417: 	    if (($env{'user.name'} eq $uname) &&
                   10418: 		($env{'user.domain'} eq $udom)) {
                   10419: 		$section=$env{'request.course.sec'};
1.733     raeburn  10420:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10421:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10422: 	    } else {
1.539     albertel 10423: 		if (! defined($usection)) {
1.551     albertel 10424: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10425: 		} else {
                   10426: 		    $section = $usection;
                   10427: 		}
1.733     raeburn  10428:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10429: 	    }
                   10430: 
                   10431: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10432: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10433: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10434: 
1.593     albertel 10435: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10436: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10437: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10438: 
1.60      www      10439: # ----------------------------------------------------------- first, check user
1.624     albertel 10440: 
                   10441: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10442: 				       ([$courselevelr,'resource'],
                   10443: 					[$courselevelm,'map'     ],
                   10444: 					[$courselevel, 'course'  ]));
1.931     albertel 10445: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10446: 
1.594     albertel 10447: # ------------------------------------------------ second, check some of course
1.684     raeburn  10448:             my $coursereply;
1.691     raeburn  10449:             if (@groups > 0) {
                   10450:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10451:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10452:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10453:             }
1.96      www      10454: 
1.684     raeburn  10455: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10456: 				  $env{'course.'.$courseid.'.domain'},
                   10457: 				  'course',
                   10458: 				  ([$seclevelr,   'resource'],
                   10459: 				   [$seclevelm,   'map'     ],
                   10460: 				   [$seclevel,    'course'  ],
                   10461: 				   [$courselevelr,'resource']));
                   10462: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10463: 
1.60      www      10464: # ------------------------------------------------------ third, check map parms
1.218     albertel 10465: 	    my %parmhash=();
                   10466: 	    my $thisparm='';
                   10467: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10468: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10469: 		    &GDBM_READER(),0640)) {
1.218     albertel 10470: 		$thisparm=$parmhash{$symbparm};
                   10471: 		untie(%parmhash);
                   10472: 	    }
1.927     albertel 10473: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10474: 	}
1.594     albertel 10475: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10476: 
1.218     albertel 10477: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10478: 	my $filename;
                   10479: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10480: 	if ($symbparm) {
1.409     www      10481: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10482: 	} else {
1.620     albertel 10483: 	    $filename=$env{'request.filename'};
1.282     albertel 10484: 	}
                   10485: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10486: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10487: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10488: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10489: 
1.927     albertel 10490: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10491: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10492: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10493: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10494: 				     $env{'course.'.$courseid.'.domain'},
                   10495: 				     'course',
1.927     albertel 10496: 				     ([$courselevelm,'map'   ],
                   10497: 				      [$courselevel, 'course']));
                   10498: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10499: 	}
1.145     www      10500: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10501: 	unless ($space eq '0') {
1.336     albertel 10502: 	    my @parts=split(/_/,$space);
                   10503: 	    my $id=pop(@parts);
                   10504: 	    my $part=join('_',@parts);
                   10505: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10506: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10507: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10508: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10509: 	}
1.395     albertel 10510: 	if ($recurse) { return undef; }
                   10511: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10512: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10513: # ---------------------------------------------------- Any other user namespace
                   10514:     } elsif ($realm eq 'environment') {
                   10515: # ----------------------------------------------------------------- environment
1.620     albertel 10516: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10517: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10518: 	} else {
1.770     albertel 10519: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10520: 		return '';
                   10521: 	    }
1.219     albertel 10522: 	    my %returnhash=&userenvironment($udom,$uname,
                   10523: 					    $spacequalifierrest);
                   10524: 	    return $returnhash{$spacequalifierrest};
                   10525: 	}
1.28      www      10526:     } elsif ($realm eq 'system') {
1.48      www      10527: # ----------------------------------------------------------------- system.time
                   10528: 	if ($space eq 'time') {
                   10529: 	    return time;
                   10530:         }
1.696     albertel 10531:     } elsif ($realm eq 'server') {
                   10532: # ----------------------------------------------------------------- system.time
                   10533: 	if ($space eq 'name') {
                   10534: 	    return $ENV{'SERVER_NAME'};
                   10535:         }
1.28      www      10536:     }
1.48      www      10537:     return '';
1.61      www      10538: }
                   10539: 
1.927     albertel 10540: sub get_reply {
                   10541:     my ($reply_value) = @_;
1.940     raeburn  10542:     if (ref($reply_value) eq 'ARRAY') {
                   10543:         if (wantarray) {
                   10544: 	    return @$reply_value;
                   10545:         }
                   10546:         return $reply_value->[0];
                   10547:     } else {
                   10548:         return $reply_value;
1.927     albertel 10549:     }
                   10550: }
                   10551: 
1.691     raeburn  10552: sub check_group_parms {
                   10553:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10554:     my @groupitems = ();
                   10555:     my $resultitem;
1.927     albertel 10556:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10557:     foreach my $group (@{$groups}) {
                   10558:         foreach my $level (@levels) {
1.927     albertel 10559:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10560:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10561:         }
                   10562:     }
                   10563:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10564:                             $env{'course.'.$courseid.'.domain'},
                   10565:                                      'course',@groupitems);
                   10566:     return $coursereply;
                   10567: }
                   10568: 
                   10569: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10570:     my ($courseid,@groups) = @_;
                   10571:     @groups = sort(@groups);
1.691     raeburn  10572:     return @groups;
                   10573: }
                   10574: 
1.395     albertel 10575: sub packages_tab_default {
                   10576:     my ($uri,$varname)=@_;
                   10577:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10578: 
                   10579:     my (@extension,@specifics,$do_default);
                   10580:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10581: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10582: 	if ($pack_type eq 'default') {
                   10583: 	    $do_default=1;
                   10584: 	} elsif ($pack_type eq 'extension') {
                   10585: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10586: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10587: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10588: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10589: 	}
                   10590:     }
                   10591:     # first look for a package that matches the requested part id
                   10592:     foreach my $package (@specifics) {
                   10593: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10594: 	next if ($pack_part ne $part);
                   10595: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10596: 	    return $packagetab{"$pack_type&$name&default"};
                   10597: 	}
                   10598:     }
                   10599:     # look for any possible matching non extension_ package
                   10600:     foreach my $package (@specifics) {
                   10601: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10602: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10603: 	    return $packagetab{"$pack_type&$name&default"};
                   10604: 	}
1.585     albertel 10605: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10606: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10607: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10608: 	}
                   10609:     }
1.738     albertel 10610:     # look for any posible extension_ match
                   10611:     foreach my $package (@extension) {
                   10612: 	my ($package,$pack_type)=@{$package};
                   10613: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10614: 	    return $packagetab{"$pack_type&$name&default"};
                   10615: 	}
                   10616: 	if (defined($packagetab{$package."&$name&default"})) {
                   10617: 	    return $packagetab{$package."&$name&default"};
                   10618: 	}
                   10619:     }
                   10620:     # look for a global default setting
                   10621:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10622: 	return $packagetab{"default&$name&default"};
                   10623:     }
1.395     albertel 10624:     return undef;
                   10625: }
                   10626: 
1.334     albertel 10627: sub add_prefix_and_part {
                   10628:     my ($prefix,$part)=@_;
                   10629:     my $keyroot;
                   10630:     if (defined($prefix) && $prefix !~ /^__/) {
                   10631: 	# prefix that has a part already
                   10632: 	$keyroot=$prefix;
                   10633:     } elsif (defined($prefix)) {
                   10634: 	# prefix that is missing a part
                   10635: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10636:     } else {
                   10637: 	# no prefix at all
                   10638: 	if (defined($part)) { $keyroot='_'.$part; }
                   10639:     }
                   10640:     return $keyroot;
                   10641: }
                   10642: 
1.71      www      10643: # ---------------------------------------------------------------- Get metadata
                   10644: 
1.599     albertel 10645: my %metaentry;
1.1070    www      10646: my %importedpartids;
1.71      www      10647: sub metadata {
1.176     www      10648:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10649:     $uri=&declutter($uri);
1.288     albertel 10650:     # if it is a non metadata possible uri return quickly
1.529     albertel 10651:     if (($uri eq '') || 
                   10652: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  10653: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10654:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10655: 	return undef;
                   10656:     }
1.1172.2.49  raeburn  10657:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10658: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10659: 	return undef;
1.288     albertel 10660:     }
1.73      www      10661:     my $filename=$uri;
                   10662:     $uri=~s/\.meta$//;
1.172     www      10663: #
                   10664: # Is the metadata already cached?
1.177     www      10665: # Look at timestamp of caching
1.172     www      10666: # Everything is cached by the main uri, libraries are never directly cached
                   10667: #
1.428     albertel 10668:     if (!defined($liburi)) {
1.599     albertel 10669: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10670: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10671:     }
                   10672:     {
1.1069    www      10673: # Imported parts would go here
1.1070    www      10674:         my %importedids=();
                   10675:         my @origfileimportpartids=();
1.1069    www      10676:         my $importedparts=0;
1.172     www      10677: #
                   10678: # Is this a recursive call for a library?
                   10679: #
1.599     albertel 10680: #	if (! exists($metacache{$uri})) {
                   10681: #	    $metacache{$uri}={};
                   10682: #	}
1.924     albertel 10683: 	my $cachetime = 60*60;
1.171     www      10684:         if ($liburi) {
                   10685: 	    $liburi=&declutter($liburi);
                   10686:             $filename=$liburi;
1.401     bowersj2 10687:         } else {
1.599     albertel 10688: 	    &devalidate_cache_new('meta',$uri);
                   10689: 	    undef(%metaentry);
1.401     bowersj2 10690: 	}
1.140     www      10691:         my %metathesekeys=();
1.73      www      10692:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10693: 	my $metastring;
1.1140    www      10694: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10695: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10696: 	    $metastring = 
1.929     albertel 10697: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10698: 					  ('grade_target' => 'meta'));
                   10699: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10700: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10701:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10702: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10703: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10704: 	    $metastring=&getfile($file);
1.489     albertel 10705: 	}
1.208     albertel 10706:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10707:         my $token;
1.140     www      10708:         undef %metathesekeys;
1.71      www      10709:         while ($token=$parser->get_token) {
1.339     albertel 10710: 	    if ($token->[0] eq 'S') {
                   10711: 		if (defined($token->[2]->{'package'})) {
1.172     www      10712: #
                   10713: # This is a package - get package info
                   10714: #
1.339     albertel 10715: 		    my $package=$token->[2]->{'package'};
                   10716: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10717: 		    if (defined($token->[2]->{'id'})) { 
                   10718: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10719: 		    }
1.599     albertel 10720: 		    if ($metaentry{':packages'}) {
                   10721: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10722: 		    } else {
1.599     albertel 10723: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10724: 		    }
1.736     albertel 10725: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10726: 			my $part=$keyroot;
                   10727: 			$part=~s/^\_//;
1.736     albertel 10728: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10729: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10730: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10731: 			    # ignore package.tab specified default values
                   10732:                             # here &package_tab_default() will fetch those
                   10733: 			    if ($subp eq 'default') { next; }
1.736     albertel 10734: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10735: 			    my $unikey;
                   10736: 			    if ($pack =~ /_0$/) {
                   10737: 				$unikey='parameter_0_'.$name;
                   10738: 				$part=0;
                   10739: 			    } else {
                   10740: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10741: 			    }
1.339     albertel 10742: 			    if ($subp eq 'display') {
                   10743: 				$value.=' [Part: '.$part.']';
                   10744: 			    }
1.599     albertel 10745: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10746: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10747: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10748: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10749: 			    }
1.599     albertel 10750: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10751: 				$metaentry{':'.$unikey}=
                   10752: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10753: 			    }
1.339     albertel 10754: 			}
                   10755: 		    }
                   10756: 		} else {
1.172     www      10757: #
                   10758: # This is not a package - some other kind of start tag
1.339     albertel 10759: #
                   10760: 		    my $entry=$token->[1];
1.1068    www      10761: 		    my $unikey='';
1.175     www      10762: 
1.339     albertel 10763: 		    if ($entry eq 'import') {
1.175     www      10764: #
                   10765: # Importing a library here
1.339     albertel 10766: #
1.1067    www      10767:                         my $location=$parser->get_text('/import');
                   10768:                         my $dir=$filename;
                   10769:                         $dir=~s|[^/]*$||;
                   10770:                         $location=&filelocation($dir,$location);
1.1069    www      10771:                        
1.1068    www      10772:                         my $importmode=$token->[2]->{'importmode'};
                   10773:                         if ($importmode eq 'problem') {
1.1069    www      10774: # Import as problem/response
1.1068    www      10775:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10776:                         } elsif ($importmode eq 'part') {
                   10777: # Import as part(s)
1.1069    www      10778:                            $importedparts=1;
                   10779: # We need to get the original file and the imported file to get the part order correct
                   10780: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10781: # Load and inspect original file
1.1070    www      10782:                            if ($#origfileimportpartids<0) {
                   10783:                               undef(%importedpartids);
                   10784:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10785:                               my $origfile=&getfile($origfilelocation);
                   10786:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10787:                            }
                   10788: 
1.1069    www      10789: # Load and inspect imported file
                   10790:                            my $impfile=&getfile($location);
                   10791:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10792:                            if ($#impfilepartids>=0) {
                   10793: # This problem had parts
1.1070    www      10794:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10795:                            } else {
                   10796: # Importing by turning a single problem into a problem part
                   10797: # It gets the import-tags ID as part-ID
                   10798:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10799:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10800:                            }
1.1068    www      10801:                         } else {
                   10802: # Normal import
                   10803:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10804:                            if (defined($token->[2]->{'id'})) {
                   10805:                               $unikey.='_'.$token->[2]->{'id'};
                   10806:                            }
1.1067    www      10807:                         }
                   10808: 
1.339     albertel 10809: 			if ($depthcount<20) {
1.736     albertel 10810: 			    my $metadata = 
                   10811: 				&metadata($uri,'keys', $location,$unikey,
                   10812: 					  $depthcount+1);
                   10813: 			    foreach my $meta (split(',',$metadata)) {
                   10814: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10815: 				$metathesekeys{$meta}=1;
1.339     albertel 10816: 			    }
1.1068    www      10817: 			
                   10818:                         }
1.1067    www      10819: 		    } else {
                   10820: #
                   10821: # Not importing, some other kind of non-package, non-library start tag
                   10822: # 
                   10823:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10824:                         if (defined($token->[2]->{'id'})) {
                   10825:                             $unikey.='_'.$token->[2]->{'id'};
                   10826:                         }
1.339     albertel 10827: 			if (defined($token->[2]->{'name'})) { 
                   10828: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10829: 			}
                   10830: 			$metathesekeys{$unikey}=1;
1.736     albertel 10831: 			foreach my $param (@{$token->[3]}) {
                   10832: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10833: 				$token->[2]->{$param};
1.339     albertel 10834: 			}
                   10835: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10836: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10837: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10838: 		 # only ws inside the tag, and not in default, so use default
                   10839: 		 # as value
1.599     albertel 10840: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10841: 			} elsif ( $internaltext =~ /\S/ ) {
                   10842: 		  # something interesting inside the tag
                   10843: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10844: 			} else {
1.908     albertel 10845: 		  # no interesting values, don't set a default
1.339     albertel 10846: 			}
1.172     www      10847: # end of not-a-package not-a-library import
1.339     albertel 10848: 		    }
1.172     www      10849: # end of not-a-package start tag
1.339     albertel 10850: 		}
1.172     www      10851: # the next is the end of "start tag"
1.339     albertel 10852: 	    }
                   10853: 	}
1.483     albertel 10854: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10855: 	$extension = lc($extension);
                   10856: 	if ($extension eq 'htm') { $extension='html'; }
                   10857: 
1.737     albertel 10858: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10859: 	    #no specific packages #how's our extension
                   10860: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10861: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10862: 					 \%metathesekeys);
                   10863: 	}
1.883     albertel 10864: 
                   10865: 	if (!exists($metaentry{':packages'})
                   10866: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10867: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10868: 		#no specific packages well let's get default then
                   10869: 		if ($key!~/^default&/) { next; }
1.488     albertel 10870: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10871: 					     \%metathesekeys);
                   10872: 	    }
                   10873: 	}
1.338     www      10874: # are there custom rights to evaluate
1.599     albertel 10875: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10876: 
1.338     www      10877:     #
                   10878:     # Importing a rights file here
1.339     albertel 10879:     #
                   10880: 	    unless ($depthcount) {
1.599     albertel 10881: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10882: 		my $dir=$filename;
                   10883: 		$dir=~s|[^/]*$||;
                   10884: 		$location=&filelocation($dir,$location);
1.736     albertel 10885: 		my $rights_metadata =
                   10886: 		    &metadata($uri,'keys',$location,'_rights',
                   10887: 			      $depthcount+1);
                   10888: 		foreach my $rights (split(',',$rights_metadata)) {
                   10889: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10890: 		    $metathesekeys{$rights}=1;
1.339     albertel 10891: 		}
                   10892: 	    }
                   10893: 	}
1.737     albertel 10894: 	# uniqifiy package listing
                   10895: 	my %seen;
                   10896: 	my @uniq_packages =
                   10897: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10898: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10899: 
1.1070    www      10900:         if ($importedparts) {
                   10901: # We had imported parts and need to rebuild partorder
                   10902:            $metaentry{':partorder'}='';
                   10903:            $metathesekeys{'partorder'}=1;
                   10904:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10905:                if ($origfileimportpartids[$index] eq 'part') {
                   10906: # original part, part of the problem
                   10907:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10908:                } else {
                   10909: # we have imported parts at this position
                   10910:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10911:                }
                   10912:            }
                   10913:            $metaentry{':partorder'}=~s/^\,//;
                   10914:         }
                   10915: 
1.737     albertel 10916: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10917: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  10918: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 10919: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10920: # this is the end of "was not already recently cached
1.71      www      10921:     }
1.599     albertel 10922:     return $metaentry{':'.$what};
1.261     albertel 10923: }
                   10924: 
1.488     albertel 10925: sub metadata_create_package_def {
1.483     albertel 10926:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10927:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10928:     if ($subp eq 'default') { next; }
                   10929:     
1.599     albertel 10930:     if (defined($metaentry{':packages'})) {
                   10931: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10932:     } else {
1.599     albertel 10933: 	$metaentry{':packages'}=$package;
1.483     albertel 10934:     }
                   10935:     my $value=$packagetab{$key};
                   10936:     my $unikey;
                   10937:     $unikey='parameter_0_'.$name;
1.599     albertel 10938:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10939:     $$metathesekeys{$unikey}=1;
1.599     albertel 10940:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10941: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10942:     }
1.599     albertel 10943:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10944: 	$metaentry{':'.$unikey}=
                   10945: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10946:     }
                   10947: }
                   10948: 
1.261     albertel 10949: sub metadata_generate_part0 {
                   10950:     my ($metadata,$metacache,$uri) = @_;
                   10951:     my %allnames;
1.737     albertel 10952:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10953: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10954: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10955: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10956: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10957: 	    $allnames{$name}=$part;
                   10958: 	  }
                   10959: 	}
                   10960:     }
                   10961:     foreach my $name (keys(%allnames)) {
                   10962:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10963:       my $key=":parameter_0_$name";
1.261     albertel 10964:       $$metacache{"$key.part"}='0';
                   10965:       $$metacache{"$key.name"}=$name;
1.428     albertel 10966:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10967: 					   $allnames{$name}.'_'.$name.
                   10968: 					   '.type'};
1.428     albertel 10969:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10970: 			     '.display'};
1.644     www      10971:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10972:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10973:       $$metacache{"$key.display"}=$olddis;
                   10974:     }
1.71      www      10975: }
                   10976: 
1.764     albertel 10977: # ------------------------------------------------------ Devalidate title cache
                   10978: 
                   10979: sub devalidate_title_cache {
                   10980:     my ($url)=@_;
                   10981:     if (!$env{'request.course.id'}) { return; }
                   10982:     my $symb=&symbread($url);
                   10983:     if (!$symb) { return; }
                   10984:     my $key=$env{'request.course.id'}."\0".$symb;
                   10985:     &devalidate_cache_new('title',$key);
                   10986: }
                   10987: 
1.1014    droeschl 10988: # ------------------------------------------------- Get the title of a course
                   10989: 
                   10990: sub current_course_title {
                   10991:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   10992: }
1.301     www      10993: # ------------------------------------------------- Get the title of a resource
                   10994: 
                   10995: sub gettitle {
                   10996:     my $urlsymb=shift;
                   10997:     my $symb=&symbread($urlsymb);
1.534     albertel 10998:     if ($symb) {
1.620     albertel 10999: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11000: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11001: 	if (defined($cached)) { 
                   11002: 	    return $result;
                   11003: 	}
1.534     albertel 11004: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11005: 	my $title='';
1.907     albertel 11006: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11007: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11008: 	} else {
                   11009: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11010: 		    &GDBM_READER(),0640)) {
                   11011: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11012: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11013: 		untie(%bighash);
                   11014: 	    }
1.534     albertel 11015: 	}
                   11016: 	$title=~s/\&colon\;/\:/gs;
                   11017: 	if ($title) {
1.1159    www      11018: # Remember both $symb and $title for dynamic metadata
                   11019:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11020:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11021: # Cache this title and then return it
1.599     albertel 11022: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11023: 	}
                   11024: 	$urlsymb=$url;
                   11025:     }
                   11026:     my $title=&metadata($urlsymb,'title');
                   11027:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11028:     return $title;
1.301     www      11029: }
1.613     albertel 11030: 
1.614     albertel 11031: sub get_slot {
                   11032:     my ($which,$cnum,$cdom)=@_;
                   11033:     if (!$cnum || !$cdom) {
1.790     albertel 11034: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11035: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11036: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11037:     }
1.703     albertel 11038:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11039:     my %slotinfo;
                   11040:     if (exists($remembered{$key})) {
                   11041: 	$slotinfo{$which} = $remembered{$key};
                   11042:     } else {
                   11043: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11044: 	&Apache::lonhomework::showhash(%slotinfo);
                   11045: 	my ($tmp)=keys(%slotinfo);
                   11046: 	if ($tmp=~/^error:/) { return (); }
                   11047: 	$remembered{$key} = $slotinfo{$which};
                   11048:     }
1.616     albertel 11049:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11050: 	return %{$slotinfo{$which}};
                   11051:     }
                   11052:     return $slotinfo{$which};
1.614     albertel 11053: }
1.1150    raeburn  11054: 
                   11055: sub get_reservable_slots {
                   11056:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11057:     my $now = time;
                   11058:     my $reservable_info;
                   11059:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11060:     if (exists($remembered{$key})) {
                   11061:         $reservable_info = $remembered{$key};
                   11062:     } else {
                   11063:         my %resv;
                   11064:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11065:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11066:         $reservable_info = \%resv;
                   11067:         $remembered{$key} = $reservable_info;
                   11068:     }
                   11069:     return $reservable_info;
                   11070: }
                   11071: 
                   11072: sub get_course_slots {
                   11073:     my ($cnum,$cdom) = @_;
                   11074:     my $hashid=$cnum.':'.$cdom;
                   11075:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11076:     if (defined($cached)) {
                   11077:         if (ref($result) eq 'HASH') {
                   11078:             return %{$result};
                   11079:         }
                   11080:     } else {
                   11081:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11082:         my ($tmp) = keys(%slots);
                   11083:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  11084:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11085:             return %slots;
                   11086:         }
                   11087:     }
                   11088:     return;
                   11089: }
                   11090: 
                   11091: sub devalidate_slots_cache {
                   11092:     my ($cnum,$cdom)=@_;
                   11093:     my $hashid=$cnum.':'.$cdom;
                   11094:     &devalidate_cache_new('allslots',$hashid);
                   11095: }
                   11096: 
1.1172.2.8  raeburn  11097: sub get_coursechange {
                   11098:     my ($cdom,$cnum) = @_;
                   11099:     if ($cdom eq '' || $cnum eq '') {
                   11100:         return unless ($env{'request.course.id'});
                   11101:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11102:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11103:     }
                   11104:     my $hashid=$cdom.'_'.$cnum;
                   11105:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11106:     if ((defined($cached)) && ($change ne '')) {
                   11107:         return $change;
                   11108:     } else {
                   11109:         my %crshash;
                   11110:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11111:         if ($crshash{'internal.contentchange'} eq '') {
                   11112:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11113:             if ($change eq '') {
                   11114:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11115:                 $change = $crshash{'internal.created'};
                   11116:             }
                   11117:         } else {
                   11118:             $change = $crshash{'internal.contentchange'};
                   11119:         }
                   11120:         my $cachetime = 600;
                   11121:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11122:     }
                   11123:     return $change;
                   11124: }
                   11125: 
                   11126: sub devalidate_coursechange_cache {
                   11127:     my ($cnum,$cdom)=@_;
                   11128:     my $hashid=$cnum.':'.$cdom;
                   11129:     &devalidate_cache_new('crschange',$hashid);
                   11130: }
                   11131: 
1.31      www      11132: # ------------------------------------------------- Update symbolic store links
                   11133: 
                   11134: sub symblist {
                   11135:     my ($mapname,%newhash)=@_;
1.438     www      11136:     $mapname=&deversion(&declutter($mapname));
1.31      www      11137:     my %hash;
1.620     albertel 11138:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11139:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11140:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11141: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11142: 		next if ($url eq 'last_known'
                   11143: 			 && $env{'form.no_update_last_known'});
                   11144: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11145: 						    $newhash{$url}->[1],
                   11146: 						    $newhash{$url}->[0]);
1.191     harris41 11147:             }
1.31      www      11148:             if (untie(%hash)) {
                   11149: 		return 'ok';
                   11150:             }
                   11151:         }
                   11152:     }
                   11153:     return 'error';
1.212     www      11154: }
                   11155: 
                   11156: # --------------------------------------------------------------- Verify a symb
                   11157: 
                   11158: sub symbverify {
1.1172.2.11  raeburn  11159:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11160:     my $thisfn=$thisurl;
1.439     www      11161:     $thisfn=&declutter($thisfn);
1.215     www      11162: # direct jump to resource in page or to a sequence - will construct own symbs
                   11163:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11164: # check URL part
1.409     www      11165:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11166: 
1.431     www      11167:     unless ($url eq $thisfn) { return 0; }
1.213     www      11168: 
1.216     www      11169:     $symb=&symbclean($symb);
1.510     www      11170:     $thisurl=&deversion($thisurl);
1.439     www      11171:     $thisfn=&deversion($thisfn);
1.213     www      11172: 
                   11173:     my %bighash;
                   11174:     my $okay=0;
1.431     www      11175: 
1.620     albertel 11176:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11177:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  11178:         my $noclutter;
1.1032    raeburn  11179:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11180:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  11181:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11182:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11183:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11184:                 $noclutter = 1;
                   11185:             }
                   11186:         }
                   11187:         my $ids;
                   11188:         if ($noclutter) {
                   11189:             $ids=$bighash{'ids_'.$thisurl};
                   11190:         } else {
                   11191:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11192:         }
1.1102    raeburn  11193:         unless ($ids) {
1.1172.2.13  raeburn  11194:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  11195:             $ids=$bighash{$idkey};
1.216     www      11196:         }
                   11197:         if ($ids) {
                   11198: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  11199:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   11200:                 $symb =~ s/\?.+$//;
                   11201:             }
1.800     albertel 11202: 	    foreach my $id (split(/\,/,$ids)) {
                   11203: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11204:                if (
                   11205:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  11206:    eq $symb) {
1.1172.2.11  raeburn  11207:                    if (ref($encstate)) {
                   11208:                        $$encstate = $bighash{'encrypted_'.$id};
                   11209:                    }
1.1172.2.13  raeburn  11210:                    if (($env{'request.role.adv'}) ||
                   11211:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  11212:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  11213:                        $okay=1;
                   11214:                        last;
                   11215:                    }
                   11216:                }
                   11217:            }
1.216     www      11218:         }
1.213     www      11219: 	untie(%bighash);
                   11220:     }
                   11221:     return $okay;
1.31      www      11222: }
                   11223: 
1.210     www      11224: # --------------------------------------------------------------- Clean-up symb
                   11225: 
                   11226: sub symbclean {
                   11227:     my $symb=shift;
1.568     albertel 11228:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11229: # remove version from map
                   11230:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11231: 
1.210     www      11232: # remove version from URL
                   11233:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11234: 
1.507     www      11235: # remove wrapper
                   11236: 
1.510     www      11237:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11238:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11239:     return $symb;
1.409     www      11240: }
                   11241: 
                   11242: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11243: 
                   11244: sub encode_symb {
                   11245:     my ($map,$resid,$url)=@_;
                   11246:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11247: }
1.409     www      11248: 
                   11249: sub decode_symb {
1.568     albertel 11250:     my $symb=shift;
                   11251:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11252:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11253:     return (&fixversion($map),$resid,&fixversion($url));
                   11254: }
                   11255: 
                   11256: sub fixversion {
                   11257:     my $fn=shift;
1.609     banghart 11258:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11259:     my %bighash;
                   11260:     my $uri=&clutter($fn);
1.620     albertel 11261:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11262: # is this cached?
1.599     albertel 11263:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11264:     if (defined($cached)) { return $result; }
                   11265: # unfortunately not cached, or expired
1.620     albertel 11266:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11267: 	    &GDBM_READER(),0640)) {
                   11268:  	if ($bighash{'version_'.$uri}) {
                   11269:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11270:  	    unless (($version eq 'mostrecent') || 
                   11271: 		    ($version==&getversion($uri))) {
1.440     www      11272:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11273:  	    }
                   11274:  	}
                   11275:  	untie %bighash;
1.413     www      11276:     }
1.599     albertel 11277:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11278: }
                   11279: 
                   11280: sub deversion {
                   11281:     my $url=shift;
                   11282:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11283:     return $url;
1.210     www      11284: }
                   11285: 
1.31      www      11286: # ------------------------------------------------------ Return symb list entry
                   11287: 
                   11288: sub symbread {
1.1172.2.66  raeburn  11289:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  11290:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  11291:     if (defined($env{$cache_str})) {
                   11292:         if ($ignorecachednull) {
                   11293:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11294:         } else {
                   11295:             return $env{$cache_str};
                   11296:         }
                   11297:     }
1.242     www      11298: # no filename provided? try from environment
1.1172.2.54  raeburn  11299:     unless ($thisfn) {
1.620     albertel 11300:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  11301:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   11302:         }
                   11303:         $thisfn=$env{'request.filename'};
1.44      www      11304:     }
1.569     albertel 11305:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11306: # is that filename actually a symb? Verify, clean, and return
                   11307:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11308: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11309: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11310: 	}
1.242     www      11311:     }
1.44      www      11312:     $thisfn=declutter($thisfn);
1.31      www      11313:     my %hash;
1.37      www      11314:     my %bighash;
                   11315:     my $syval='';
1.620     albertel 11316:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11317:         my $targetfn = $thisfn;
1.609     banghart 11318:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11319:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11320:         }
1.687     albertel 11321: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11322: 	    $targetfn=$1;
                   11323: 	}
1.620     albertel 11324:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11325:                       &GDBM_READER(),0640)) {
1.481     raeburn  11326: 	    $syval=$hash{$targetfn};
1.37      www      11327:             untie(%hash);
                   11328:         }
                   11329: # ---------------------------------------------------------- There was an entry
                   11330:         if ($syval) {
1.601     albertel 11331: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11332: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11333: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11334: 		    #return $env{$cache_str}='';
1.601     albertel 11335: 		#}    
                   11336: 		#$syval.=$1;
                   11337: 	    #}
1.37      www      11338:         } else {
                   11339: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11340:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11341:                             &GDBM_READER(),0640)) {
1.37      www      11342: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11343:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11344:               unless ($ids) { 
                   11345:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11346:               }
                   11347:               unless ($ids) {
                   11348: # alias?
                   11349: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11350:               }
1.37      www      11351:               if ($ids) {
                   11352: # ------------------------------------------------------------------- Has ID(s)
                   11353:                  my @possibilities=split(/\,/,$ids);
1.39      www      11354:                  if ($#possibilities==0) {
                   11355: # ----------------------------------------------- There is only one possibility
1.37      www      11356: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11357: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11358: 						    $resid,$thisfn);
1.1172.2.66  raeburn  11359:                      if (ref($possibles) eq 'HASH') {
                   11360:                          $possibles->{$syval} = 1;
                   11361:                      }
                   11362:                      if ($checkforblock) {
                   11363:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11364:                          if (@blockers) {
                   11365:                              $syval = '';
                   11366:                              return;
                   11367:                          }
                   11368:                      }
                   11369:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      11370: # ------------------------------------------ There is more than one possibility
                   11371:                      my $realpossible=0;
1.800     albertel 11372:                      foreach my $id (@possibilities) {
                   11373: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  11374:                          my $canaccess;
                   11375:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11376:                              $canaccess = 1;
                   11377:                          } else {
                   11378:                              $canaccess = &allowed('bre',$file);
                   11379:                          }
                   11380:                          if ($canaccess) {
                   11381:          		     my ($mapid,$resid)=split(/\./,$id);
                   11382:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11383:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11384:                                                              $resid,$thisfn);
                   11385:                                  if (ref($possibles) eq 'HASH') {
                   11386:                                      $possibles->{$syval} = 1;
                   11387:                                  }
                   11388:                                  if ($checkforblock) {
                   11389:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11390:                                      unless (@blockers > 0) {
                   11391:                                          $syval = $poss_syval;
                   11392:                                          $realpossible++;
                   11393:                                      }
                   11394:                                  } else {
                   11395:                                      $syval = $poss_syval;
                   11396:                                      $realpossible++;
                   11397:                                  }
                   11398:                              }
1.39      www      11399: 			 }
1.191     harris41 11400:                      }
1.39      www      11401: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11402:                  } else {
                   11403:                      $syval='';
1.37      www      11404:                  }
                   11405: 	      }
1.1172.2.66  raeburn  11406:               untie(%bighash);
1.481     raeburn  11407:            }
1.31      www      11408:         }
1.62      www      11409:         if ($syval) {
1.620     albertel 11410: 	    return $env{$cache_str}=$syval;
1.62      www      11411:         }
1.31      www      11412:     }
1.949     raeburn  11413:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11414:     return $env{$cache_str}='';
1.31      www      11415: }
                   11416: 
                   11417: # ---------------------------------------------------------- Return random seed
                   11418: 
1.32      www      11419: sub numval {
                   11420:     my $txt=shift;
                   11421:     $txt=~tr/A-J/0-9/;
                   11422:     $txt=~tr/a-j/0-9/;
                   11423:     $txt=~tr/K-T/0-9/;
                   11424:     $txt=~tr/k-t/0-9/;
                   11425:     $txt=~tr/U-Z/0-5/;
                   11426:     $txt=~tr/u-z/0-5/;
                   11427:     $txt=~s/\D//g;
1.564     albertel 11428:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11429:     return int($txt);
1.368     albertel 11430: }
                   11431: 
1.484     albertel 11432: sub numval2 {
                   11433:     my $txt=shift;
                   11434:     $txt=~tr/A-J/0-9/;
                   11435:     $txt=~tr/a-j/0-9/;
                   11436:     $txt=~tr/K-T/0-9/;
                   11437:     $txt=~tr/k-t/0-9/;
                   11438:     $txt=~tr/U-Z/0-5/;
                   11439:     $txt=~tr/u-z/0-5/;
                   11440:     $txt=~s/\D//g;
                   11441:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11442:     my $total;
                   11443:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11444:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11445:     return int($total);
                   11446: }
                   11447: 
1.575     albertel 11448: sub numval3 {
                   11449:     use integer;
                   11450:     my $txt=shift;
                   11451:     $txt=~tr/A-J/0-9/;
                   11452:     $txt=~tr/a-j/0-9/;
                   11453:     $txt=~tr/K-T/0-9/;
                   11454:     $txt=~tr/k-t/0-9/;
                   11455:     $txt=~tr/U-Z/0-5/;
                   11456:     $txt=~tr/u-z/0-5/;
                   11457:     $txt=~s/\D//g;
                   11458:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11459:     my $total;
                   11460:     foreach my $val (@txts) { $total+=$val; }
                   11461:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11462:     return $total;
                   11463: }
                   11464: 
1.675     albertel 11465: sub digest {
                   11466:     my ($data)=@_;
                   11467:     my $digest=&Digest::MD5::md5($data);
                   11468:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11469:     my ($e,$f);
                   11470:     {
                   11471:         use integer;
                   11472:         $e=($a+$b);
                   11473:         $f=($c+$d);
                   11474:         if ($_64bit) {
                   11475:             $e=(($e<<32)>>32);
                   11476:             $f=(($f<<32)>>32);
                   11477:         }
                   11478:     }
                   11479:     if (wantarray) {
                   11480: 	return ($e,$f);
                   11481:     } else {
                   11482: 	my $g;
                   11483: 	{
                   11484: 	    use integer;
                   11485: 	    $g=($e+$f);
                   11486: 	    if ($_64bit) {
                   11487: 		$g=(($g<<32)>>32);
                   11488: 	    }
                   11489: 	}
                   11490: 	return $g;
                   11491:     }
                   11492: }
                   11493: 
1.368     albertel 11494: sub latest_rnd_algorithm_id {
1.675     albertel 11495:     return '64bit5';
1.366     albertel 11496: }
1.32      www      11497: 
1.503     albertel 11498: sub get_rand_alg {
                   11499:     my ($courseid)=@_;
1.790     albertel 11500:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11501:     if ($courseid) {
1.620     albertel 11502: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11503:     }
                   11504:     return &latest_rnd_algorithm_id();
                   11505: }
                   11506: 
1.562     albertel 11507: sub validCODE {
                   11508:     my ($CODE)=@_;
                   11509:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11510:     return 0;
                   11511: }
                   11512: 
1.491     albertel 11513: sub getCODE {
1.620     albertel 11514:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11515:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11516: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11517: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11518: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11519:     }
                   11520:     return undef;
                   11521: }
1.1133    foxr     11522: #
                   11523: #  Determines the random seed for a specific context:
                   11524: #
                   11525: # parameters:
                   11526: #   symb      - in course context the symb for the seed.
                   11527: #   course_id - The course id of the form domain_coursenum.
                   11528: #   domain    - Domain for the user.
                   11529: #   course    - Course for the user.
                   11530: #   cenv      - environment of the course.
                   11531: #
                   11532: # NOTE:
                   11533: #   All parameters are picked out of the environment if missing
                   11534: #   or not defined.
                   11535: #   If a symb cannot be determined the current time is used instead.
                   11536: #
                   11537: #  For a given well defined symb, courside, domain, username,
                   11538: #  and course environment, the seed is reproducible.
                   11539: #
1.31      www      11540: sub rndseed {
1.1133    foxr     11541:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11542:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11543:     if (!defined($symb)) {
1.366     albertel 11544: 	unless ($symb=$wsymb) { return time; }
                   11545:     }
1.1146    foxr     11546:     if (!defined $courseid) { 
                   11547: 	$courseid=$wcourseid; 
                   11548:     }
                   11549:     if (!defined $domain) { $domain=$wdomain; }
                   11550:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11551: 
                   11552:     my $which;
                   11553:     if (defined($cenv->{'rndseed'})) {
                   11554: 	$which = $cenv->{'rndseed'};
                   11555:     } else {
                   11556: 	$which =&get_rand_alg($courseid);
                   11557:     }
1.491     albertel 11558:     if (defined(&getCODE())) {
1.675     albertel 11559: 	if ($which eq '64bit5') {
                   11560: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11561: 	} elsif ($which eq '64bit4') {
1.575     albertel 11562: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11563: 	} else {
                   11564: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11565: 	}
1.675     albertel 11566:     } elsif ($which eq '64bit5') {
                   11567: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11568:     } elsif ($which eq '64bit4') {
                   11569: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11570:     } elsif ($which eq '64bit3') {
                   11571: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11572:     } elsif ($which eq '64bit2') {
                   11573: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11574:     } elsif ($which eq '64bit') {
                   11575: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11576:     }
                   11577:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11578: }
                   11579: 
                   11580: sub rndseed_32bit {
                   11581:     my ($symb,$courseid,$domain,$username)=@_;
                   11582:     {
                   11583: 	use integer;
                   11584: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11585: 	my $symbseed=numval($symb) << 22;
                   11586: 	my $namechck=unpack("%32C*",$username) << 17;
                   11587: 	my $nameseed=numval($username) << 12;
                   11588: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11589: 	my $courseseed=unpack("%32C*",$courseid);
                   11590: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11591: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11592: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11593: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11594: 	return $num;
                   11595:     }
                   11596: }
                   11597: 
                   11598: sub rndseed_64bit {
                   11599:     my ($symb,$courseid,$domain,$username)=@_;
                   11600:     {
                   11601: 	use integer;
                   11602: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11603: 	my $symbseed=numval($symb) << 10;
                   11604: 	my $namechck=unpack("%32S*",$username);
                   11605: 	
                   11606: 	my $nameseed=numval($username) << 21;
                   11607: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11608: 	my $courseseed=unpack("%32S*",$courseid);
                   11609: 	
                   11610: 	my $num1=$symbchck+$symbseed+$namechck;
                   11611: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11612: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11613: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11614: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11615: 	return "$num1,$num2";
1.155     albertel 11616:     }
1.366     albertel 11617: }
                   11618: 
1.443     albertel 11619: sub rndseed_64bit2 {
                   11620:     my ($symb,$courseid,$domain,$username)=@_;
                   11621:     {
                   11622: 	use integer;
                   11623: 	# strings need to be an even # of cahracters long, it it is odd the
                   11624:         # last characters gets thrown away
                   11625: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11626: 	my $symbseed=numval($symb) << 10;
                   11627: 	my $namechck=unpack("%32S*",$username.' ');
                   11628: 	
                   11629: 	my $nameseed=numval($username) << 21;
1.501     albertel 11630: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11631: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11632: 	
                   11633: 	my $num1=$symbchck+$symbseed+$namechck;
                   11634: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11635: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11636: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11637: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11638: 	return "$num1,$num2";
                   11639:     }
                   11640: }
                   11641: 
                   11642: sub rndseed_64bit3 {
                   11643:     my ($symb,$courseid,$domain,$username)=@_;
                   11644:     {
                   11645: 	use integer;
                   11646: 	# strings need to be an even # of cahracters long, it it is odd the
                   11647:         # last characters gets thrown away
                   11648: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11649: 	my $symbseed=numval2($symb) << 10;
                   11650: 	my $namechck=unpack("%32S*",$username.' ');
                   11651: 	
                   11652: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11653: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11654: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11655: 	
                   11656: 	my $num1=$symbchck+$symbseed+$namechck;
                   11657: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11658: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11659: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11660: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11661: 	
1.503     albertel 11662: 	return "$num1:$num2";
1.443     albertel 11663:     }
                   11664: }
                   11665: 
1.575     albertel 11666: sub rndseed_64bit4 {
                   11667:     my ($symb,$courseid,$domain,$username)=@_;
                   11668:     {
                   11669: 	use integer;
                   11670: 	# strings need to be an even # of cahracters long, it it is odd the
                   11671:         # last characters gets thrown away
                   11672: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11673: 	my $symbseed=numval3($symb) << 10;
                   11674: 	my $namechck=unpack("%32S*",$username.' ');
                   11675: 	
                   11676: 	my $nameseed=numval3($username) << 21;
                   11677: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11678: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11679: 	
                   11680: 	my $num1=$symbchck+$symbseed+$namechck;
                   11681: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11682: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11683: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11684: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11685: 	
1.575     albertel 11686: 	return "$num1:$num2";
                   11687:     }
                   11688: }
                   11689: 
1.675     albertel 11690: sub rndseed_64bit5 {
                   11691:     my ($symb,$courseid,$domain,$username)=@_;
                   11692:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11693:     return "$num1:$num2";
                   11694: }
                   11695: 
1.366     albertel 11696: sub rndseed_CODE_64bit {
                   11697:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11698:     {
1.366     albertel 11699: 	use integer;
1.443     albertel 11700: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11701: 	my $symbseed=numval2($symb);
1.491     albertel 11702: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11703: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11704: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11705: 	my $num1=$symbseed+$CODEchck;
                   11706: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11707: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11708: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11709: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11710: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11711: 	return "$num1:$num2";
1.366     albertel 11712:     }
                   11713: }
                   11714: 
1.575     albertel 11715: sub rndseed_CODE_64bit4 {
                   11716:     my ($symb,$courseid,$domain,$username)=@_;
                   11717:     {
                   11718: 	use integer;
                   11719: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11720: 	my $symbseed=numval3($symb);
                   11721: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11722: 	my $CODEseed=numval3(&getCODE());
                   11723: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11724: 	my $num1=$symbseed+$CODEchck;
                   11725: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11726: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11727: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11728: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11729: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11730: 	return "$num1:$num2";
                   11731:     }
                   11732: }
                   11733: 
1.675     albertel 11734: sub rndseed_CODE_64bit5 {
                   11735:     my ($symb,$courseid,$domain,$username)=@_;
                   11736:     my $code = &getCODE();
                   11737:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11738:     return "$num1:$num2";
                   11739: }
                   11740: 
1.366     albertel 11741: sub setup_random_from_rndseed {
                   11742:     my ($rndseed)=@_;
1.503     albertel 11743:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  11744: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11745:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11746:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11747:         } else {
                   11748:             &Math::Random::random_set_seed($num1,$num2);
                   11749:         }
1.366     albertel 11750:     } else {
                   11751: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11752:     }
1.36      albertel 11753: }
                   11754: 
1.474     albertel 11755: sub latest_receipt_algorithm_id {
1.835     albertel 11756:     return 'receipt3';
1.474     albertel 11757: }
                   11758: 
1.480     www      11759: sub recunique {
                   11760:     my $fucourseid=shift;
                   11761:     my $unique;
1.835     albertel 11762:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11763: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11764: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11765:     } else {
                   11766: 	$unique=$perlvar{'lonReceipt'};
                   11767:     }
                   11768:     return unpack("%32C*",$unique);
                   11769: }
                   11770: 
                   11771: sub recprefix {
                   11772:     my $fucourseid=shift;
                   11773:     my $prefix;
1.835     albertel 11774:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11775: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11776: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11777:     } else {
                   11778: 	$prefix=$perlvar{'lonHostID'};
                   11779:     }
                   11780:     return unpack("%32C*",$prefix);
                   11781: }
                   11782: 
1.76      www      11783: sub ireceipt {
1.474     albertel 11784:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11785: 
                   11786:     my $return =&recprefix($fucourseid).'-';
                   11787: 
                   11788:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11789: 	$env{'request.state'} eq 'construct') {
                   11790: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11791: 	return $return;
                   11792:     }
                   11793: 
1.76      www      11794:     my $cuname=unpack("%32C*",$funame);
                   11795:     my $cudom=unpack("%32C*",$fudom);
                   11796:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11797:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11798:     my $cunique=&recunique($fucourseid);
1.474     albertel 11799:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11800:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11801: 
1.790     albertel 11802: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11803: 			       
                   11804: 	$return.= ($cunique%$cuname+
                   11805: 		   $cunique%$cudom+
                   11806: 		   $cusymb%$cuname+
                   11807: 		   $cusymb%$cudom+
                   11808: 		   $cucourseid%$cuname+
                   11809: 		   $cucourseid%$cudom+
                   11810: 		   $cpart%$cuname+
                   11811: 		   $cpart%$cudom);
                   11812:     } else {
                   11813: 	$return.= ($cunique%$cuname+
                   11814: 		   $cunique%$cudom+
                   11815: 		   $cusymb%$cuname+
                   11816: 		   $cusymb%$cudom+
                   11817: 		   $cucourseid%$cuname+
                   11818: 		   $cucourseid%$cudom);
                   11819:     }
                   11820:     return $return;
1.76      www      11821: }
                   11822: 
                   11823: sub receipt {
1.474     albertel 11824:     my ($part)=@_;
1.790     albertel 11825:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11826:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11827: }
1.260     ng       11828: 
1.790     albertel 11829: sub whichuser {
                   11830:     my ($passedsymb)=@_;
                   11831:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11832:     if (defined($env{'form.grade_symb'})) {
                   11833: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11834: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11835: 	if (!$allowed &&
                   11836: 	    exists($env{'request.course.sec'}) &&
                   11837: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11838: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11839: 			      '/'.$env{'request.course.sec'});
                   11840: 	}
                   11841: 	if ($allowed) {
                   11842: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11843: 	    $courseid=$tmp_courseid;
                   11844: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11845: 	    ($name)=&get_env_multiple('form.grade_username');
                   11846: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11847: 	}
                   11848:     }
                   11849:     if (!$passedsymb) {
                   11850: 	$symb=&symbread();
                   11851:     } else {
                   11852: 	$symb=$passedsymb;
                   11853:     }
                   11854:     $courseid=$env{'request.course.id'};
                   11855:     $domain=$env{'user.domain'};
                   11856:     $name=$env{'user.name'};
                   11857:     if ($name eq 'public' && $domain eq 'public') {
                   11858: 	if (!defined($env{'form.username'})) {
                   11859: 	    $env{'form.username'}.=time.rand(10000000);
                   11860: 	}
                   11861: 	$name.=$env{'form.username'};
                   11862:     }
                   11863:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11864: 
                   11865: }
                   11866: 
1.36      albertel 11867: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11868: # returns either the contents of the file or 
                   11869: # -1 if the file doesn't exist
1.481     raeburn  11870: #
                   11871: # if the target is a file that was uploaded via DOCS, 
                   11872: # a check will be made to see if a current copy exists on the local server,
                   11873: # if it does this will be served, otherwise a copy will be retrieved from
                   11874: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11875: # the local server.   
1.472     albertel 11876: 
1.36      albertel 11877: sub getfile {
1.538     albertel 11878:     my ($file) = @_;
1.609     banghart 11879:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11880:     &repcopy($file);
                   11881:     return &readfile($file);
                   11882: }
                   11883: 
                   11884: sub repcopy_userfile {
                   11885:     my ($file)=@_;
1.1142    raeburn  11886:     my $londocroot = $perlvar{'lonDocRoot'};
                   11887:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11888:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11889:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11890: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11891:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11892:     if (-e "$file") {
1.828     www      11893: # we already have a local copy, check it out
1.538     albertel 11894: 	my @fileinfo = stat($file);
1.828     www      11895: 	my $rtncode;
                   11896: 	my $info;
1.538     albertel 11897: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11898: 	if ($lwpresp ne 'ok') {
1.828     www      11899: # there is no such file anymore, even though we had a local copy
1.482     albertel 11900: 	    if ($rtncode eq '404') {
1.538     albertel 11901: 		unlink($file);
1.482     albertel 11902: 	    }
                   11903: 	    return -1;
                   11904: 	}
                   11905: 	if ($info < $fileinfo[9]) {
1.828     www      11906: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11907: 	    return 'ok';
1.828     www      11908: 	} else {
                   11909: # the file is outdated, get rid of it
                   11910: 	    unlink($file);
1.482     albertel 11911: 	}
1.828     www      11912:     }
                   11913: # one way or the other, at this point, we don't have the file
                   11914: # construct the correct path for the file
                   11915:     my @parts = ($cdom,$cnum); 
                   11916:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11917: 	push @parts, split(/\//,$1);
                   11918:     }
                   11919:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11920:     foreach my $part (@parts) {
                   11921: 	$path .= '/'.$part;
                   11922: 	if (!-e $path) {
                   11923: 	    mkdir($path,0770);
1.482     albertel 11924: 	}
                   11925:     }
1.828     www      11926: # now the path exists for sure
                   11927: # get a user agent
                   11928:     my $ua=new LWP::UserAgent;
                   11929:     my $transferfile=$file.'.in.transfer';
                   11930: # FIXME: this should flock
                   11931:     if (-e $transferfile) { return 'ok'; }
                   11932:     my $request;
                   11933:     $uri=~s/^\///;
1.980     raeburn  11934:     my $homeserver = &homeserver($cnum,$cdom);
                   11935:     my $protocol = $protocol{$homeserver};
                   11936:     $protocol = 'http' if ($protocol ne 'https');
                   11937:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11938:     my $response=$ua->request($request,$transferfile);
                   11939: # did it work?
                   11940:     if ($response->is_error()) {
                   11941: 	unlink($transferfile);
                   11942: 	&logthis("Userfile repcopy failed for $uri");
                   11943: 	return -1;
                   11944:     }
                   11945: # worked, rename the transfer file
                   11946:     rename($transferfile,$file);
1.607     raeburn  11947:     return 'ok';
1.481     raeburn  11948: }
                   11949: 
1.517     albertel 11950: sub tokenwrapper {
                   11951:     my $uri=shift;
1.980     raeburn  11952:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11953:     $uri=~s|^/||;
1.620     albertel 11954:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11955:     my $token=$1;
1.552     albertel 11956:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11957:     if ($udom && $uname && $file) {
                   11958: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11959:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11960:         my $homeserver = &homeserver($uname,$udom);
                   11961:         my $protocol = $protocol{$homeserver};
                   11962:         $protocol = 'http' if ($protocol ne 'https');
                   11963:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11964:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11965:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11966:     } else {
                   11967:         return '/adm/notfound.html';
                   11968:     }
                   11969: }
                   11970: 
1.828     www      11971: # call with reqtype HEAD: get last modification time
                   11972: # call with reqtype GET: get the file contents
                   11973: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11974: #
1.481     raeburn  11975: sub getuploaded {
                   11976:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11977:     $uri=~s/^\///;
1.980     raeburn  11978:     my $homeserver = &homeserver($cnum,$cdom);
                   11979:     my $protocol = $protocol{$homeserver};
                   11980:     $protocol = 'http' if ($protocol ne 'https');
                   11981:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  11982:     my $ua=new LWP::UserAgent;
                   11983:     my $request=new HTTP::Request($reqtype,$uri);
                   11984:     my $response=$ua->request($request);
                   11985:     $$rtncode = $response->code;
1.482     albertel 11986:     if (! $response->is_success()) {
                   11987: 	return 'failed';
                   11988:     }      
                   11989:     if ($reqtype eq 'HEAD') {
1.486     www      11990: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 11991:     } elsif ($reqtype eq 'GET') {
                   11992: 	$$info = $response->content;
1.472     albertel 11993:     }
1.482     albertel 11994:     return 'ok';
1.36      albertel 11995: }
                   11996: 
1.481     raeburn  11997: sub readfile {
                   11998:     my $file = shift;
                   11999:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12000:     my $fh;
                   12001:     open($fh,"<$file");
                   12002:     my $a='';
1.800     albertel 12003:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12004:     return $a;
                   12005: }
                   12006: 
1.36      albertel 12007: sub filelocation {
1.590     banghart 12008:     my ($dir,$file) = @_;
                   12009:     my $location;
                   12010:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12011: 
                   12012:     if ($file =~ m-^/adm/-) {
                   12013: 	$file=~s-^/adm/wrapper/-/-;
                   12014: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12015:     }
1.882     albertel 12016: 
1.1139    www      12017:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12018:         $location = $file;
1.609     banghart 12019:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12020:         my ($udom,$uname,$filename)=
1.811     albertel 12021:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12022:         my $home=&homeserver($uname,$udom);
                   12023:         my $is_me=0;
                   12024:         my @ids=&current_machine_ids();
                   12025:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12026:         if ($is_me) {
1.1117    foxr     12027:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12028:         } else {
                   12029:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12030:   	      $udom.'/'.$uname.'/'.$filename;
                   12031:         }
1.882     albertel 12032:     } elsif ($file =~ m-^/adm/-) {
                   12033: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12034:     } else {
                   12035:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12036:         $file=~s:^/(res|priv)/:/:;
                   12037:         my $space=$1;
1.590     banghart 12038:         if ( !( $file =~ m:^/:) ) {
                   12039:             $location = $dir. '/'.$file;
                   12040:         } else {
1.1142    raeburn  12041:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12042:         }
1.59      albertel 12043:     }
1.590     banghart 12044:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12045:     while ($location=~m{/\.\./}) {
                   12046: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12047: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12048: 	} else {
                   12049: 	    $location=~ s{/\.\./}{/}g;
                   12050: 	}
                   12051:     } #remove dir/..
1.590     banghart 12052:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12053:     return $location;
1.46      www      12054: }
1.36      albertel 12055: 
1.46      www      12056: sub hreflocation {
                   12057:     my ($dir,$file)=@_;
1.980     raeburn  12058:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12059: 	$file=filelocation($dir,$file);
1.700     albertel 12060:     } elsif ($file=~m-^/adm/-) {
                   12061: 	$file=~s-^/adm/wrapper/-/-;
                   12062: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12063:     }
                   12064:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12065: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12066:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12067: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12068: 	        {/uploaded/$1/$2/}x;
1.46      www      12069:     }
1.913     albertel 12070:     if ($file=~ m{^/userfiles/}) {
                   12071: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12072:     }
1.462     albertel 12073:     return $file;
1.465     albertel 12074: }
                   12075: 
1.1139    www      12076: 
                   12077: 
                   12078: 
                   12079: 
1.465     albertel 12080: sub current_machine_domains {
1.853     albertel 12081:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12082: }
                   12083: 
                   12084: sub machine_domains {
                   12085:     my ($hostname) = @_;
1.465     albertel 12086:     my @domains;
1.838     albertel 12087:     my %hostname = &all_hostnames();
1.465     albertel 12088:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12089: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12090: 	if ($hostname eq $name) {
1.844     albertel 12091: 	    push(@domains,&host_domain($id));
1.465     albertel 12092: 	}
                   12093:     }
                   12094:     return @domains;
                   12095: }
                   12096: 
                   12097: sub current_machine_ids {
1.853     albertel 12098:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12099: }
                   12100: 
                   12101: sub machine_ids {
                   12102:     my ($hostname) = @_;
                   12103:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12104:     my @ids;
1.888     albertel 12105:     my %name_to_host = &all_names();
1.889     albertel 12106:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12107: 	return @{ $name_to_host{$hostname} };
                   12108:     }
                   12109:     return;
1.31      www      12110: }
                   12111: 
1.824     raeburn  12112: sub additional_machine_domains {
                   12113:     my @domains;
                   12114:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12115:     while( my $line = <$fh>) {
                   12116:         $line =~ s/\s//g;
                   12117:         push(@domains,$line);
                   12118:     }
                   12119:     return @domains;
                   12120: }
                   12121: 
                   12122: sub default_login_domain {
                   12123:     my $domain = $perlvar{'lonDefDomain'};
                   12124:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12125:     foreach my $posdom (&current_machine_domains(),
                   12126:                         &additional_machine_domains()) {
                   12127:         if (lc($posdom) eq lc($testdomain)) {
                   12128:             $domain=$posdom;
                   12129:             last;
                   12130:         }
                   12131:     }
                   12132:     return $domain;
                   12133: }
                   12134: 
1.31      www      12135: # ------------------------------------------------------------- Declutters URLs
                   12136: 
                   12137: sub declutter {
                   12138:     my $thisfn=shift;
1.569     albertel 12139:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  12140:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12141:         $thisfn=~s{^/home/httpd/html}{};
                   12142:     }
1.31      www      12143:     $thisfn=~s/^\///;
1.697     albertel 12144:     $thisfn=~s|^adm/wrapper/||;
                   12145:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12146:     $thisfn=~s/^res\///;
1.1172    bisitz   12147:     $thisfn=~s/^priv\///;
1.1032    raeburn  12148:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12149:         $thisfn=~s/\?.+$//;
                   12150:     }
1.268     www      12151:     return $thisfn;
                   12152: }
                   12153: 
                   12154: # ------------------------------------------------------------- Clutter up URLs
                   12155: 
                   12156: sub clutter {
                   12157:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12158:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12159: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12160:        $thisfn='/res'.$thisfn; 
                   12161:     }
1.1031    raeburn  12162:     if ($thisfn !~m|^/adm|) {
                   12163: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12164: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12165: 	} else {
                   12166: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12167: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12168: 	    if ($embstyle eq 'ssi'
                   12169: 		|| ($embstyle eq 'hdn')
                   12170: 		|| ($embstyle eq 'rat')
                   12171: 		|| ($embstyle eq 'prv')
                   12172: 		|| ($embstyle eq 'ign')) {
                   12173: 		#do nothing with these
                   12174: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12175: 		|| ($embstyle eq 'emb')
                   12176: 		|| ($embstyle eq 'wrp')) {
                   12177: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12178: 	    } elsif ($embstyle eq 'unk'
                   12179: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12180: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12181: 	    } else {
1.718     www      12182: #		&logthis("Got a blank emb style");
1.695     albertel 12183: 	    }
1.694     albertel 12184: 	}
                   12185:     }
1.31      www      12186:     return $thisfn;
1.12      www      12187: }
                   12188: 
1.787     albertel 12189: sub clutter_with_no_wrapper {
                   12190:     my $uri = &clutter(shift);
                   12191:     if ($uri =~ m-^/adm/-) {
                   12192: 	$uri =~ s-^/adm/wrapper/-/-;
                   12193: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12194:     }
                   12195:     return $uri;
                   12196: }
                   12197: 
1.557     albertel 12198: sub freeze_escape {
                   12199:     my ($value)=@_;
                   12200:     if (ref($value)) {
                   12201: 	$value=&nfreeze($value);
                   12202: 	return '__FROZEN__'.&escape($value);
                   12203:     }
                   12204:     return &escape($value);
                   12205: }
                   12206: 
1.11      www      12207: 
1.557     albertel 12208: sub thaw_unescape {
                   12209:     my ($value)=@_;
                   12210:     if ($value =~ /^__FROZEN__/) {
                   12211: 	substr($value,0,10,undef);
                   12212: 	$value=&unescape($value);
                   12213: 	return &thaw($value);
                   12214:     }
                   12215:     return &unescape($value);
                   12216: }
                   12217: 
1.436     albertel 12218: sub correct_line_ends {
                   12219:     my ($result)=@_;
                   12220:     $$result =~s/\r\n/\n/mg;
                   12221:     $$result =~s/\r/\n/mg;
1.415     albertel 12222: }
1.1       albertel 12223: # ================================================================ Main Program
                   12224: 
1.184     www      12225: sub goodbye {
1.204     albertel 12226:    &logthis("Starting Shut down");
1.443     albertel 12227: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12228:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12229: #converted
1.599     albertel 12230: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12231:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12232: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12233: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12234: #1.1 only
1.870     albertel 12235: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12236: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12237: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12238: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12239:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12240:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12241:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12242:    &flushcourselogs();
                   12243:    &logthis("Shutting down");
                   12244: }
                   12245: 
1.852     albertel 12246: sub get_dns {
1.1172.2.17  raeburn  12247:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12248:     if (!$ignore_cache) {
                   12249: 	my ($content,$cached)=
                   12250: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12251: 	if ($cached) {
1.1172.2.17  raeburn  12252: 	    &$func($content,$hashref);
1.869     albertel 12253: 	    return;
                   12254: 	}
                   12255:     }
                   12256: 
                   12257:     my %alldns;
1.852     albertel 12258:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12259:     foreach my $dns (<$config>) {
                   12260: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12261:         my $line = $1;
                   12262:         my ($host,$protocol) = split(/:/,$line);
                   12263:         if ($protocol ne 'https') {
                   12264:             $protocol = 'http';
                   12265:         }
                   12266: 	$alldns{$host} = $protocol;
1.869     albertel 12267:     }
                   12268:     while (%alldns) {
1.1172.2.52  raeburn  12269: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12270: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12271:         $ua->timeout(30);
1.979     raeburn  12272: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12273: 	my $response=$ua->request($request);
1.979     raeburn  12274:         delete($alldns{$dns});
1.852     albertel 12275: 	next if ($response->is_error());
                   12276: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  12277:         unless ($nocache) {
1.1172.2.23  raeburn  12278: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  12279:         }
                   12280: 	&$func(\@content,$hashref);
1.869     albertel 12281: 	return;
1.852     albertel 12282:     }
                   12283:     close($config);
1.871     albertel 12284:     my $which = (split('/',$url))[3];
                   12285:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12286:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12287:     my @content = <$config>;
1.1172.2.17  raeburn  12288:     &$func(\@content,$hashref);
                   12289:     return;
                   12290: }
                   12291: 
                   12292: # ------------------------------------------------------Get DNS checksums file
                   12293: sub parse_dns_checksums_tab {
                   12294:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  12295:     my $lonhost = $perlvar{'lonHostID'};
                   12296:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  12297:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  12298:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12299:     my $webconfdir = '/etc/httpd/conf';
                   12300:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12301:         $webconfdir = '/etc/apache2';
                   12302:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12303:         if ($1 >= 10) {
                   12304:             $webconfdir = '/etc/apache2';
                   12305:         }
                   12306:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12307:         if ($1 >= 10.0) {
                   12308:             $webconfdir = '/etc/apache2';
                   12309:         }
                   12310:     }
1.1172.2.17  raeburn  12311:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12312:     my (%chksum,%revnum);
                   12313:     if (ref($lines) eq 'ARRAY') {
                   12314:         chomp(@{$lines});
1.1172.2.34  raeburn  12315:         my $version = shift(@{$lines});
                   12316:         if ($version eq $release) {
1.1172.2.17  raeburn  12317:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  12318:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  12319:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12320:                     if ($webconfdir eq '/etc/apache2') {
                   12321:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12322:                     }
                   12323:                 }
1.1172.2.34  raeburn  12324:                 $chksum{$file} = $shasum;
                   12325:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  12326:             }
                   12327:             if (ref($hashref) eq 'HASH') {
                   12328:                 %{$hashref} = (
                   12329:                                 sums     => \%chksum,
                   12330:                                 versions => \%revnum,
                   12331:                               );
                   12332:             }
                   12333:         }
                   12334:     }
1.869     albertel 12335:     return;
1.852     albertel 12336: }
1.1172.2.17  raeburn  12337: 
                   12338: sub fetch_dns_checksums {
                   12339:     my %checksums;
1.1172.2.34  raeburn  12340:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  12341:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  12342:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12343:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  12344:              \%checksums);
                   12345:     return \%checksums;
                   12346: }
                   12347: 
1.327     albertel 12348: # ------------------------------------------------------------ Read domain file
                   12349: {
1.852     albertel 12350:     my $loaded;
1.846     albertel 12351:     my %domain;
                   12352: 
1.852     albertel 12353:     sub parse_domain_tab {
                   12354: 	my ($lines) = @_;
                   12355: 	foreach my $line (@$lines) {
                   12356: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12357: 
1.846     albertel 12358: 	    chomp($line);
1.852     albertel 12359: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12360: 	    my %this_domain;
                   12361: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12362: 			       'lang_def', 'city', 'longi', 'lati',
                   12363: 			       'primary') {
                   12364: 		$this_domain{$field} = shift(@elements);
                   12365: 	    }
                   12366: 	    $domain{$name} = \%this_domain;
1.852     albertel 12367: 	}
                   12368:     }
1.864     albertel 12369: 
                   12370:     sub reset_domain_info {
                   12371: 	undef($loaded);
                   12372: 	undef(%domain);
                   12373:     }
                   12374: 
1.852     albertel 12375:     sub load_domain_tab {
1.1172.2.70  raeburn  12376: 	my ($ignore_cache,$nocache) = @_;
                   12377: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12378: 	my $fh;
                   12379: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12380: 	    my @lines = <$fh>;
                   12381: 	    &parse_domain_tab(\@lines);
1.448     albertel 12382: 	}
1.852     albertel 12383: 	close($fh);
                   12384: 	$loaded = 1;
1.327     albertel 12385:     }
1.846     albertel 12386: 
                   12387:     sub domain {
1.852     albertel 12388: 	&load_domain_tab() if (!$loaded);
                   12389: 
1.846     albertel 12390: 	my ($name,$what) = @_;
                   12391: 	return if ( !exists($domain{$name}) );
                   12392: 
                   12393: 	if (!$what) {
                   12394: 	    return $domain{$name}{'description'};
                   12395: 	}
                   12396: 	return $domain{$name}{$what};
                   12397:     }
1.974     raeburn  12398: 
                   12399:     sub domain_info {
                   12400:         &load_domain_tab() if (!$loaded);
                   12401:         return %domain;
                   12402:     }
                   12403: 
1.327     albertel 12404: }
                   12405: 
                   12406: 
1.1       albertel 12407: # ------------------------------------------------------------- Read hosts file
                   12408: {
1.838     albertel 12409:     my %hostname;
1.844     albertel 12410:     my %hostdom;
1.845     albertel 12411:     my %libserv;
1.852     albertel 12412:     my $loaded;
1.888     albertel 12413:     my %name_to_host;
1.1074    raeburn  12414:     my %internetdom;
1.1107    raeburn  12415:     my %LC_dns_serv;
1.852     albertel 12416: 
                   12417:     sub parse_hosts_tab {
                   12418: 	my ($file) = @_;
                   12419: 	foreach my $configline (@$file) {
                   12420: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12421:             chomp($configline);
                   12422: 	    if ($configline =~ /^\^/) {
                   12423:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12424:                     $LC_dns_serv{$1} = 1;
                   12425:                 }
                   12426:                 next;
                   12427:             }
1.1074    raeburn  12428: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12429: 	    $name=~s/\s//g;
                   12430: 	    if ($id && $domain && $role && $name) {
                   12431: 		$hostname{$id}=$name;
1.888     albertel 12432: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12433: 		$hostdom{$id}=$domain;
                   12434: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12435:                 if (defined($protocol)) {
                   12436:                     if ($protocol eq 'https') {
                   12437:                         $protocol{$id} = $protocol;
                   12438:                     } else {
                   12439:                         $protocol{$id} = 'http'; 
                   12440:                     }
1.968     raeburn  12441:                 } else {
1.969     raeburn  12442:                     $protocol{$id} = 'http';
1.968     raeburn  12443:                 }
1.1074    raeburn  12444:                 if (defined($intdom)) {
                   12445:                     $internetdom{$id} = $intdom;
                   12446:                 }
1.852     albertel 12447: 	    }
                   12448: 	}
                   12449:     }
1.864     albertel 12450:     
                   12451:     sub reset_hosts_info {
1.897     albertel 12452: 	&purge_remembered();
1.864     albertel 12453: 	&reset_domain_info();
                   12454: 	&reset_hosts_ip_info();
1.892     albertel 12455: 	undef(%name_to_host);
1.864     albertel 12456: 	undef(%hostname);
                   12457: 	undef(%hostdom);
                   12458: 	undef(%libserv);
                   12459: 	undef($loaded);
                   12460:     }
1.1       albertel 12461: 
1.852     albertel 12462:     sub load_hosts_tab {
1.1172.2.70  raeburn  12463: 	my ($ignore_cache,$nocache) = @_;
                   12464: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 12465: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12466: 	my @config = <$config>;
                   12467: 	&parse_hosts_tab(\@config);
                   12468: 	close($config);
                   12469: 	$loaded=1;
1.1       albertel 12470:     }
1.852     albertel 12471: 
1.838     albertel 12472:     sub hostname {
1.852     albertel 12473: 	&load_hosts_tab() if (!$loaded);
                   12474: 
1.838     albertel 12475: 	my ($lonid) = @_;
                   12476: 	return $hostname{$lonid};
                   12477:     }
1.845     albertel 12478: 
1.838     albertel 12479:     sub all_hostnames {
1.852     albertel 12480: 	&load_hosts_tab() if (!$loaded);
                   12481: 
1.838     albertel 12482: 	return %hostname;
                   12483:     }
1.845     albertel 12484: 
1.888     albertel 12485:     sub all_names {
1.1172.2.70  raeburn  12486:         my ($ignore_cache,$nocache) = @_;
                   12487: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12488: 
                   12489: 	return %name_to_host;
                   12490:     }
                   12491: 
1.974     raeburn  12492:     sub all_host_domain {
                   12493:         &load_hosts_tab() if (!$loaded);
                   12494:         return %hostdom;
                   12495:     }
                   12496: 
1.845     albertel 12497:     sub is_library {
1.852     albertel 12498: 	&load_hosts_tab() if (!$loaded);
                   12499: 
1.845     albertel 12500: 	return exists($libserv{$_[0]});
                   12501:     }
                   12502: 
                   12503:     sub all_library {
1.852     albertel 12504: 	&load_hosts_tab() if (!$loaded);
                   12505: 
1.845     albertel 12506: 	return %libserv;
                   12507:     }
                   12508: 
1.1062    droeschl 12509:     sub unique_library {
                   12510: 	#2x reverse removes all hostnames that appear more than once
                   12511:         my %unique = reverse &all_library();
                   12512:         return reverse %unique;
                   12513:     }
                   12514: 
1.841     albertel 12515:     sub get_servers {
1.852     albertel 12516: 	&load_hosts_tab() if (!$loaded);
                   12517: 
1.841     albertel 12518: 	my ($domain,$type) = @_;
                   12519: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12520: 	                                          : %hostname;
                   12521: 	my %result;
1.842     albertel 12522: 	if (ref($domain) eq 'ARRAY') {
                   12523: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12524: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12525: 		    $result{$host} = $hostname;
                   12526: 		}
                   12527: 	    }
                   12528: 	} else {
                   12529: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12530: 		if ($hostdom{$host} eq $domain) {
                   12531: 		    $result{$host} = $hostname;
                   12532: 		}
1.841     albertel 12533: 	    }
                   12534: 	}
                   12535: 	return %result;
                   12536:     }
1.845     albertel 12537: 
1.1062    droeschl 12538:     sub get_unique_servers {
                   12539:         my %unique = reverse &get_servers(@_);
                   12540: 	return reverse %unique;
                   12541:     }
                   12542: 
1.844     albertel 12543:     sub host_domain {
1.852     albertel 12544: 	&load_hosts_tab() if (!$loaded);
                   12545: 
1.844     albertel 12546: 	my ($lonid) = @_;
                   12547: 	return $hostdom{$lonid};
                   12548:     }
                   12549: 
1.841     albertel 12550:     sub all_domains {
1.852     albertel 12551: 	&load_hosts_tab() if (!$loaded);
                   12552: 
1.841     albertel 12553: 	my %seen;
                   12554: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12555: 	return @uniq;
                   12556:     }
1.1074    raeburn  12557: 
                   12558:     sub internet_dom {
                   12559:         &load_hosts_tab() if (!$loaded);
                   12560: 
                   12561:         my ($lonid) = @_;
                   12562:         return $internetdom{$lonid};
                   12563:     }
1.1107    raeburn  12564: 
                   12565:     sub is_LC_dns {
                   12566:         &load_hosts_tab() if (!$loaded);
                   12567: 
                   12568:         my ($hostname) = @_;
                   12569:         return exists($LC_dns_serv{$hostname});
                   12570:     }
                   12571: 
1.1       albertel 12572: }
                   12573: 
1.847     albertel 12574: { 
                   12575:     my %iphost;
1.856     albertel 12576:     my %name_to_ip;
                   12577:     my %lonid_to_ip;
1.869     albertel 12578: 
1.847     albertel 12579:     sub get_hosts_from_ip {
                   12580: 	my ($ip) = @_;
                   12581: 	my %iphosts = &get_iphost();
                   12582: 	if (ref($iphosts{$ip})) {
                   12583: 	    return @{$iphosts{$ip}};
                   12584: 	}
                   12585: 	return;
1.839     albertel 12586:     }
1.864     albertel 12587:     
                   12588:     sub reset_hosts_ip_info {
                   12589: 	undef(%iphost);
                   12590: 	undef(%name_to_ip);
                   12591: 	undef(%lonid_to_ip);
                   12592:     }
1.856     albertel 12593: 
                   12594:     sub get_host_ip {
                   12595: 	my ($lonid) = @_;
                   12596: 	if (exists($lonid_to_ip{$lonid})) {
                   12597: 	    return $lonid_to_ip{$lonid};
                   12598: 	}
                   12599: 	my $name=&hostname($lonid);
                   12600:    	my $ip = gethostbyname($name);
                   12601: 	return if (!$ip || length($ip) ne 4);
                   12602: 	$ip=inet_ntoa($ip);
                   12603: 	$name_to_ip{$name}   = $ip;
                   12604: 	$lonid_to_ip{$lonid} = $ip;
                   12605: 	return $ip;
                   12606:     }
1.847     albertel 12607:     
                   12608:     sub get_iphost {
1.1172.2.70  raeburn  12609: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 12610: 
1.869     albertel 12611: 	if (!$ignore_cache) {
                   12612: 	    if (%iphost) {
                   12613: 		return %iphost;
                   12614: 	    }
                   12615: 	    my ($ip_info,$cached)=
                   12616: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12617: 	    if ($cached) {
                   12618: 		%iphost      = %{$ip_info->[0]};
                   12619: 		%name_to_ip  = %{$ip_info->[1]};
                   12620: 		%lonid_to_ip = %{$ip_info->[2]};
                   12621: 		return %iphost;
                   12622: 	    }
                   12623: 	}
1.894     albertel 12624: 
                   12625: 	# get yesterday's info for fallback
                   12626: 	my %old_name_to_ip;
                   12627: 	my ($ip_info,$cached)=
                   12628: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12629: 	if ($cached) {
                   12630: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12631: 	}
                   12632: 
1.1172.2.70  raeburn  12633: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 12634: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12635: 	    my $ip;
                   12636: 	    if (!exists($name_to_ip{$name})) {
                   12637: 		$ip = gethostbyname($name);
                   12638: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12639: 		    if (defined($old_name_to_ip{$name})) {
                   12640: 			$ip = $old_name_to_ip{$name};
                   12641: 			&logthis("Can't find $name defaulting to old $ip");
                   12642: 		    } else {
                   12643: 			&logthis("Name $name no IP found");
                   12644: 			next;
                   12645: 		    }
                   12646: 		} else {
                   12647: 		    $ip=inet_ntoa($ip);
1.847     albertel 12648: 		}
                   12649: 		$name_to_ip{$name} = $ip;
                   12650: 	    } else {
                   12651: 		$ip = $name_to_ip{$name};
1.653     albertel 12652: 	    }
1.888     albertel 12653: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12654: 		$lonid_to_ip{$id} = $ip;
                   12655: 	    }
                   12656: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12657: 	}
1.1172.2.70  raeburn  12658:         unless ($nocache) {
                   12659: 	    &do_cache_new('iphost','iphost',
                   12660: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12661: 		          48*60*60);
                   12662:         }
1.869     albertel 12663: 
1.847     albertel 12664: 	return %iphost;
1.598     albertel 12665:     }
                   12666: 
1.992     raeburn  12667:     #
                   12668:     #  Given a DNS returns the loncapa host name for that DNS 
                   12669:     # 
                   12670:     sub host_from_dns {
                   12671:         my ($dns) = @_;
                   12672:         my @hosts;
                   12673:         my $ip;
                   12674: 
1.993     raeburn  12675:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12676:             $ip = $name_to_ip{$dns};
                   12677:         }
                   12678:         if (!$ip) {
                   12679:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12680:             if (length($ip) == 4) { 
                   12681: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12682:             }
                   12683:         }
                   12684:         if ($ip) {
                   12685: 	    @hosts = get_hosts_from_ip($ip);
                   12686: 	    return $hosts[0];
                   12687:         }
                   12688:         return undef;
1.986     foxr     12689:     }
1.992     raeburn  12690: 
1.1074    raeburn  12691:     sub get_internet_names {
                   12692:         my ($lonid) = @_;
                   12693:         return if ($lonid eq '');
                   12694:         my ($idnref,$cached)=
                   12695:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12696:         if ($cached) {
                   12697:             return $idnref;
                   12698:         }
                   12699:         my $ip = &get_host_ip($lonid);
                   12700:         my @hosts = &get_hosts_from_ip($ip);
                   12701:         my %iphost = &get_iphost();
                   12702:         my (@idns,%seen);
                   12703:         foreach my $id (@hosts) {
                   12704:             my $dom = &host_domain($id);
                   12705:             my $prim_id = &domain($dom,'primary');
                   12706:             my $prim_ip = &get_host_ip($prim_id);
                   12707:             next if ($seen{$prim_ip});
                   12708:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12709:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12710:                     my $intdom = &internet_dom($id);
                   12711:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12712:                         push(@idns,$intdom);
                   12713:                     }
                   12714:                 }
                   12715:             }
                   12716:             $seen{$prim_ip} = 1;
                   12717:         }
1.1172.2.23  raeburn  12718:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12719:     }
                   12720: 
1.986     foxr     12721: }
                   12722: 
1.1079    raeburn  12723: sub all_loncaparevs {
1.1172.2.39  raeburn  12724:     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  12725: }
                   12726: 
1.1172.2.27  raeburn  12727: # ------------------------------------------------------- Read loncaparev table
                   12728: {
                   12729:     sub load_loncaparevs {
                   12730:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12731:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12732:                 while (my $configline=<$config>) {
                   12733:                     chomp($configline);
                   12734:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12735:                     $loncaparevs{$hostid}=$loncaparev;
                   12736:                 }
                   12737:                 close($config);
                   12738:             }
                   12739:         }
                   12740:     }
                   12741: }
                   12742: 
                   12743: # ----------------------------------------------------- Read serverhostID table
                   12744: {
                   12745:     sub load_serverhomeIDs {
                   12746:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12747:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12748:                 while (my $configline=<$config>) {
                   12749:                     chomp($configline);
                   12750:                     my ($name,$id)=split(/:/,$configline);
                   12751:                     $serverhomeIDs{$name}=$id;
                   12752:                 }
                   12753:                 close($config);
                   12754:             }
                   12755:         }
                   12756:     }
                   12757: }
                   12758: 
                   12759: 
1.862     albertel 12760: BEGIN {
                   12761: 
                   12762: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12763:     unless ($readit) {
                   12764: {
                   12765:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12766:     %perlvar = (%perlvar,%{$configvars});
                   12767: }
                   12768: 
                   12769: 
1.1       albertel 12770: # ------------------------------------------------------ Read spare server file
                   12771: {
1.448     albertel 12772:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12773: 
                   12774:     while (my $configline=<$config>) {
                   12775:        chomp($configline);
1.284     matthew  12776:        if ($configline) {
1.784     albertel 12777: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12778: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12779: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12780:        }
                   12781:     }
1.448     albertel 12782:     close($config);
1.1       albertel 12783: }
1.11      www      12784: # ------------------------------------------------------------ Read permissions
                   12785: {
1.448     albertel 12786:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12787: 
                   12788:     while (my $configline=<$config>) {
1.448     albertel 12789: 	chomp($configline);
                   12790: 	if ($configline) {
                   12791: 	    my ($role,$perm)=split(/ /,$configline);
                   12792: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12793: 	}
1.11      www      12794:     }
1.448     albertel 12795:     close($config);
1.11      www      12796: }
                   12797: 
                   12798: # -------------------------------------------- Read plain texts for permissions
                   12799: {
1.448     albertel 12800:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12801: 
                   12802:     while (my $configline=<$config>) {
1.448     albertel 12803: 	chomp($configline);
                   12804: 	if ($configline) {
1.742     raeburn  12805: 	    my ($short,@plain)=split(/:/,$configline);
                   12806:             %{$prp{$short}} = ();
                   12807: 	    if (@plain > 0) {
                   12808:                 $prp{$short}{'std'} = $plain[0];
                   12809:                 for (my $i=1; $i<@plain; $i++) {
                   12810:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12811:                 }
                   12812:             }
1.448     albertel 12813: 	}
1.135     www      12814:     }
1.448     albertel 12815:     close($config);
1.135     www      12816: }
                   12817: 
                   12818: # ---------------------------------------------------------- Read package table
                   12819: {
1.448     albertel 12820:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12821: 
                   12822:     while (my $configline=<$config>) {
1.483     albertel 12823: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12824: 	chomp($configline);
                   12825: 	my ($short,$plain)=split(/:/,$configline);
                   12826: 	my ($pack,$name)=split(/\&/,$short);
                   12827: 	if ($plain ne '') {
                   12828: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12829: 	    $packagetab{$short}=$plain; 
                   12830: 	}
1.11      www      12831:     }
1.448     albertel 12832:     close($config);
1.329     matthew  12833: }
                   12834: 
1.1172.2.27  raeburn  12835: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  12836: 
1.1172.2.27  raeburn  12837: &load_loncaparevs();
                   12838: 
                   12839: # ------------------------------------------------------- Read serverhostID table
                   12840: 
                   12841: &load_serverhomeIDs();
1.1074    raeburn  12842: 
1.1172.2.27  raeburn  12843: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12844: {
                   12845:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12846:     if (-e $file) {
                   12847:         my $parser = HTML::LCParser->new($file);
                   12848:         while (my $token = $parser->get_token()) {
                   12849:             if ($token->[0] eq 'S') {
                   12850:                 my $item = $token->[1];
                   12851:                 my $name = $token->[2]{'name'};
                   12852:                 my $value = $token->[2]{'value'};
                   12853:                 if ($item ne '' && $name ne '' && $value ne '') {
                   12854:                     my $release = $parser->get_text();
                   12855:                     $release =~ s/(^\s*|\s*$ )//gx;
                   12856:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   12857:                 }
                   12858:             }
                   12859:         }
                   12860:     }
1.1073    raeburn  12861: }
                   12862: 
1.1138    raeburn  12863: # ---------------------------------------------------------- Read managers table
                   12864: {
                   12865:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12866:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12867:             while (my $configline=<$config>) {
                   12868:                 chomp($configline);
                   12869:                 next if ($configline =~ /^\#/);
                   12870:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12871:                     $managerstab{$configline} = 1;
                   12872:                 }
                   12873:             }
                   12874:             close($config);
                   12875:         }
                   12876:     }
                   12877: }
                   12878: 
1.329     matthew  12879: # ------------- set up temporary directory
                   12880: {
1.1117    foxr     12881:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12882: 
1.11      www      12883: }
                   12884: 
1.794     albertel 12885: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12886: 				'compress_threshold'=> 20_000,
                   12887:  			        });
1.185     www      12888: 
1.281     www      12889: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12890: $dumpcount=0;
1.958     www      12891: $locknum=0;
1.22      www      12892: 
1.163     harris41 12893: &logtouch();
1.672     albertel 12894: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12895: $readit=1;
1.564     albertel 12896:     {
                   12897: 	use integer;
                   12898: 	my $test=(2**32)+1;
1.568     albertel 12899: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12900: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12901:     }
1.195     www      12902: }
1.1       albertel 12903: }
1.179     www      12904: 
1.1       albertel 12905: 1;
1.191     harris41 12906: __END__
                   12907: 
1.243     albertel 12908: =pod
                   12909: 
1.191     harris41 12910: =head1 NAME
                   12911: 
1.243     albertel 12912: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12913: 
                   12914: =head1 SYNOPSIS
                   12915: 
1.243     albertel 12916: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12917: 
                   12918:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12919: 
1.243     albertel 12920: Common parameters:
                   12921: 
                   12922: =over 4
                   12923: 
                   12924: =item *
                   12925: 
                   12926: $uname : an internal username (if $cname expecting a course Id specifically)
                   12927: 
                   12928: =item *
                   12929: 
                   12930: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12931: 
                   12932: =item *
                   12933: 
                   12934: $symb : a resource instance identifier
                   12935: 
                   12936: =item *
                   12937: 
                   12938: $namespace : the name of a .db file that contains the data needed or
                   12939: being set.
                   12940: 
                   12941: =back
                   12942: 
1.394     bowersj2 12943: =head1 OVERVIEW
1.191     harris41 12944: 
1.394     bowersj2 12945: lonnet provides subroutines which interact with the
                   12946: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12947: about classes, users, and resources.
1.243     albertel 12948: 
                   12949: For many of these objects you can also use this to store data about
                   12950: them or modify them in various ways.
1.191     harris41 12951: 
1.394     bowersj2 12952: =head2 Symbs
1.191     harris41 12953: 
1.394     bowersj2 12954: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12955: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12956: map, the resource number of the resource in the map, and the URL of
                   12957: the resource itself. The latter is somewhat redundant, but might help
                   12958: if maps change.
                   12959: 
                   12960: An example is
                   12961: 
                   12962:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12963: 
                   12964: The respective map entry is
                   12965: 
                   12966:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12967:   title="Problem 2">
                   12968:  </resource>
                   12969: 
                   12970: Symbs are used by the random number generator, as well as to store and
                   12971: restore data specific to a certain instance of for example a problem.
                   12972: 
                   12973: =head2 Storing And Retrieving Data
                   12974: 
                   12975: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12976: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12977: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12978: is is the non-critical message twin of cstore. These functions are for
                   12979: handlers to store a perl hash to a user's permanent data space in an
                   12980: easy manner, and to retrieve it again on another call. It is expected
                   12981: that a handler would use this once at the beginning to retrieve data,
                   12982: and then again once at the end to send only the new data back.
                   12983: 
                   12984: The data is stored in the user's data directory on the user's
                   12985: homeserver under the ID of the course.
                   12986: 
                   12987: The hash that is returned by restore will have all of the previous
                   12988: value for all of the elements of the hash.
                   12989: 
                   12990: Example:
                   12991: 
                   12992:  #creating a hash
                   12993:  my %hash;
                   12994:  $hash{'foo'}='bar';
                   12995: 
                   12996:  #storing it
                   12997:  &Apache::lonnet::cstore(\%hash);
                   12998: 
                   12999:  #changing a value
                   13000:  $hash{'foo'}='notbar';
                   13001: 
                   13002:  #adding a new value
                   13003:  $hash{'bar'}='foo';
                   13004:  &Apache::lonnet::cstore(\%hash);
                   13005: 
                   13006:  #retrieving the hash
                   13007:  my %history=&Apache::lonnet::restore();
                   13008: 
                   13009:  #print the hash
                   13010:  foreach my $key (sort(keys(%history))) {
                   13011:    print("\%history{$key} = $history{$key}");
                   13012:  }
                   13013: 
                   13014: Will print out:
1.191     harris41 13015: 
1.394     bowersj2 13016:  %history{1:foo} = bar
                   13017:  %history{1:keys} = foo:timestamp
                   13018:  %history{1:timestamp} = 990455579
                   13019:  %history{2:bar} = foo
                   13020:  %history{2:foo} = notbar
                   13021:  %history{2:keys} = foo:bar:timestamp
                   13022:  %history{2:timestamp} = 990455580
                   13023:  %history{bar} = foo
                   13024:  %history{foo} = notbar
                   13025:  %history{timestamp} = 990455580
                   13026:  %history{version} = 2
                   13027: 
                   13028: Note that the special hash entries C<keys>, C<version> and
                   13029: C<timestamp> were added to the hash. C<version> will be equal to the
                   13030: total number of versions of the data that have been stored. The
                   13031: C<timestamp> attribute will be the UNIX time the hash was
                   13032: stored. C<keys> is available in every historical section to list which
                   13033: keys were added or changed at a specific historical revision of a
                   13034: hash.
                   13035: 
                   13036: B<Warning>: do not store the hash that restore returns directly. This
                   13037: will cause a mess since it will restore the historical keys as if the
                   13038: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13039: 
1.394     bowersj2 13040: Calling convention:
1.191     harris41 13041: 
1.1172.2.27  raeburn  13042:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  13043:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13044: 
1.394     bowersj2 13045: For more detailed information, see lonnet specific documentation.
1.191     harris41 13046: 
1.394     bowersj2 13047: =head1 RETURN MESSAGES
1.191     harris41 13048: 
1.394     bowersj2 13049: =over 4
1.191     harris41 13050: 
1.394     bowersj2 13051: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13052: 
1.394     bowersj2 13053: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13054: when the connection is brought back up
1.191     harris41 13055: 
1.394     bowersj2 13056: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13057: for later delivery
1.191     harris41 13058: 
1.967     bisitz   13059: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13060: 
1.394     bowersj2 13061: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13062: that was requested
1.191     harris41 13063: 
1.243     albertel 13064: =back
1.191     harris41 13065: 
1.243     albertel 13066: =head1 PUBLIC SUBROUTINES
1.191     harris41 13067: 
1.243     albertel 13068: =head2 Session Environment Functions
1.191     harris41 13069: 
1.243     albertel 13070: =over 4
1.191     harris41 13071: 
1.394     bowersj2 13072: =item * 
                   13073: X<appenv()>
1.949     raeburn  13074: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13075: the user envirnoment file, and will be restored for each access this
1.620     albertel 13076: user makes during this session, also modifies the %env for the current
1.949     raeburn  13077: process. Optional rolesarrayref - if defined contains a reference to an array
                   13078: of roles which are exempt from the restriction on modifying user.role entries 
                   13079: in the user's environment.db and in %env.    
1.191     harris41 13080: 
                   13081: =item *
1.394     bowersj2 13082: X<delenv()>
1.987     raeburn  13083: B<delenv($delthis,$regexp)>: removes all items from the session
                   13084: environment file that begin with $delthis. If the 
                   13085: optional second arg - $regexp - is true, $delthis is treated as a 
                   13086: regular expression, otherwise \Q$delthis\E is used. 
                   13087: The values are also deleted from the current processes %env.
1.191     harris41 13088: 
1.795     albertel 13089: =item * get_env_multiple($name) 
                   13090: 
                   13091: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13092: values may be defined and end up as an array ref.
                   13093: 
                   13094: returns an array of values
                   13095: 
1.243     albertel 13096: =back
                   13097: 
                   13098: =head2 User Information
1.191     harris41 13099: 
1.243     albertel 13100: =over 4
1.191     harris41 13101: 
                   13102: =item *
1.394     bowersj2 13103: X<queryauthenticate()>
                   13104: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13105: authentication scheme
                   13106: 
                   13107: =item *
1.394     bowersj2 13108: X<authenticate()>
1.1073    raeburn  13109: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13110: authenticate user from domain's lib servers (first use the current
                   13111: one). C<$upass> should be the users password.
1.1073    raeburn  13112: $checkdefauth is optional (value is 1 if a check should be made to
                   13113:    authenticate user using default authentication method, and allow
                   13114:    account creation if username does not have account in the domain).
                   13115: $clientcancheckhost is optional (value is 1 if checking whether the
                   13116:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13117: 
                   13118: =item *
1.394     bowersj2 13119: X<homeserver()>
                   13120: B<homeserver($uname,$udom)>: find the server which has
                   13121: the user's directory and files (there must be only one), this caches
                   13122: the answer, and also caches if there is a borken connection.
1.191     harris41 13123: 
                   13124: =item *
1.394     bowersj2 13125: X<idget()>
                   13126: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13127: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13128: username, and only 1 username per ID in a specific domain) (returns
                   13129: hash: id=>name,id=>name)
1.191     harris41 13130: 
                   13131: =item *
1.394     bowersj2 13132: X<idrget()>
                   13133: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13134: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13135: 
                   13136: =item *
1.394     bowersj2 13137: X<idput()>
                   13138: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13139: 
                   13140: =item *
1.394     bowersj2 13141: X<rolesinit()>
1.1169    droeschl 13142: B<rolesinit($udom,$username)>: get user privileges.
                   13143: returns user role, first access and timer interval hashes
1.243     albertel 13144: 
                   13145: =item *
1.1171    droeschl 13146: X<privileged()>
                   13147: B<privileged($username,$domain)>: returns a true if user has a
                   13148: privileged and active role (i.e. su or dc), false otherwise.
                   13149: 
                   13150: =item *
1.551     albertel 13151: X<getsection()>
                   13152: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13153: course $cname, return section name/number or '' for "not in course"
                   13154: and '-1' for "no section"
                   13155: 
                   13156: =item *
1.394     bowersj2 13157: X<userenvironment()>
                   13158: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13159: passed in @what from the requested user's environment, returns a hash
                   13160: 
1.858     raeburn  13161: =item * 
                   13162: X<userlog_query()>
1.859     albertel 13163: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13164: activity.log file. %filters defines filters applied when parsing the
                   13165: log file. These can be start or end timestamps, or the type of action
                   13166: - log to look for Login or Logout events, check for Checkin or
                   13167: Checkout, role for role selection. The response is in the form
                   13168: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13169: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13170: 
1.243     albertel 13171: =back
                   13172: 
                   13173: =head2 User Roles
                   13174: 
                   13175: =over 4
                   13176: 
                   13177: =item *
                   13178: 
1.1172.2.65  raeburn  13179: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13180: returns codes for allowed actions.
                   13181: 
                   13182: The first argument is required, all others are optional.
                   13183: 
                   13184: $priv is the privilege being checked.
                   13185: $uri contains additional information about what is being checked for access (e.g.,
                   13186: URL, course ID etc.).
                   13187: $symb is the unique resource instance identifier in a course; if needed,
                   13188: but not provided, it will be retrieved via a call to &symbread().
                   13189: $role is the role for which a priv is being checked (only used if priv is evb).
                   13190: $clientip is the user's IP address (only used when checking for access to portfolio
                   13191: files).
                   13192: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   13193: prevents recursive calls to &allowed.
                   13194: 
1.243     albertel 13195:  F: full access
                   13196:  U,I,K: authentication modes (cxx only)
                   13197:  '': forbidden
                   13198:  1: user needs to choose course
                   13199:  2: browse allowed
1.766     albertel 13200:  A: passphrase authentication needed
1.1172.2.65  raeburn  13201:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13202: 
                   13203: =item *
                   13204: 
1.1172.2.13  raeburn  13205: constructaccess($url,$setpriv) : check for access to construction space URL
                   13206: 
                   13207: See if the owner domain and name in the URL match those in the
                   13208: expected environment.  If so, return three element list
                   13209: ($ownername,$ownerdomain,$ownerhome).
                   13210: 
                   13211: Otherwise return the null string.
                   13212: 
                   13213: If second argument 'setpriv' is true, it assigns the privileges,
                   13214: and returns the same three element list, unless the owner has
                   13215: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13216: in which case the null string is returned.
                   13217: 
                   13218: =item *
                   13219: 
1.243     albertel 13220: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   13221: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   13222: and course level
                   13223: 
                   13224: =item *
                   13225: 
1.988     raeburn  13226: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13227: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13228: $type is Course (default) or Community.
1.988     raeburn  13229: If $forcedefault evaluates to true, text returned will be default 
                   13230: text for $type. Otherwise, if this is a course, the text returned 
                   13231: will be a custom name for the role (if defined in the course's 
                   13232: environment).  If no custom name is defined the default is returned.
                   13233:    
1.832     raeburn  13234: =item *
                   13235: 
1.1172.2.23  raeburn  13236: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13237: All arguments are optional. Returns a hash of a roles, either for
                   13238: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13239: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13240: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13241: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13242: For each key, value is set to colon-separated start and end times for
                   13243: the role.  If no username and domain are specified, will default to
1.934     raeburn  13244: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13245: of role statuses (active, future or previous), roles 
                   13246: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13247: to restrict the list of roles reported. If no array ref is 
                   13248: provided for types, will default to return only active roles.
1.834     albertel 13249: 
1.1172.2.13  raeburn  13250: =item *
                   13251: 
                   13252: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   13253: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   13254: 
                   13255: Additional optional arguments are: $type (if role checking is to be restricted
                   13256: to certain user status types -- previous (expired roles), active (currently
                   13257: available roles) or future (roles available in the future), and
                   13258: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  13259: have active Domain Coordinator role in course's domain or in additional
                   13260: domains (specified in 'Domains to check for privileged users' in course
                   13261: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13262: 
                   13263: =item *
                   13264: 
                   13265: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13266: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13267: $possdomains and $possroles are optional array refs -- to domains to check and
                   13268: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13269: users' roles.db to check for a dc or su role in any domain. This can be
                   13270: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13271: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13272: this then allows &privileged_by_domain() to be used, which caches the identity
                   13273: of privileged users, eliminating the need for repeated calls to &dump().
                   13274: 
                   13275: =item *
                   13276: 
                   13277: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13278: where the outer hash keys are domains specified in the $possdomains array ref,
                   13279: next inner hash keys are privileged roles specified in the $roles array ref,
                   13280: and the innermost hash contains key = value pairs for username:domain = end:start
                   13281: for active or future "privileged" users with that role in that domain. To avoid
                   13282: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13283: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  13284: 
1.243     albertel 13285: =back
                   13286: 
                   13287: =head2 User Modification
                   13288: 
                   13289: =over 4
                   13290: 
                   13291: =item *
                   13292: 
1.957     raeburn  13293: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13294: user for the level given by URL.  Optional start and end dates (leave empty
                   13295: string or zero for "no date")
1.191     harris41 13296: 
                   13297: =item *
                   13298: 
1.243     albertel 13299: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13300: change a users, password, possible return values are: ok,
                   13301: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13302: refused
1.191     harris41 13303: 
                   13304: =item *
                   13305: 
1.243     albertel 13306: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13307: 
                   13308: =item *
                   13309: 
1.1058    raeburn  13310: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13311:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13312: 
                   13313: will update user information (firstname,middlename,lastname,generation,
                   13314: permanentemail), and if forceid is true, student/employee ID also.
                   13315: A user's institutional affiliation(s) can also be updated.
                   13316: User information fields will not be overwritten with empty entries 
                   13317: unless the field is included in the $candelete array reference.
                   13318: This array is included when a single user is modified via "Manage Users",
                   13319: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13320: 
                   13321: =item *
                   13322: 
1.286     matthew  13323: modifystudent
                   13324: 
1.957     raeburn  13325: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  13326: The course id is resolved based on the current user's environment.  
                   13327: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13328: associated with a course.
                   13329: 
1.297     matthew  13330: This call is essentially a wrapper for lonnet::modifyuser and
                   13331: lonnet::modify_student_enrollment
1.286     matthew  13332: 
                   13333: Inputs: 
                   13334: 
                   13335: =over 4
                   13336: 
1.957     raeburn  13337: =item B<$udom> Student's loncapa domain
1.286     matthew  13338: 
1.957     raeburn  13339: =item B<$uname> Student's loncapa login name
1.286     matthew  13340: 
1.964     bisitz   13341: =item B<$uid> Student/Employee ID
1.286     matthew  13342: 
1.957     raeburn  13343: =item B<$umode> Student's authentication mode
1.286     matthew  13344: 
1.957     raeburn  13345: =item B<$upass> Student's password
1.286     matthew  13346: 
1.957     raeburn  13347: =item B<$first> Student's first name
1.286     matthew  13348: 
1.957     raeburn  13349: =item B<$middle> Student's middle name
1.286     matthew  13350: 
1.957     raeburn  13351: =item B<$last> Student's last name
1.286     matthew  13352: 
1.957     raeburn  13353: =item B<$gene> Student's generation
1.286     matthew  13354: 
1.957     raeburn  13355: =item B<$usec> Student's section in course
1.286     matthew  13356: 
                   13357: =item B<$end> Unix time of the roles expiration
                   13358: 
                   13359: =item B<$start> Unix time of the roles start date
                   13360: 
                   13361: =item B<$forceid> If defined, allow $uid to be changed
                   13362: 
                   13363: =item B<$desiredhome> server to use as home server for student
                   13364: 
1.957     raeburn  13365: =item B<$email> Student's permanent e-mail address
                   13366: 
                   13367: =item B<$type> Type of enrollment (auto or manual)
                   13368: 
1.963     raeburn  13369: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13370: 
                   13371: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13372: 
1.963     raeburn  13373: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13374: 
1.963     raeburn  13375: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13376: 
1.1172.2.19  raeburn  13377: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13378: 
                   13379: =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  13380: 
1.286     matthew  13381: =back
1.297     matthew  13382: 
                   13383: =item *
                   13384: 
                   13385: modify_student_enrollment
                   13386: 
1.1172.2.31  raeburn  13387: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13388: 'role.request.course' must be defined for this function to proceed.
                   13389: 
                   13390: Inputs:
                   13391: 
                   13392: =over 4
                   13393: 
1.1172.2.31  raeburn  13394: =item $udom, student's domain
1.297     matthew  13395: 
1.1172.2.31  raeburn  13396: =item $uname, student's name
1.297     matthew  13397: 
1.1172.2.31  raeburn  13398: =item $uid, student's user id
1.297     matthew  13399: 
1.1172.2.31  raeburn  13400: =item $first, student's first name
1.297     matthew  13401: 
                   13402: =item $middle
                   13403: 
                   13404: =item $last
                   13405: 
                   13406: =item $gene
                   13407: 
                   13408: =item $usec
                   13409: 
                   13410: =item $end
                   13411: 
                   13412: =item $start
                   13413: 
1.957     raeburn  13414: =item $type
                   13415: 
                   13416: =item $locktype
                   13417: 
                   13418: =item $cid
                   13419: 
                   13420: =item $selfenroll
                   13421: 
                   13422: =item $context
                   13423: 
1.1172.2.19  raeburn  13424: =item $credits, number of credits student will earn from this class
                   13425: 
1.1172.2.76  raeburn  13426: =item $instsec, institutional course section code for student
                   13427: 
1.297     matthew  13428: =back
                   13429: 
1.191     harris41 13430: 
                   13431: =item *
                   13432: 
1.243     albertel 13433: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13434: custom role; give a custom role to a user for the level given by URL.  Specify
                   13435: name and domain of role author, and role name
1.191     harris41 13436: 
                   13437: =item *
                   13438: 
1.243     albertel 13439: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13440: 
                   13441: =item *
                   13442: 
1.243     albertel 13443: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13444: 
                   13445: =back
                   13446: 
                   13447: =head2 Course Infomation
                   13448: 
                   13449: =over 4
1.191     harris41 13450: 
                   13451: =item *
                   13452: 
1.1118    foxr     13453: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13454: specified course id, including all environment settings for the
                   13455: course, the description of the course will be in the hash under the
                   13456: key 'description'
1.191     harris41 13457: 
1.1118    foxr     13458: $options is an optional parameter that if supplied is a hash reference that controls
                   13459: what how this function works.  It has the following key/values:
                   13460: 
                   13461: =over 4
                   13462: 
                   13463: =item freshen_cache
                   13464: 
                   13465: If defined, and the environment cache for the course is valid, it is 
                   13466: returned in the returned hash.
                   13467: 
                   13468: =item one_time
                   13469: 
                   13470: If defined, the last cache time is set to _now_
                   13471: 
                   13472: =item user
                   13473: 
                   13474: If defined, the supplied username is used instead of the current user.
                   13475: 
                   13476: 
                   13477: =back
                   13478: 
1.191     harris41 13479: =item *
                   13480: 
1.624     albertel 13481: resdata($name,$domain,$type,@which) : request for current parameter
                   13482: setting for a specific $type, where $type is either 'course' or 'user',
                   13483: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  13484: answers for 10 minutes.
1.243     albertel 13485: 
1.877     foxr     13486: =item *
                   13487: 
                   13488: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13489: data base, returning a hash that is keyed by the resource name and has
                   13490: values that are the resource value.  I believe that the timestamps and
                   13491: versions are also returned.
                   13492: 
1.1172.2.31  raeburn  13493: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13494: supplemental content area. This routine caches the number of files for
                   13495: 10 minutes.
                   13496: 
1.243     albertel 13497: =back
                   13498: 
                   13499: =head2 Course Modification
                   13500: 
                   13501: =over 4
1.191     harris41 13502: 
                   13503: =item *
                   13504: 
1.243     albertel 13505: writecoursepref($courseid,%prefs) : write preferences (environment
                   13506: database) for a course
1.191     harris41 13507: 
                   13508: =item *
                   13509: 
1.1011    raeburn  13510: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13511: 
                   13512: =item *
                   13513: 
1.1038    raeburn  13514: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13515: 
1.1167    droeschl 13516: =item *
                   13517: 
                   13518: is_course($courseid), is_course($cdom, $cnum)
                   13519: 
                   13520: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13521: two component version $cdom, $cnum. It checks if the specified course exists.
                   13522: 
                   13523: Returns:
                   13524:     undef if the course doesn't exist, otherwise
                   13525:     in scalar context the combined courseid.
                   13526:     in list context the two components of the course identifier, domain and 
                   13527:     courseid.    
                   13528: 
1.243     albertel 13529: =back
                   13530: 
                   13531: =head2 Resource Subroutines
                   13532: 
                   13533: =over 4
1.191     harris41 13534: 
                   13535: =item *
                   13536: 
1.243     albertel 13537: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13538: 
                   13539: =item *
                   13540: 
1.243     albertel 13541: repcopy($filename) : subscribes to the requested file, and attempts to
                   13542: replicate from the owning library server, Might return
1.607     raeburn  13543: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13544: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13545: resource. Expects the local filesystem pathname
                   13546: (/home/httpd/html/res/....)
                   13547: 
                   13548: =back
                   13549: 
                   13550: =head2 Resource Information
                   13551: 
                   13552: =over 4
1.191     harris41 13553: 
                   13554: =item *
                   13555: 
1.1172.2.28  raeburn  13556: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13557: and returns the value of a variety of different possible values,
                   13558: $varname should be a request string, and the other parameters can be
                   13559: used to specify who and what one is asking about. Ordinarily, $cid 
                   13560: does not need to be specified, as it is retrived from 
                   13561: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13562: within lonuserstate::loadmap() when initializing a course, before
                   13563: $env{'request.course.id'} has been set, so it needs to be provided
                   13564: in that one case.
1.243     albertel 13565: 
                   13566: Possible values for $varname are environment.lastname (or other item
                   13567: from the envirnment hash), user.name (or someother aspect about the
                   13568: user), resource.0.maxtries (or some other part and parameter of a
                   13569: resource)
1.204     albertel 13570: 
                   13571: =item *
                   13572: 
1.243     albertel 13573: directcondval($number) : get current value of a condition; reads from a state
                   13574: string
1.204     albertel 13575: 
                   13576: =item *
                   13577: 
1.243     albertel 13578: condval($condidx) : value of condition index based on state
1.204     albertel 13579: 
                   13580: =item *
                   13581: 
1.243     albertel 13582: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13583: resource's metadata, $what should be either a specific key, or either
                   13584: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13585: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13586: 
                   13587: this function automatically caches all requests
1.191     harris41 13588: 
                   13589: =item *
                   13590: 
1.243     albertel 13591: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13592: network of library servers; returns file handle of where SQL and regex results
                   13593: will be stored for query
1.191     harris41 13594: 
                   13595: =item *
                   13596: 
1.1172.2.66  raeburn  13597: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   13598: return symbolic list entry (all arguments optional).
                   13599: 
                   13600: Args: filename is the filename (including path) for the file for which a symb
                   13601: is required; donotrecurse, if true will prevent calls to allowed() being made
                   13602: to check access status if more than one resource was found in the bighash
                   13603: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   13604: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   13605: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   13606: cause possible symbs to be checked to determine if they are subject to content
                   13607: blocking, if so they will not be included as possible symbs; possibles is a
                   13608: ref to a hash, which, as a side effect, will be populated with all possible
                   13609: symbs (content blocking not tested).
                   13610: 
1.243     albertel 13611: returns the data handle
1.191     harris41 13612: 
                   13613: =item *
                   13614: 
1.1172.2.17  raeburn  13615: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  13616: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13617: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  13618: on failure, user must be in a course, as it assumes the existence of
                   13619: the course initial hash, and uses $env('request.course.id'}.  The third
                   13620: arg is an optional reference to a scalar.  If this arg is passed in the
                   13621: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13622: encrypted; otherwise it will be null.
1.243     albertel 13623: 
1.191     harris41 13624: =item *
                   13625: 
1.243     albertel 13626: symbclean($symb) : removes versions numbers from a symb, returns the
                   13627: cleaned symb
1.191     harris41 13628: 
                   13629: =item *
                   13630: 
1.243     albertel 13631: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13632: course map, user must be in a course for it to work.
1.191     harris41 13633: 
                   13634: =item *
                   13635: 
1.243     albertel 13636: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13637: 
                   13638: =item *
                   13639: 
1.243     albertel 13640: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13641: a random seed, all arguments are optional, if they aren't sent it uses the
                   13642: environment to derive them. Note: if symb isn't sent and it can't get one
                   13643: from &symbread it will use the current time as its return value
1.191     harris41 13644: 
                   13645: =item *
                   13646: 
1.243     albertel 13647: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13648: unfakeable, receipt
1.191     harris41 13649: 
                   13650: =item *
                   13651: 
1.620     albertel 13652: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13653: 
                   13654: =item *
                   13655: 
1.243     albertel 13656: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13657: 
                   13658: =item *
                   13659: 
1.243     albertel 13660: 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 13661: 
                   13662: =item *
                   13663: 
1.243     albertel 13664: 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 13665: 
                   13666: =item *
                   13667: 
1.243     albertel 13668: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13669: 
                   13670: =item *
                   13671: 
1.243     albertel 13672: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13673: forcing spreadsheet to reevaluate the resource scores next time.
                   13674: 
1.1172.2.13  raeburn  13675: =item *
                   13676: 
                   13677: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13678: when viewing in course context.
                   13679: 
                   13680:  input: six args -- filename (decluttered), course number, course domain,
                   13681:                     url, symb (if registered) and group (if this is a
                   13682:                     group item -- e.g., bulletin board, group page etc.).
                   13683: 
                   13684:  output: array of five scalars --
                   13685:          $cfile -- url for file editing if editable on current server
                   13686:          $home -- homeserver of resource (i.e., for author if published,
                   13687:                                           or course if uploaded.).
                   13688:          $switchserver --  1 if server switch will be needed.
                   13689:          $forceedit -- 1 if icon/link should be to go to edit mode
                   13690:          $forceview -- 1 if icon/link should be to go to view mode
                   13691: 
                   13692: =item *
                   13693: 
                   13694: is_course_upload($file,$cnum,$cdom)
                   13695: 
                   13696: Used in course context to determine if current file was uploaded to
                   13697: the course (i.e., would be found in /userfiles/docs on the course's
                   13698: homeserver.
                   13699: 
                   13700:   input: 3 args -- filename (decluttered), course number and course domain.
                   13701:   output: boolean -- 1 if file was uploaded.
                   13702: 
1.243     albertel 13703: =back
                   13704: 
                   13705: =head2 Storing/Retreiving Data
                   13706: 
                   13707: =over 4
1.191     harris41 13708: 
                   13709: =item *
                   13710: 
1.1172.2.64  raeburn  13711: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   13712: permanently for this url; hashref needs to be given and should be a \%hashname;
                   13713: the remaining args aren't required and if they aren't passed or are '' they will
                   13714: be derived from the env (with the exception of $laststore, which is an
                   13715: optional arg used when a user's submission is stored in grading).
                   13716: $laststore is $version=$timestamp, where $version is the most recent version
                   13717: number retrieved for the corresponding $symb in the $namespace db file, and
                   13718: $timestamp is the timestamp for that transaction (UNIX time).
                   13719: $laststore is currently only passed when cstore() is called by
                   13720: structuretags::finalize_storage().
1.191     harris41 13721: 
                   13722: =item *
                   13723: 
1.1172.2.64  raeburn  13724: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   13725: but uses critical subroutine
1.191     harris41 13726: 
                   13727: =item *
                   13728: 
1.243     albertel 13729: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13730: all args are optional
1.191     harris41 13731: 
                   13732: =item *
                   13733: 
1.717     albertel 13734: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13735: dumps the complete (or key matching regexp) namespace into a hash
                   13736: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13737: normally &store()ed into
                   13738: 
                   13739: $range should be either an integer '100' (give me the first 100
                   13740:                                            matching records)
                   13741:               or be  two integers sperated by a - with no spaces
                   13742:                  '30-50' (give me the 30th through the 50th matching
                   13743:                           records)
                   13744: 
                   13745: 
                   13746: =item *
                   13747: 
1.1172.2.59  raeburn  13748: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 13749: replaces a &store() version of data with a replacement set of data
                   13750: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  13751: reference. If $tolog is true, the transaction is logged in the courselog
                   13752: with an action=PUTSTORE.
1.717     albertel 13753: 
                   13754: =item *
                   13755: 
1.243     albertel 13756: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13757: works very similar to store/cstore, but all data is stored in a
                   13758: temporary location and can be reset using tmpreset, $storehash should
                   13759: be a hash reference, returns nothing on success
1.191     harris41 13760: 
                   13761: =item *
                   13762: 
1.243     albertel 13763: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13764: similar to restore, but all data is stored in a temporary location and
                   13765: can be reset using tmpreset. Returns a hash of values on success,
                   13766: error string otherwise.
1.191     harris41 13767: 
                   13768: =item *
                   13769: 
1.243     albertel 13770: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13771: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13772: 
                   13773: =item *
                   13774: 
1.243     albertel 13775: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13776: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13777: 
                   13778: =item *
                   13779: 
1.243     albertel 13780: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13781: namesp ($udom and $uname are optional)
1.191     harris41 13782: 
                   13783: =item *
                   13784: 
1.702     albertel 13785: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13786: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13787: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13788: 
1.702     albertel 13789: $range should be either an integer '100' (give me the first 100
                   13790:                                            matching records)
                   13791:               or be  two integers sperated by a - with no spaces
                   13792:                  '30-50' (give me the 30th through the 50th matching
                   13793:                           records)
1.449     matthew  13794: =item *
                   13795: 
                   13796: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13797: $store can be a scalar, an array reference, or if the amount to be 
                   13798: incremented is > 1, a hash reference.
                   13799: 
                   13800: ($udom and $uname are optional)
1.191     harris41 13801: 
                   13802: =item *
                   13803: 
1.243     albertel 13804: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13805: ($udom and $uname are optional)
1.191     harris41 13806: 
                   13807: =item *
                   13808: 
1.243     albertel 13809: cput($namespace,$storehash,$udom,$uname) : critical put
                   13810: ($udom and $uname are optional)
1.191     harris41 13811: 
                   13812: =item *
                   13813: 
1.748     albertel 13814: newput($namespace,$storehash,$udom,$uname) :
                   13815: 
                   13816: Attempts to store the items in the $storehash, but only if they don't
                   13817: currently exist, if this succeeds you can be certain that you have 
                   13818: successfully created a new key value pair in the $namespace db.
                   13819: 
                   13820: 
                   13821: Args:
                   13822:  $namespace: name of database to store values to
                   13823:  $storehash: hashref to store to the db
                   13824:  $udom: (optional) domain of user containing the db
                   13825:  $uname: (optional) name of user caontaining the db
                   13826: 
                   13827: Returns:
                   13828:  'ok' -> succeeded in storing all keys of $storehash
                   13829:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13830:                         least <key> already existed in the db (other
                   13831:                         requested keys may also already exist)
1.967     bisitz   13832:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13833:  'con_lost' -> unable to contact request server
                   13834:  'refused' -> action was not allowed by remote machine
                   13835: 
                   13836: 
                   13837: =item *
                   13838: 
1.243     albertel 13839: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13840: reference filled in from namesp (encrypts the return communication)
                   13841: ($udom and $uname are optional)
1.191     harris41 13842: 
                   13843: =item *
                   13844: 
1.243     albertel 13845: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13846: critical subroutine
                   13847: 
1.806     raeburn  13848: =item *
                   13849: 
1.860     raeburn  13850: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13851: array reference filled in from namespace found in domain level on either
                   13852: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13853: 
                   13854: =item *
                   13855: 
1.860     raeburn  13856: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13857: domain level either on specified domain server ($uhome) or primary domain 
                   13858: server ($udom and $uhome are optional)
1.806     raeburn  13859: 
1.943     raeburn  13860: =item * 
                   13861: 
1.1172.2.35  raeburn  13862: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   13863: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13864: the target domain.
                   13865: 
                   13866: May also include additional key => value pairs for the following groups:
                   13867: 
                   13868: =over
                   13869: 
                   13870: =item
                   13871: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13872: 
                   13873: =over
                   13874: 
                   13875: =item defaultquota, authorquota
                   13876: 
                   13877: =back
                   13878: 
                   13879: =item
                   13880: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13881: portfolio for users).
                   13882: 
                   13883: =over
                   13884: 
                   13885: =item
                   13886: aboutme, blog, webdav, portfolio
                   13887: 
                   13888: =back
                   13889: 
                   13890: =item
                   13891: requestcourses: ability to request courses, and how requests are processed.
                   13892: 
                   13893: =over
                   13894: 
                   13895: =item
1.1172.2.37  raeburn  13896: official, unofficial, community, textbook
1.1172.2.35  raeburn  13897: 
                   13898: =back
                   13899: 
                   13900: =item
                   13901: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13902: 
                   13903: =over
                   13904: 
                   13905: =item
1.1172.2.44  raeburn  13906: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  13907: 
                   13908: =back
                   13909: 
                   13910: =item
                   13911: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13912: for course's uploaded content.
                   13913: 
                   13914: =over
                   13915: 
                   13916: =item
1.1172.2.68  raeburn  13917: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   13918: communityquota, textbookquota
1.1172.2.35  raeburn  13919: 
                   13920: =back
                   13921: 
                   13922: =item
                   13923: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13924: on your servers.
                   13925: 
                   13926: =over
                   13927: 
                   13928: =item
                   13929: remotesessions, hostedsessions
                   13930: 
                   13931: =back
                   13932: 
                   13933: =back
                   13934: 
                   13935: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13936: utility to create a configuration.db file on a domain's primary library server
                   13937: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13938: -- corresponding values are authentication type (internal, krb4, krb5,
                   13939: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   13940: will be available. Values are retrieved from cache (if current), unless the
                   13941: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13942: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13943: 
                   13944: Typical usage:
1.943     raeburn  13945: 
1.1172.2.35  raeburn  13946: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13947: 
1.243     albertel 13948: =back
                   13949: 
                   13950: =head2 Network Status Functions
                   13951: 
                   13952: =over 4
1.191     harris41 13953: 
                   13954: =item *
                   13955: 
1.1137    raeburn  13956: dirlist() : return directory list based on URI (first arg).
                   13957: 
                   13958: Inputs: 1 required, 5 optional.
                   13959: 
                   13960: =over
                   13961: 
                   13962: =item 
                   13963: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13964: 
                   13965: =item
                   13966: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13967: 
                   13968: =item
                   13969: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13970: 
                   13971: =item
                   13972: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13973: 
                   13974: =item
                   13975: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13976: 
                   13977: =item 
                   13978: $alternateRoot - path to prepend in place of path from $uri.
                   13979: 
                   13980: =back
                   13981: 
                   13982: Returns: Array of up to two items.
                   13983: 
                   13984: =over
                   13985: 
                   13986: a reference to an array of files/subdirectories
                   13987: 
                   13988: =over
                   13989: 
                   13990: Each element in the array of files/subdirectories is a & separated list of
                   13991: item name and the result of running stat on the item.  If dirlist was requested
                   13992: for a file instead of a directory, the item name will be ''. For a directory 
                   13993: listing, if the item is a metadata file, the element will end &N&M 
                   13994: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   13995: default copyright set (1).  
                   13996: 
                   13997: =back
                   13998: 
                   13999: a scalar containing error condition (if encountered).
                   14000: 
                   14001: =over
                   14002: 
                   14003: =item 
                   14004: no_host (no homeserver identified for $username:$domain).
                   14005: 
                   14006: =item 
                   14007: no_such_host (server contacted for listing not identified as valid host).
                   14008: 
                   14009: =item 
                   14010: con_lost (connection to remote server failed).
                   14011: 
                   14012: =item 
                   14013: refused (invalid $username:$domain received on lond side).
                   14014: 
                   14015: =item 
                   14016: no_such_dir (directory at specified path on lond side does not exist). 
                   14017: 
                   14018: =item 
                   14019: empty (directory at specified path on lond side is empty).
                   14020: 
                   14021: =over
                   14022: 
                   14023: This is currently not encountered because the &ls3, &ls2, 
                   14024: &ls (_handler) routines on the lond side do not filter out
                   14025: . and .. from a directory listing. 
                   14026: 
                   14027: =back
                   14028: 
                   14029: =back
                   14030: 
                   14031: =back
1.191     harris41 14032: 
                   14033: =item *
                   14034: 
1.243     albertel 14035: spareserver() : find server with least workload from spare.tab
                   14036: 
1.986     foxr     14037: 
                   14038: =item *
                   14039: 
                   14040: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14041: if there is no corresponding loncapa host.
                   14042: 
1.243     albertel 14043: =back
                   14044: 
1.986     foxr     14045: 
1.243     albertel 14046: =head2 Apache Request
                   14047: 
                   14048: =over 4
1.191     harris41 14049: 
                   14050: =item *
                   14051: 
1.243     albertel 14052: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14053: localhost, posts hash
                   14054: 
                   14055: =back
                   14056: 
                   14057: =head2 Data to String to Data
                   14058: 
                   14059: =over 4
1.191     harris41 14060: 
                   14061: =item *
                   14062: 
1.243     albertel 14063: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14064: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14065: 
                   14066: =item *
                   14067: 
1.243     albertel 14068: hashref2str($hashref) : convert a hashref into a string complete with
                   14069: escaping and '=' and '&' separators, supports elements that are
                   14070: arrayrefs and hashrefs
1.191     harris41 14071: 
                   14072: =item *
                   14073: 
1.243     albertel 14074: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14075: with escaping and '&' separators, supports elements that are arrayrefs
                   14076: and hashrefs
1.191     harris41 14077: 
                   14078: =item *
                   14079: 
1.243     albertel 14080: str2hash($string) : convert string to hash using unescaping and
                   14081: splitting on '=' and '&', supports elements that are arrayrefs and
                   14082: hashrefs
1.191     harris41 14083: 
                   14084: =item *
                   14085: 
1.243     albertel 14086: str2array($string) : convert string to hash using unescaping and
                   14087: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14088: 
                   14089: =back
                   14090: 
                   14091: =head2 Logging Routines
                   14092: 
                   14093: 
                   14094: These routines allow one to make log messages in the lonnet.log and
                   14095: lonnet.perm logfiles.
1.191     harris41 14096: 
1.1119    foxr     14097: =over 4
                   14098: 
1.191     harris41 14099: =item *
                   14100: 
1.243     albertel 14101: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14102: 
                   14103: =item *
                   14104: 
1.243     albertel 14105: logthis() : append message to the normal lonnet.log file, it gets
                   14106: preiodically rolled over and deleted.
1.191     harris41 14107: 
                   14108: =item *
                   14109: 
1.243     albertel 14110: logperm() : append a permanent message to lonnet.perm.log, this log
                   14111: file never gets deleted by any automated portion of the system, only
                   14112: messages of critical importance should go in here.
                   14113: 
1.1119    foxr     14114: 
1.243     albertel 14115: =back
                   14116: 
                   14117: =head2 General File Helper Routines
                   14118: 
                   14119: =over 4
1.191     harris41 14120: 
                   14121: =item *
                   14122: 
1.481     raeburn  14123: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14124: (a) files in /uploaded
                   14125:   (i) If a local copy of the file exists - 
                   14126:       compares modification date of local copy with last-modified date for 
                   14127:       definitive version stored on home server for course. If local copy is 
                   14128:       stale, requests a new version from the home server and stores it. 
                   14129:       If the original has been removed from the home server, then local copy 
                   14130:       is unlinked.
                   14131:   (ii) If local copy does not exist -
                   14132:       requests the file from the home server and stores it. 
                   14133:   
                   14134:   If $caller is 'uploadrep':  
                   14135:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14136:     for request for files originally uploaded via DOCS. 
                   14137:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14138:   
                   14139:   Otherwise:
                   14140:      This indicates a call from the content generation phase of the request.
                   14141:      -  returns the entire contents of the file or -1.
                   14142:      
                   14143: (b) files in /res
                   14144:    - returns the entire contents of a file or -1; 
                   14145:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14146: 
1.712     albertel 14147: 
                   14148: =item *
                   14149: 
                   14150: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14151:                   reference
                   14152: 
                   14153: returns either a stat() list of data about the file or an empty list
                   14154: if the file doesn't exist or couldn't find out about it (connection
                   14155: problems or user unknown)
                   14156: 
1.191     harris41 14157: =item *
                   14158: 
1.243     albertel 14159: filelocation($dir,$file) : returns file system location of a file
                   14160: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14161: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14162: and a file of ../bob will become /a/bob)
1.191     harris41 14163: 
                   14164: =item *
                   14165: 
                   14166: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14167: filelocation except for hrefs
                   14168: 
                   14169: =item *
                   14170: 
1.1172.2.49  raeburn  14171: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14172: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14173: 
1.243     albertel 14174: =back
                   14175: 
1.608     albertel 14176: =head2 Usererfile file routines (/uploaded*)
                   14177: 
                   14178: =over 4
                   14179: 
                   14180: =item *
                   14181: 
                   14182: userfileupload(): main rotine for putting a file in a user or course's
                   14183:                   filespace, arguments are,
                   14184: 
1.620     albertel 14185:  formname - required - this is the name of the element in $env where the
1.608     albertel 14186:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14187:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14188:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14189:  context - if coursedoc, store the file in the course of the active role
                   14190:              of the current user; 
                   14191:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14192:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14193:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14194:          if undefined, it will be placed in "unknown"
                   14195: 
                   14196:  (This routine calls clean_filename() to remove any dangerous
                   14197:  characters from the filename, and then calls finuserfileupload() to
                   14198:  complete the transaction)
                   14199: 
                   14200:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14201:  and /adm/notfound.html if unsuccessful
                   14202: 
                   14203: =item *
                   14204: 
                   14205: clean_filename(): routine for cleaing a filename up for storage in
                   14206:                  userfile space, argument is:
                   14207: 
                   14208:  filename - proposed filename
                   14209: 
                   14210: returns: the new clean filename
                   14211: 
                   14212: =item *
                   14213: 
1.1090    raeburn  14214: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14215: userspace, probably shouldn't be called directly
                   14216: 
                   14217:   docuname: username or courseid of destination for the file
                   14218:   docudom: domain of user/course of destination for the file
                   14219:   formname: same as for userfileupload()
1.1090    raeburn  14220:   fname: filename (including subdirectories) for the file
                   14221:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14222:   allfiles: reference to hash used to store objects found by parser
                   14223:   codebase: reference to hash used for codebases of java objects found by parser
                   14224:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14225:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14226:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14227:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14228:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14229:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14230:   mimetype: reference to scalar to accommodate mime type determined
                   14231:             from File::MMagic if $parser = parse.
1.608     albertel 14232: 
                   14233:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14234:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14235:  was 'overwrite').
                   14236:  
1.608     albertel 14237: 
                   14238: =item *
                   14239: 
                   14240: renameuserfile(): renames an existing userfile to a new name
                   14241: 
                   14242:   Args:
                   14243:    docuname: username or courseid of destination for the file
                   14244:    docudom: domain of user/course of destination for the file
                   14245:    old: current file name (including any subdirs under userfiles)
                   14246:    new: desired file name (including any subdirs under userfiles)
                   14247: 
                   14248: =item *
                   14249: 
                   14250: mkdiruserfile(): creates a directory is a userfiles dir
                   14251: 
                   14252:   Args:
                   14253:    docuname: username or courseid of destination for the file
                   14254:    docudom: domain of user/course of destination for the file
                   14255:    dir: dir to create (including any subdirs under userfiles)
                   14256: 
                   14257: =item *
                   14258: 
                   14259: removeuserfile(): removes a file that exists in userfiles
                   14260: 
                   14261:   Args:
                   14262:    docuname: username or courseid of destination for the file
                   14263:    docudom: domain of user/course of destination for the file
                   14264:    fname: filname to delete (including any subdirs under userfiles)
                   14265: 
                   14266: =item *
                   14267: 
                   14268: removeuploadedurl(): convience function for removeuserfile()
                   14269: 
                   14270:   Args:
                   14271:    url:  a full /uploaded/... url to delete
                   14272: 
1.747     albertel 14273: =item * 
                   14274: 
                   14275: get_portfile_permissions():
                   14276:   Args:
                   14277:     domain: domain of user or course contain the portfolio files
                   14278:     user: name of user or num of course contain the portfolio files
                   14279:   Returns:
                   14280:     hashref of a dump of the proper file_permissions.db
                   14281:    
                   14282: 
                   14283: =item * 
                   14284: 
                   14285: get_access_controls():
                   14286: 
                   14287: Args:
                   14288:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14289:   group: (optional) the group you want the files associated with
                   14290:   file: (optional) the file you want access info on
                   14291: 
                   14292: Returns:
1.749     raeburn  14293:     a hash (keys are file names) of hashes containing
                   14294:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14295:         values are XML containing access control settings (see below) 
1.747     albertel 14296: 
                   14297: Internal notes:
                   14298: 
1.749     raeburn  14299:  access controls are stored in file_permissions.db as key=value pairs.
                   14300:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14301:         where scope -> public,guest,course,group,domains or users.
                   14302:               end -> UNIX time for end of access (0 -> no end date)
                   14303:               start -> UNIX time for start of access
                   14304: 
                   14305:     value -> XML description of access control
                   14306:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14307:             <start></start>
                   14308:             <end></end>
                   14309: 
                   14310:             <password></password>  for scope type = guest
                   14311: 
                   14312:             <domain></domain>     for scope type = course or group
                   14313:             <number></number>
                   14314:             <roles id="">
                   14315:              <role></role>
                   14316:              <access></access>
                   14317:              <section></section>
                   14318:              <group></group>
                   14319:             </roles>
                   14320: 
                   14321:             <dom></dom>         for scope type = domains
                   14322: 
                   14323:             <users>             for scope type = users
                   14324:              <user>
                   14325:               <uname></uname>
                   14326:               <udom></udom>
                   14327:              </user>
                   14328:             </users>
                   14329:            </scope> 
                   14330:               
                   14331:  Access data is also aggregated for each file in an additional key=value pair:
                   14332:  key -> path to file/file_name\0accesscontrol 
                   14333:  value -> reference to hash
                   14334:           hash contains key = value pairs
                   14335:           where key = uniqueID:scope_end_start
                   14336:                 value = UNIX time record was last updated
                   14337: 
                   14338:           Used to improve speed of look-ups of access controls for each file.  
                   14339:  
                   14340:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14341: 
1.1172.2.13  raeburn  14342: =item *
                   14343: 
1.749     raeburn  14344: modify_access_controls():
                   14345: 
                   14346: Modifies access controls for a portfolio file
                   14347: Args
                   14348: 1. file name
                   14349: 2. reference to hash of required changes,
                   14350: 3. domain
                   14351: 4. username
                   14352:   where domain,username are the domain of the portfolio owner 
                   14353:   (either a user or a course) 
                   14354: 
                   14355: Returns:
                   14356: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14357: 2. result of deletions ('ok' or 'error', with error message).
                   14358: 3. reference to hash of any new or updated access controls.
                   14359: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14360:    key = integer (inbound ID)
1.1172.2.13  raeburn  14361:    value = uniqueID
                   14362: 
                   14363: =item *
                   14364: 
                   14365: get_timebased_id():
                   14366: 
                   14367: Attempts to get a unique timestamp-based suffix for use with items added to a
                   14368: course via the Course Editor (e.g., folders, composite pages,
                   14369: group bulletin boards).
                   14370: 
                   14371: Args: (first three required; six others optional)
                   14372: 
                   14373: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14374:    docssequence, or name of group
                   14375: 
                   14376: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14377:    e.g., num, boardids
                   14378: 
                   14379: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   14380:    file will be named nohist_namespace.db
                   14381: 
                   14382: 4. cdom: domain of course; default is current course domain from %env
                   14383: 
                   14384: 5. cnum: course number; default is current course number from %env
                   14385: 
                   14386: 6. idtype: set to concat if an additional digit is to be appended to the
                   14387:    unix timestamp to form the suffix, if the plain timestamp is already
                   14388:    in use.  Default is to not do this, but simply increment the unix
                   14389:    timestamp by 1 until a unique key is obtained.
                   14390: 
                   14391: 7. who: holder of locking key; defaults to user:domain for user.
                   14392: 
                   14393: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   14394:    retrying); default is 3.
                   14395: 
                   14396: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   14397: 
                   14398: Returns:
                   14399: 
                   14400: 1. suffix obtained (numeric)
                   14401: 
                   14402: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14403: 
                   14404: 3. error: contains (localized) error message if an error occurred.
                   14405: 
1.747     albertel 14406: 
1.608     albertel 14407: =back
                   14408: 
1.243     albertel 14409: =head2 HTTP Helper Routines
                   14410: 
                   14411: =over 4
                   14412: 
1.191     harris41 14413: =item *
                   14414: 
                   14415: escape() : unpack non-word characters into CGI-compatible hex codes
                   14416: 
                   14417: =item *
                   14418: 
                   14419: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14420: 
1.243     albertel 14421: =back
                   14422: 
                   14423: =head1 PRIVATE SUBROUTINES
                   14424: 
                   14425: =head2 Underlying communication routines (Shouldn't call)
                   14426: 
                   14427: =over 4
                   14428: 
                   14429: =item *
                   14430: 
                   14431: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14432: 
                   14433: =item *
                   14434: 
                   14435: reply() : uses subreply to send a message to remote machine, logs all failures
                   14436: 
                   14437: =item *
                   14438: 
                   14439: critical() : passes a critical message to another server; if cannot
                   14440: get through then place message in connection buffer directory and
                   14441: returns con_delayed, if incapable of saving message, returns
                   14442: con_failed
                   14443: 
                   14444: =item *
                   14445: 
                   14446: reconlonc() : tries to reconnect lonc client processes.
                   14447: 
                   14448: =back
                   14449: 
                   14450: =head2 Resource Access Logging
                   14451: 
                   14452: =over 4
                   14453: 
                   14454: =item *
                   14455: 
                   14456: flushcourselogs() : flush (save) buffer logs and access logs
                   14457: 
                   14458: =item *
                   14459: 
                   14460: courselog($what) : save message for course in hash
                   14461: 
                   14462: =item *
                   14463: 
                   14464: courseacclog($what) : save message for course using &courselog().  Perform
                   14465: special processing for specific resource types (problems, exams, quizzes, etc).
                   14466: 
1.191     harris41 14467: =item *
                   14468: 
                   14469: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14470: as a PerlChildExitHandler
1.243     albertel 14471: 
                   14472: =back
                   14473: 
                   14474: =head2 Other
                   14475: 
                   14476: =over 4
                   14477: 
                   14478: =item *
                   14479: 
                   14480: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14481: 
                   14482: =back
                   14483: 
                   14484: =cut
1.877     foxr     14485: 

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