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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.93.2  1(raebur    4:7): # $Id: lonnet.pm,v 1.1172.2.93 2017/05/13 13:58:49 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.1172.2.88  raeburn  1005:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
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 {
1.1172.2.88  raeburn  1277:     my ($uname,$udom,$caller) = @_;
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.88  raeburn  1428:         unless ($caller eq 'login') {
                   1429:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1430:                 $is_balancer = 0;
                   1431:                 if ($uname ne '' && $udom ne '') {
                   1432:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1172.2.5  raeburn  1433: 
1.1172.2.88  raeburn  1434:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1435:                                  'user.loadbalcheck.time' => time});
                   1436:                     }
1.1172.2.5  raeburn  1437:                 }
1.1129    raeburn  1438:             }
                   1439:         }
                   1440:     }
                   1441:     return ($is_balancer,$otherserver);
                   1442: }
                   1443: 
1.1172.2.12  raeburn  1444: sub check_balancer_result {
                   1445:     my ($result,@hosts) = @_;
                   1446:     my ($is_balancer,$currtargets,$currrules);
                   1447:     if (ref($result) eq 'HASH') {
                   1448:         if ($result->{'lonhost'} ne '') {
                   1449:             my $currbalancer = $result->{'lonhost'};
                   1450:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1451:                 $is_balancer = 1;
                   1452:                 $currtargets = $result->{'targets'};
                   1453:                 $currrules = $result->{'rules'};
                   1454:             }
                   1455:         } else {
                   1456:             foreach my $key (keys(%{$result})) {
                   1457:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1458:                     (ref($result->{$key}) eq 'HASH')) {
                   1459:                     $is_balancer = 1;
                   1460:                     $currrules = $result->{$key}{'rules'};
                   1461:                     $currtargets = $result->{$key}{'targets'};
                   1462:                     last;
                   1463:                 }
                   1464:             }
                   1465:         }
                   1466:     }
                   1467:     return ($is_balancer,$currtargets,$currrules);
                   1468: }
                   1469: 
1.1129    raeburn  1470: sub get_loadbalancer_targets {
                   1471:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1472:     my $offloadto;
1.1172.2.4  raeburn  1473:     if ($rule_in_effect eq 'none') {
                   1474:         return [$perlvar{'lonHostID'}];
                   1475:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1476:         $offloadto = $currtargets;
                   1477:     } else {
                   1478:         if ($rule_in_effect eq 'homeserver') {
                   1479:             my $homeserver = &homeserver($uname,$udom);
                   1480:             if ($homeserver ne 'no_host') {
                   1481:                 $offloadto = [$homeserver];
                   1482:             }
                   1483:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1484:             my %domconfig =
                   1485:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1486:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1487:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1488:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1489:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1490:                     }
                   1491:                 }
                   1492:             } else {
1.1172.2.7  raeburn  1493:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1494:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1495:                 if (&hostname($remotebalancer) ne '') {
                   1496:                     $offloadto = [$remotebalancer];
                   1497:                 }
                   1498:             }
                   1499:         } elsif (&hostname($rule_in_effect) ne '') {
                   1500:             $offloadto = [$rule_in_effect];
                   1501:         }
                   1502:     }
                   1503:     return $offloadto;
                   1504: }
                   1505: 
1.1127    raeburn  1506: sub internet_dom_servers {
                   1507:     my ($dom) = @_;
                   1508:     my (%uniqservers,%servers);
                   1509:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1510:     my @machinedoms = &machine_domains($primaryserver);
                   1511:     foreach my $mdom (@machinedoms) {
                   1512:         my %currservers = %servers;
                   1513:         my %server = &get_servers($mdom);
                   1514:         %servers = (%currservers,%server);
                   1515:     }
                   1516:     my %by_hostname;
                   1517:     foreach my $id (keys(%servers)) {
                   1518:         push(@{$by_hostname{$servers{$id}}},$id);
                   1519:     }
                   1520:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1521:         if (@{$by_hostname{$hostname}} > 1) {
                   1522:             my $match = 0;
                   1523:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1524:                 if (&host_domain($id) eq $dom) {
                   1525:                     $uniqservers{$id} = $hostname;
                   1526:                     $match = 1;
                   1527:                 }
                   1528:             }
                   1529:             unless ($match) {
                   1530:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1531:             }
                   1532:         } else {
                   1533:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1534:         }
                   1535:     }
                   1536:     return %uniqservers;
                   1537: }
                   1538: 
1.1       albertel 1539: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1540: 
1.599     albertel 1541: my %homecache;
1.1       albertel 1542: sub homeserver {
1.230     stredwic 1543:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1544:     my $index="$uname:$udom";
1.426     albertel 1545: 
1.599     albertel 1546:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1547: 
                   1548:     my %servers = &get_servers($udom,'library');
                   1549:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1550:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1551: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1552: 
                   1553: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1554: 	if ($answer eq 'found') {
                   1555: 	    delete($badServerCache{$tryserver}); 
                   1556: 	    return $homecache{$index}=$tryserver;
                   1557: 	} elsif ($answer eq 'no_host') {
                   1558: 	    $badServerCache{$tryserver}=1;
                   1559: 	}
1.1       albertel 1560:     }    
                   1561:     return 'no_host';
1.70      www      1562: }
                   1563: 
                   1564: # ------------------------------------- Find the usernames behind a list of IDs
                   1565: 
                   1566: sub idget {
                   1567:     my ($udom,@ids)=@_;
                   1568:     my %returnhash=();
                   1569:     
1.841     albertel 1570:     my %servers = &get_servers($udom,'library');
                   1571:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1572: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1573: 	$idlist=~tr/A-Z/a-z/; 
                   1574: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1575: 	my @answer=();
                   1576: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1577: 	    @answer=split(/\&/,$reply);
                   1578: 	}                    ;
                   1579: 	my $i;
                   1580: 	for ($i=0;$i<=$#ids;$i++) {
                   1581: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1582: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1583: 	    } 
                   1584: 	}
                   1585:     } 
1.70      www      1586:     return %returnhash;
                   1587: }
                   1588: 
                   1589: # ------------------------------------- Find the IDs behind a list of usernames
                   1590: 
                   1591: sub idrget {
                   1592:     my ($udom,@unames)=@_;
                   1593:     my %returnhash=();
1.800     albertel 1594:     foreach my $uname (@unames) {
                   1595:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1596:     }
1.70      www      1597:     return %returnhash;
                   1598: }
                   1599: 
                   1600: # ------------------------------- Store away a list of names and associated IDs
                   1601: 
                   1602: sub idput {
                   1603:     my ($udom,%ids)=@_;
                   1604:     my %servers=();
1.800     albertel 1605:     foreach my $uname (keys(%ids)) {
                   1606: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1607:         my $uhom=&homeserver($uname,$udom);
1.70      www      1608:         if ($uhom ne 'no_host') {
1.800     albertel 1609:             my $id=&escape($ids{$uname});
1.70      www      1610:             $id=~tr/A-Z/a-z/;
1.800     albertel 1611:             my $esc_unam=&escape($uname);
1.70      www      1612: 	    if ($servers{$uhom}) {
1.800     albertel 1613: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1614:             } else {
1.800     albertel 1615:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1616:             }
                   1617:         }
1.191     harris41 1618:     }
1.800     albertel 1619:     foreach my $server (keys(%servers)) {
                   1620:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1621:     }
1.344     www      1622: }
                   1623: 
1.1172.2.30  raeburn  1624: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1625: 
                   1626: sub iddel {
                   1627:     my ($udom,$idshashref,$uhome)=@_;
                   1628:     my %result=();
                   1629:     unless (ref($idshashref) eq 'HASH') {
                   1630:         return %result;
                   1631:     }
                   1632:     my %servers=();
                   1633:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1634:         my $uhom;
                   1635:         if ($uhome) {
                   1636:             $uhom = $uhome;
                   1637:         } else {
                   1638:             $uhom=&homeserver($uname,$udom);
                   1639:         }
                   1640:         if ($uhom ne 'no_host') {
                   1641:             if ($servers{$uhom}) {
                   1642:                 $servers{$uhom}.='&'.&escape($id);
                   1643:             } else {
                   1644:                 $servers{$uhom}=&escape($id);
                   1645:             }
                   1646:         }
                   1647:     }
                   1648:     foreach my $server (keys(%servers)) {
                   1649:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1650:     }
                   1651:     return %result;
                   1652: }
                   1653: 
1.1023    raeburn  1654: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1655: sub dump_dom {
1.1165    droeschl 1656:     my ($namespace, $udom, $regexp) = @_;
                   1657: 
                   1658:     $udom ||= $env{'user.domain'};
                   1659: 
                   1660:     return () unless $udom;
                   1661: 
                   1662:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1663: }
                   1664: 
1.1023    raeburn  1665: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1666: 
                   1667: sub get_dom {
1.860     raeburn  1668:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1669:     return if ($udom eq 'public');
1.806     raeburn  1670:     my $items='';
                   1671:     foreach my $item (@$storearr) {
                   1672:         $items.=&escape($item).'&';
                   1673:     }
                   1674:     $items=~s/\&$//;
1.860     raeburn  1675:     if (!$udom) {
                   1676:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1677:         return if ($udom eq 'public');
1.860     raeburn  1678:         if (defined(&domain($udom,'primary'))) {
                   1679:             $uhome=&domain($udom,'primary');
                   1680:         } else {
1.874     albertel 1681:             undef($uhome);
1.860     raeburn  1682:         }
                   1683:     } else {
                   1684:         if (!$uhome) {
                   1685:             if (defined(&domain($udom,'primary'))) {
                   1686:                 $uhome=&domain($udom,'primary');
                   1687:             }
                   1688:         }
                   1689:     }
                   1690:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1691:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1692:         my %returnhash;
1.875     albertel 1693:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1694:             return %returnhash;
                   1695:         }
1.806     raeburn  1696:         my @pairs=split(/\&/,$rep);
                   1697:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1698:             return @pairs;
                   1699:         }
                   1700:         my $i=0;
                   1701:         foreach my $item (@$storearr) {
                   1702:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1703:             $i++;
                   1704:         }
                   1705:         return %returnhash;
                   1706:     } else {
1.880     banghart 1707:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1708:     }
                   1709: }
                   1710: 
                   1711: # -------------------------------------------- put items in domain db files 
                   1712: 
                   1713: sub put_dom {
1.860     raeburn  1714:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1715:     if (!$udom) {
                   1716:         $udom=$env{'user.domain'};
                   1717:         if (defined(&domain($udom,'primary'))) {
                   1718:             $uhome=&domain($udom,'primary');
                   1719:         } else {
1.874     albertel 1720:             undef($uhome);
1.860     raeburn  1721:         }
                   1722:     } else {
                   1723:         if (!$uhome) {
                   1724:             if (defined(&domain($udom,'primary'))) {
                   1725:                 $uhome=&domain($udom,'primary');
                   1726:             }
                   1727:         }
                   1728:     } 
                   1729:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1730:         my $items='';
                   1731:         foreach my $item (keys(%$storehash)) {
                   1732:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1733:         }
                   1734:         $items=~s/\&$//;
                   1735:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1736:     } else {
1.860     raeburn  1737:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1738:     }
                   1739: }
                   1740: 
1.1023    raeburn  1741: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1742: sub newput_dom {
1.1023    raeburn  1743:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1744:     my $result;
                   1745:     if (!$udom) {
                   1746:         $udom=$env{'user.domain'};
                   1747:     }
1.1023    raeburn  1748:     if ($udom) {
                   1749:         my $uname = &get_domainconfiguser($udom);
                   1750:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1751:     }
                   1752:     return $result;
                   1753: }
                   1754: 
1.1023    raeburn  1755: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1756: sub del_dom {
1.1023    raeburn  1757:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1758:     if (ref($storearr) eq 'ARRAY') {
                   1759:         if (!$udom) {
                   1760:             $udom=$env{'user.domain'};
                   1761:         }
1.1023    raeburn  1762:         if ($udom) {
                   1763:             my $uname = &get_domainconfiguser($udom); 
                   1764:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1765:         }
                   1766:     }
                   1767: }
                   1768: 
1.1023    raeburn  1769: # ----------------------------------construct domainconfig user for a domain 
                   1770: sub get_domainconfiguser {
                   1771:     my ($udom) = @_;
                   1772:     return $udom.'-domainconfig';
                   1773: }
                   1774: 
1.837     raeburn  1775: sub retrieve_inst_usertypes {
                   1776:     my ($udom) = @_;
                   1777:     my (%returnhash,@order);
1.989     raeburn  1778:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1779:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1780:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1781:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1782:     } else {
                   1783:         if (defined(&domain($udom,'primary'))) {
                   1784:             my $uhome=&domain($udom,'primary');
                   1785:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1786:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1787:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1788:                 return (\%returnhash,\@order);
                   1789:             }
                   1790:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1791:             my @pairs=split(/\&/,$hashitems);
                   1792:             foreach my $item (@pairs) {
                   1793:                 my ($key,$value)=split(/=/,$item,2);
                   1794:                 $key = &unescape($key);
                   1795:                 next if ($key =~ /^error: 2 /);
                   1796:                 $returnhash{$key}=&thaw_unescape($value);
                   1797:             }
                   1798:             my @esc_order = split(/\&/,$orderitems);
                   1799:             foreach my $item (@esc_order) {
                   1800:                 push(@order,&unescape($item));
                   1801:             }
                   1802:         } else {
1.1172.2.44  raeburn  1803:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1804:         }
1.1172.2.44  raeburn  1805:         return (\%returnhash,\@order);
1.837     raeburn  1806:     }
                   1807: }
                   1808: 
1.868     raeburn  1809: sub is_domainimage {
                   1810:     my ($url) = @_;
1.1172.2.74  raeburn  1811:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1812:         if (&domain($1) ne '') {
                   1813:             return '1';
                   1814:         }
                   1815:     }
                   1816:     return;
                   1817: }
                   1818: 
1.899     raeburn  1819: sub inst_directory_query {
                   1820:     my ($srch) = @_;
                   1821:     my $udom = $srch->{'srchdomain'};
                   1822:     my %results;
                   1823:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1824:     my $outcome;
1.899     raeburn  1825:     if ($homeserver ne '') {
1.904     albertel 1826: 	my $queryid=&reply("querysend:instdirsearch:".
                   1827: 			   &escape($srch->{'srchby'}).':'.
                   1828: 			   &escape($srch->{'srchterm'}).':'.
                   1829: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1830: 	my $host=&hostname($homeserver);
                   1831: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.93.2  1(raebur 1832:7): 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 1833: 	    return;
                   1834: 	}
                   1835: 	my $response = &get_query_reply($queryid);
                   1836: 	my $maxtries = 5;
                   1837: 	my $tries = 1;
                   1838: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1839: 	    $response = &get_query_reply($queryid);
                   1840: 	    $tries ++;
                   1841: 	}
                   1842: 
                   1843:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1844:             if ($response eq 'unavailable') {
                   1845:                 $outcome = $response;
                   1846:             } else {
                   1847:                 $outcome = 'ok';
                   1848:                 my @matches = split(/\n/,$response);
                   1849:                 foreach my $match (@matches) {
                   1850:                     my ($key,$value) = split(/=/,$match);
                   1851:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1852:                 }
1.899     raeburn  1853:             }
                   1854:         }
                   1855:     }
1.909     raeburn  1856:     return ($outcome,%results);
1.899     raeburn  1857: }
                   1858: 
                   1859: sub usersearch {
                   1860:     my ($srch) = @_;
                   1861:     my $dom = $srch->{'srchdomain'};
                   1862:     my %results;
                   1863:     my %libserv = &all_library();
                   1864:     my $query = 'usersearch';
                   1865:     foreach my $tryserver (keys(%libserv)) {
                   1866:         if (&host_domain($tryserver) eq $dom) {
                   1867:             my $host=&hostname($tryserver);
                   1868:             my $queryid=
1.911     raeburn  1869:                 &reply("querysend:".&escape($query).':'.
                   1870:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1871:                        &escape($srch->{'srchtype'}).':'.
                   1872:                        &escape($srch->{'srchterm'}),$tryserver);
                   1873:             if ($queryid !~/^\Q$host\E\_/) {
                   1874:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1875:                 next;
1.899     raeburn  1876:             }
                   1877:             my $reply = &get_query_reply($queryid);
                   1878:             my $maxtries = 1;
                   1879:             my $tries = 1;
                   1880:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1881:                 $reply = &get_query_reply($queryid);
                   1882:                 $tries ++;
                   1883:             }
                   1884:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1885:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1886:             } else {
1.911     raeburn  1887:                 my @matches;
                   1888:                 if ($reply =~ /\n/) {
                   1889:                     @matches = split(/\n/,$reply);
                   1890:                 } else {
                   1891:                     @matches = split(/\&/,$reply);
                   1892:                 }
1.899     raeburn  1893:                 foreach my $match (@matches) {
                   1894:                     my ($uname,$udom,%userhash);
1.911     raeburn  1895:                     foreach my $entry (split(/:/,$match)) {
                   1896:                         my ($key,$value) =
                   1897:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1898:                         $userhash{$key} = $value;
                   1899:                         if ($key eq 'username') {
                   1900:                             $uname = $value;
                   1901:                         } elsif ($key eq 'domain') {
                   1902:                             $udom = $value;
1.911     raeburn  1903:                         }
1.899     raeburn  1904:                     }
                   1905:                     $results{$uname.':'.$udom} = \%userhash;
                   1906:                 }
                   1907:             }
                   1908:         }
                   1909:     }
                   1910:     return %results;
                   1911: }
                   1912: 
1.912     raeburn  1913: sub get_instuser {
                   1914:     my ($udom,$uname,$id) = @_;
                   1915:     my $homeserver = &domain($udom,'primary');
                   1916:     my ($outcome,%results);
                   1917:     if ($homeserver ne '') {
                   1918:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1919:                            &escape($id).':'.&escape($udom),$homeserver);
                   1920:         my $host=&hostname($homeserver);
                   1921:         if ($queryid !~/^\Q$host\E\_/) {
                   1922:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1923:             return;
                   1924:         }
                   1925:         my $response = &get_query_reply($queryid);
                   1926:         my $maxtries = 5;
                   1927:         my $tries = 1;
                   1928:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1929:             $response = &get_query_reply($queryid);
                   1930:             $tries ++;
                   1931:         }
                   1932:         if (!&error($response) && $response ne 'refused') {
                   1933:             if ($response eq 'unavailable') {
                   1934:                 $outcome = $response;
                   1935:             } else {
                   1936:                 $outcome = 'ok';
                   1937:                 my @matches = split(/\n/,$response);
                   1938:                 foreach my $match (@matches) {
                   1939:                     my ($key,$value) = split(/=/,$match);
                   1940:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1941:                 }
                   1942:             }
                   1943:         }
                   1944:     }
                   1945:     my %userinfo;
                   1946:     if (ref($results{$uname}) eq 'HASH') {
                   1947:         %userinfo = %{$results{$uname}};
                   1948:     } 
                   1949:     return ($outcome,%userinfo);
                   1950: }
                   1951: 
1.1172.2.69  raeburn  1952: sub get_multiple_instusers {
                   1953:     my ($udom,$users,$caller) = @_;
                   1954:     my ($outcome,$results);
                   1955:     if (ref($users) eq 'HASH') {
                   1956:         my $count = keys(%{$users});
                   1957:         my $requested = &freeze_escape($users);
                   1958:         my $homeserver = &domain($udom,'primary');
                   1959:         if ($homeserver ne '') {
                   1960:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   1961:             my $host=&hostname($homeserver);
                   1962:             if ($queryid !~/^\Q$host\E\_/) {
                   1963:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   1964:                          ' for host: '.$homeserver.'in domain '.$udom);
                   1965:                 return ($outcome,$results);
                   1966:             }
                   1967:             my $response = &get_query_reply($queryid);
                   1968:             my $maxtries = 5;
                   1969:             if ($count > 100) {
                   1970:                 $maxtries = 1+int($count/20);
                   1971:             }
                   1972:             my $tries = 1;
                   1973:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   1974:                 $response = &get_query_reply($queryid);
                   1975:                 $tries ++;
                   1976:             }
                   1977:             if ($response eq '') {
                   1978:                 $results = {};
                   1979:                 foreach my $key (keys(%{$users})) {
                   1980:                     my ($uname,$id);
                   1981:                     if ($caller eq 'id') {
                   1982:                         $id = $key;
                   1983:                     } else {
                   1984:                         $uname = $key;
                   1985:                     }
                   1986:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   1987:                     $outcome = $resp;
                   1988:                     if ($resp eq 'ok') {
                   1989:                         %{$results} = (%{$results}, %info);
                   1990:                     } else {
                   1991:                         last;
                   1992:                     }
                   1993:                 }
                   1994:             } elsif(!&error($response) && ($response ne 'refused')) {
                   1995:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   1996:                     $outcome = $response;
                   1997:                 } else {
                   1998:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   1999:                     if ($outcome eq 'ok') {
                   2000:                         $results = &thaw_unescape($userdata);
                   2001:                     }
                   2002:                 }
                   2003:             }
                   2004:         }
                   2005:     }
                   2006:     return ($outcome,$results);
                   2007: }
                   2008: 
1.912     raeburn  2009: sub inst_rulecheck {
1.923     raeburn  2010:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2011:     my %returnhash;
                   2012:     if ($udom ne '') {
                   2013:         if (ref($rules) eq 'ARRAY') {
                   2014:             @{$rules} = map {&escape($_);} (@{$rules});
                   2015:             my $rulestr = join(':',@{$rules});
                   2016:             my $homeserver=&domain($udom,'primary');
                   2017:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2018:                 my $response;
                   2019:                 if ($item eq 'username') {                
                   2020:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2021:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2022:                                               $homeserver));
1.923     raeburn  2023:                 } elsif ($item eq 'id') {
                   2024:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2025:                                               ':'.&escape($id).':'.$rulestr,
                   2026:                                               $homeserver));
1.945     raeburn  2027:                 } elsif ($item eq 'selfcreate') {
                   2028:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2029:                                                &escape($udom).':'.&escape($uname).
                   2030:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2031:                 }
1.912     raeburn  2032:                 if ($response ne 'refused') {
                   2033:                     my @pairs=split(/\&/,$response);
                   2034:                     foreach my $item (@pairs) {
                   2035:                         my ($key,$value)=split(/=/,$item,2);
                   2036:                         $key = &unescape($key);
                   2037:                         next if ($key =~ /^error: 2 /);
                   2038:                         $returnhash{$key}=&thaw_unescape($value);
                   2039:                     }
                   2040:                 }
                   2041:             }
                   2042:         }
                   2043:     }
                   2044:     return %returnhash;
                   2045: }
                   2046: 
                   2047: sub inst_userrules {
1.923     raeburn  2048:     my ($udom,$check) = @_;
1.912     raeburn  2049:     my (%ruleshash,@ruleorder);
                   2050:     if ($udom ne '') {
                   2051:         my $homeserver=&domain($udom,'primary');
                   2052:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2053:             my $response;
                   2054:             if ($check eq 'id') {
                   2055:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2056:                                  $homeserver);
1.943     raeburn  2057:             } elsif ($check eq 'email') {
                   2058:                 $response=&reply('instemailrules:'.&escape($udom),
                   2059:                                  $homeserver);
1.923     raeburn  2060:             } else {
                   2061:                 $response=&reply('instuserrules:'.&escape($udom),
                   2062:                                  $homeserver);
                   2063:             }
1.912     raeburn  2064:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2065:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2066:                 ($response ne 'no_such_host')) {
                   2067:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2068:                 my @pairs=split(/\&/,$hashitems);
                   2069:                 foreach my $item (@pairs) {
                   2070:                     my ($key,$value)=split(/=/,$item,2);
                   2071:                     $key = &unescape($key);
                   2072:                     next if ($key =~ /^error: 2 /);
                   2073:                     $ruleshash{$key}=&thaw_unescape($value);
                   2074:                 }
                   2075:                 my @esc_order = split(/\&/,$orderitems);
                   2076:                 foreach my $item (@esc_order) {
                   2077:                     push(@ruleorder,&unescape($item));
                   2078:                 }
                   2079:             }
                   2080:         }
                   2081:     }
                   2082:     return (\%ruleshash,\@ruleorder);
                   2083: }
                   2084: 
1.976     raeburn  2085: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2086: 
                   2087: sub get_domain_defaults {
1.1172.2.35  raeburn  2088:     my ($domain,$ignore_cache) = @_;
                   2089:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2090:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2091:     unless ($ignore_cache) {
                   2092:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2093:         if (defined($cached)) {
                   2094:             if (ref($result) eq 'HASH') {
                   2095:                 return %{$result};
                   2096:             }
1.943     raeburn  2097:         }
                   2098:     }
                   2099:     my %domdefaults;
                   2100:     my %domconfig =
1.989     raeburn  2101:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2102:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2103:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2104:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2105:                                   'coursecategories','autoenroll',
                   2106:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2107:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2108:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2109:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2110:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2111:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2112:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2113:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2114:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2115:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2116:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2117:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2118:     } else {
                   2119:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2120:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2121:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2122:     }
1.976     raeburn  2123:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2124:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2125:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2126:         } else {
                   2127:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2128:         }
1.1172.2.6  raeburn  2129:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2130:         foreach my $item (@usertools) {
                   2131:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2132:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2133:             }
                   2134:         }
1.1172.2.29  raeburn  2135:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2136:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2137:         }
1.976     raeburn  2138:     }
1.985     raeburn  2139:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2140:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2141:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2142:         }
                   2143:     }
1.1172.2.9  raeburn  2144:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2145:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2146:     }
1.989     raeburn  2147:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2148:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2149:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2150:         }
                   2151:     }
1.1047    raeburn  2152:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2153:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2154:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2155:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2156:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2157:         }
1.1172.2.41  raeburn  2158:         foreach my $type (@coursetypes) {
                   2159:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2160:                 unless ($type eq 'community') {
                   2161:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2162:                 }
                   2163:             }
                   2164:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2165:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2166:             }
1.1172.2.60  raeburn  2167:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2168:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2169:                     $domdefaults{$type.'postsubtimeout'} =
                   2170:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2171:                 }
                   2172:             }
1.1172.2.30  raeburn  2173:         }
1.1172.2.67  raeburn  2174:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2175:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2176:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2177:                 if (@clonecodes) {
                   2178:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2179:                 }
                   2180:             }
                   2181:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2182:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2183:         }
1.1047    raeburn  2184:     }
1.1073    raeburn  2185:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2186:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2187:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2188:         }
                   2189:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2190:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2191:         }
1.1172.2.62  raeburn  2192:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2193:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2194:         }
1.1073    raeburn  2195:     }
1.1172.2.41  raeburn  2196:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2197:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2198:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2199:                             'approval','limit');
                   2200:             foreach my $type (@coursetypes) {
                   2201:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2202:                     my @mgrdc = ();
                   2203:                     foreach my $item (@settings) {
                   2204:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2205:                             push(@mgrdc,$item);
                   2206:                         }
                   2207:                     }
                   2208:                     if (@mgrdc) {
                   2209:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2210:                     }
                   2211:                 }
                   2212:             }
                   2213:         }
                   2214:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2215:             foreach my $type (@coursetypes) {
                   2216:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2217:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2218:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2219:                     }
                   2220:                 }
                   2221:             }
                   2222:         }
                   2223:     }
1.1172.2.46  raeburn  2224:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2225:         $domdefaults{'catauth'} = 'std';
                   2226:         $domdefaults{'catunauth'} = 'std';
                   2227:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2228:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2229:         }
                   2230:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2231:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2232:         }
                   2233:     }
1.1172.2.76  raeburn  2234:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2235:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2236:     }
1.1172.2.89  raeburn  2237:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2238:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2239:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2240:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2241:         }
                   2242:     }
1.1172.2.23  raeburn  2243:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2244:     return %domdefaults;
                   2245: }
                   2246: 
1.344     www      2247: # --------------------------------------------------- Assign a key to a student
                   2248: 
                   2249: sub assign_access_key {
1.364     www      2250: #
                   2251: # a valid key looks like uname:udom#comments
                   2252: # comments are being appended
                   2253: #
1.498     www      2254:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2255:     $kdom=
1.620     albertel 2256:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2257:     $knum=
1.620     albertel 2258:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2259:     $cdom=
1.620     albertel 2260:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2261:     $cnum=
1.620     albertel 2262:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2263:     $udom=$env{'user.name'} unless (defined($udom));
                   2264:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2265:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2266:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2267:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2268:                                                   # assigned to this person
                   2269:                                                   # - this should not happen,
1.345     www      2270:                                                   # unless something went wrong
                   2271:                                                   # the first time around
                   2272: # ready to assign
1.364     www      2273:         $logentry=$1.'; '.$logentry;
1.496     www      2274:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2275:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2276: # key now belongs to user
1.346     www      2277: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2278:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2279:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2280:                 return 'ok';
                   2281:             } else {
                   2282:                 return 
                   2283:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2284: 	    }
                   2285:         } else {
                   2286:             return 'error: Could not assign key, try again later.';
                   2287:         }
1.364     www      2288:     } elsif (!$existing{$ckey}) {
1.345     www      2289: # the key does not exist
                   2290: 	return 'error: The key does not exist';
                   2291:     } else {
                   2292: # the key is somebody else's
                   2293: 	return 'error: The key is already in use';
                   2294:     }
1.344     www      2295: }
                   2296: 
1.364     www      2297: # ------------------------------------------ put an additional comment on a key
                   2298: 
                   2299: sub comment_access_key {
                   2300: #
                   2301: # a valid key looks like uname:udom#comments
                   2302: # comments are being appended
                   2303: #
                   2304:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2305:     $cdom=
1.620     albertel 2306:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2307:     $cnum=
1.620     albertel 2308:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2309:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2310:     if ($existing{$ckey}) {
                   2311:         $existing{$ckey}.='; '.$logentry;
                   2312: # ready to assign
1.367     www      2313:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2314:                                                  $cdom,$cnum) eq 'ok') {
                   2315: 	    return 'ok';
                   2316:         } else {
                   2317: 	    return 'error: Count not store comment.';
                   2318:         }
                   2319:     } else {
                   2320: # the key does not exist
                   2321: 	return 'error: The key does not exist';
                   2322:     }
                   2323: }
                   2324: 
1.344     www      2325: # ------------------------------------------------------ Generate a set of keys
                   2326: 
                   2327: sub generate_access_keys {
1.364     www      2328:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2329:     $cdom=
1.620     albertel 2330:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2331:     $cnum=
1.620     albertel 2332:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2333:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2334:     unless (($cdom) && ($cnum)) { return 0; }
                   2335:     if ($number>10000) { return 0; }
                   2336:     sleep(2); # make sure don't get same seed twice
                   2337:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2338:     my $total=0;
                   2339:     for (my $i=1;$i<=$number;$i++) {
                   2340:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2341:                   sprintf("%lx",int(100000*rand)).'-'.
                   2342:                   sprintf("%lx",int(100000*rand));
                   2343:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2344:        $newkey=~s/0/h/g; # and also 0 and O
                   2345:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2346:        if ($existing{$newkey}) {
                   2347:            $i--;
                   2348:        } else {
1.364     www      2349: 	  if (&put('accesskeys',
                   2350:               { $newkey => '# generated '.localtime().
1.620     albertel 2351:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2352:                            '; '.$logentry },
                   2353: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2354:               $total++;
                   2355: 	  }
                   2356:        }
                   2357:     }
1.620     albertel 2358:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2359:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2360:     return $total;
                   2361: }
                   2362: 
                   2363: # ------------------------------------------------------- Validate an accesskey
                   2364: 
                   2365: sub validate_access_key {
                   2366:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2367:     $cdom=
1.620     albertel 2368:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2369:     $cnum=
1.620     albertel 2370:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2371:     $udom=$env{'user.domain'} unless (defined($udom));
                   2372:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2373:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2374:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2375: }
                   2376: 
                   2377: # ------------------------------------- Find the section of student in a course
1.652     albertel 2378: sub devalidate_getsection_cache {
                   2379:     my ($udom,$unam,$courseid)=@_;
                   2380:     my $hashid="$udom:$unam:$courseid";
                   2381:     &devalidate_cache_new('getsection',$hashid);
                   2382: }
1.298     matthew  2383: 
1.815     albertel 2384: sub courseid_to_courseurl {
                   2385:     my ($courseid) = @_;
                   2386:     #already url style courseid
                   2387:     return $courseid if ($courseid =~ m{^/});
                   2388: 
                   2389:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2390: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2391: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2392: 	return "/$cdom/$cnum";
                   2393:     }
                   2394: 
                   2395:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2396:     if (exists($courseinfo{'num'})) {
                   2397: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2398:     }
                   2399: 
                   2400:     return undef;
                   2401: }
                   2402: 
1.298     matthew  2403: sub getsection {
                   2404:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2405:     my $cachetime=1800;
1.551     albertel 2406: 
                   2407:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2408:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2409:     if (defined($cached)) { return $result; }
                   2410: 
1.298     matthew  2411:     my %Pending; 
                   2412:     my %Expired;
                   2413:     #
                   2414:     # Each role can either have not started yet (pending), be active, 
                   2415:     #    or have expired.
                   2416:     #
                   2417:     # If there is an active role, we are done.
                   2418:     #
                   2419:     # If there is more than one role which has not started yet, 
                   2420:     #     choose the one which will start sooner
                   2421:     # If there is one role which has not started yet, return it.
                   2422:     #
                   2423:     # If there is more than one expired role, choose the one which ended last.
                   2424:     # If there is a role which has expired, return it.
                   2425:     #
1.815     albertel 2426:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2427:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2428:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2429:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2430:         my $section=$1;
                   2431:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2432:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2433:         my $now=time;
1.548     albertel 2434:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2435:             $Expired{$end}=$section;
                   2436:             next;
                   2437:         }
1.548     albertel 2438:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2439:             $Pending{$start}=$section;
                   2440:             next;
                   2441:         }
1.599     albertel 2442:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2443:     }
                   2444:     #
                   2445:     # Presumedly there will be few matching roles from the above
                   2446:     # loop and the sorting time will be negligible.
                   2447:     if (scalar(keys(%Pending))) {
                   2448:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2449:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2450:     } 
                   2451:     if (scalar(keys(%Expired))) {
                   2452:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2453:         my $time = pop(@sorted);
1.599     albertel 2454:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2455:     }
1.599     albertel 2456:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2457: }
1.70      www      2458: 
1.599     albertel 2459: sub save_cache {
                   2460:     &purge_remembered();
1.722     albertel 2461:     #&Apache::loncommon::validate_page();
1.620     albertel 2462:     undef(%env);
1.780     albertel 2463:     undef($env_loaded);
1.599     albertel 2464: }
1.452     albertel 2465: 
1.599     albertel 2466: my $to_remember=-1;
                   2467: my %remembered;
                   2468: my %accessed;
                   2469: my $kicks=0;
                   2470: my $hits=0;
1.849     albertel 2471: sub make_key {
                   2472:     my ($name,$id) = @_;
1.872     albertel 2473:     if (length($id) > 65 
                   2474: 	&& length(&escape($id)) > 200) {
                   2475: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2476:     }
1.849     albertel 2477:     return &escape($name.':'.$id);
                   2478: }
                   2479: 
1.599     albertel 2480: sub devalidate_cache_new {
                   2481:     my ($name,$id,$debug) = @_;
                   2482:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2483:     my $remembered_id=$name.':'.$id;
1.849     albertel 2484:     $id=&make_key($name,$id);
1.599     albertel 2485:     $memcache->delete($id);
1.1172.2.81  raeburn  2486:     delete($remembered{$remembered_id});
                   2487:     delete($accessed{$remembered_id});
1.599     albertel 2488: }
                   2489: 
                   2490: sub is_cached_new {
                   2491:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2492:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2493:                                      # keys in %remembered hash, which persists for
                   2494:                                      # duration of request (no restriction on key length).
                   2495:     if (exists($remembered{$remembered_id})) {
                   2496: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2497: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2498: 	$hits++;
1.1172.2.81  raeburn  2499: 	return ($remembered{$remembered_id},1);
1.599     albertel 2500:     }
1.1172.2.81  raeburn  2501:     $id=&make_key($name,$id);
1.599     albertel 2502:     my $value = $memcache->get($id);
                   2503:     if (!(defined($value))) {
                   2504: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2505: 	return (undef,undef);
1.416     albertel 2506:     }
1.599     albertel 2507:     if ($value eq '__undef__') {
                   2508: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2509: 	$value=undef;
                   2510:     }
1.1172.2.81  raeburn  2511:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2512:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2513:     return ($value,1);
                   2514: }
                   2515: 
                   2516: sub do_cache_new {
                   2517:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2518:     my $remembered_id=$name.':'.$id;
1.849     albertel 2519:     $id=&make_key($name,$id);
1.599     albertel 2520:     my $setvalue=$value;
                   2521:     if (!defined($setvalue)) {
                   2522: 	$setvalue='__undef__';
                   2523:     }
1.623     albertel 2524:     if (!defined($time) ) {
                   2525: 	$time=600;
                   2526:     }
1.599     albertel 2527:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2528:     my $result = $memcache->set($id,$setvalue,$time);
                   2529:     if (! $result) {
1.872     albertel 2530: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2531: 	$memcache->disconnect_all();
1.872     albertel 2532:     }
1.600     albertel 2533:     # need to make a copy of $value
1.1172.2.81  raeburn  2534:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2535:     return $value;
                   2536: }
                   2537: 
                   2538: sub make_room {
1.1172.2.81  raeburn  2539:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2540: 
1.1172.2.81  raeburn  2541:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2542:                                     : $value;
1.599     albertel 2543:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2544:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2545:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2546:     my $to_kick;
                   2547:     my $max_time=0;
                   2548:     foreach my $other (keys(%accessed)) {
                   2549: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2550: 	    $to_kick=$other;
                   2551: 	    $max_time=&tv_interval($accessed{$other});
                   2552: 	}
                   2553:     }
                   2554:     delete($remembered{$to_kick});
                   2555:     delete($accessed{$to_kick});
                   2556:     $kicks++;
                   2557:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2558:     return;
                   2559: }
                   2560: 
1.599     albertel 2561: sub purge_remembered {
1.604     albertel 2562:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2563:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2564:     undef(%remembered);
                   2565:     undef(%accessed);
1.428     albertel 2566: }
1.70      www      2567: # ------------------------------------- Read an entry from a user's environment
                   2568: 
                   2569: sub userenvironment {
                   2570:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2571:     my $items;
                   2572:     foreach my $item (@what) {
                   2573:         $items.=&escape($item).'&';
                   2574:     }
                   2575:     $items=~s/\&$//;
1.70      www      2576:     my %returnhash=();
1.1009    raeburn  2577:     my $uhome = &homeserver($unam,$udom);
                   2578:     unless ($uhome eq 'no_host') {
                   2579:         my @answer=split(/\&/, 
                   2580:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2581:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2582:             return %returnhash;
                   2583:         }
1.1009    raeburn  2584:         my $i;
                   2585:         for ($i=0;$i<=$#what;$i++) {
                   2586: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2587:         }
1.70      www      2588:     }
                   2589:     return %returnhash;
1.1       albertel 2590: }
                   2591: 
1.617     albertel 2592: # ---------------------------------------------------------- Get a studentphoto
                   2593: sub studentphoto {
                   2594:     my ($udom,$unam,$ext) = @_;
                   2595:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2596:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2597:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2598:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2599:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2600:             } else {
                   2601:                 my ($result,$perm_reqd)=
1.707     albertel 2602: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2603:                 if ($result eq 'ok') {
                   2604:                     if (!($perm_reqd eq 'yes')) {
                   2605:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2606:                     }
                   2607:                 }
                   2608:             }
                   2609:         }
                   2610:     } else {
                   2611:         my ($result,$perm_reqd) = 
1.707     albertel 2612: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2613:         if ($result eq 'ok') {
                   2614:             if (!($perm_reqd eq 'yes')) {
                   2615:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2616:             }
                   2617:         }
                   2618:     }
                   2619:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2620: }
                   2621: 
                   2622: sub retrievestudentphoto {
                   2623:     my ($udom,$unam,$ext,$type) = @_;
                   2624:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2625:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2626:     if ($ret eq 'ok') {
                   2627:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2628:         if ($type eq 'thumbnail') {
                   2629:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2630:         }
                   2631:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2632:         return $tokenurl;
                   2633:     } else {
                   2634:         if ($type eq 'thumbnail') {
                   2635:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2636:         } else { 
                   2637:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2638:         }
1.617     albertel 2639:     }
                   2640: }
                   2641: 
1.263     www      2642: # -------------------------------------------------------------------- New chat
                   2643: 
                   2644: sub chatsend {
1.724     raeburn  2645:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2646:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2647:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2648:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2649:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2650: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2651: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2652: }
                   2653: 
                   2654: # ------------------------------------------ Find current version of a resource
                   2655: 
                   2656: sub getversion {
                   2657:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2658:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2659:     return &currentversion(&filelocation('',$fname));
                   2660: }
                   2661: 
                   2662: sub currentversion {
                   2663:     my $fname=shift;
                   2664:     my $author=$fname;
                   2665:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2666:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2667:     my $home=&homeserver($uname,$udom);
1.292     www      2668:     if ($home eq 'no_host') { 
                   2669:         return -1; 
                   2670:     }
1.1112    www      2671:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2672:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2673: 	return -1;
                   2674:     }
1.1112    www      2675:     return $answer;
1.263     www      2676: }
                   2677: 
1.1111    www      2678: #
                   2679: # Return special version number of resource if set by override, empty otherwise
                   2680: #
                   2681: sub usedversion {
                   2682:     my $fname=shift;
                   2683:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2684:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2685:     if ($urlversion) { return $urlversion; }
                   2686:     return '';
                   2687: }
                   2688: 
1.1       albertel 2689: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2690: 
1.1       albertel 2691: sub subscribe {
                   2692:     my $fname=shift;
1.761     raeburn  2693:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2694:     $fname=~s/[\n\r]//g;
1.1       albertel 2695:     my $author=$fname;
                   2696:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2697:     my ($udom,$uname)=split(/\//,$author);
                   2698:     my $home=homeserver($uname,$udom);
1.335     albertel 2699:     if ($home eq 'no_host') {
                   2700:         return 'not_found';
1.1       albertel 2701:     }
                   2702:     my $answer=reply("sub:$fname",$home);
1.64      www      2703:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2704: 	$answer.=' by '.$home;
                   2705:     }
1.1       albertel 2706:     return $answer;
                   2707: }
                   2708:     
1.8       www      2709: # -------------------------------------------------------------- Replicate file
                   2710: 
                   2711: sub repcopy {
                   2712:     my $filename=shift;
1.23      www      2713:     $filename=~s/\/+/\//g;
1.1142    raeburn  2714:     my $londocroot = $perlvar{'lonDocRoot'};
                   2715:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2716:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2717:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2718: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2719: 	return &repcopy_userfile($filename);
                   2720:     }
1.532     albertel 2721:     $filename=~s/[\n\r]//g;
1.8       www      2722:     my $transname="$filename.in.transfer";
1.828     www      2723: # FIXME: this should flock
1.607     raeburn  2724:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2725:     my $remoteurl=subscribe($filename);
1.64      www      2726:     if ($remoteurl =~ /^con_lost by/) {
                   2727: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2728:            return 'unavailable';
1.8       www      2729:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2730: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2731: 	   return 'not_found';
1.64      www      2732:     } elsif ($remoteurl =~ /^rejected by/) {
                   2733: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2734:            return 'forbidden';
1.20      www      2735:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2736:            return 'ok';
1.8       www      2737:     } else {
1.290     www      2738:         my $author=$filename;
                   2739:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2740:         my ($udom,$uname)=split(/\//,$author);
                   2741:         my $home=homeserver($uname,$udom);
                   2742:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2743:            my @parts=split(/\//,$filename);
                   2744:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2745:            if ($path ne "$londocroot/res") {
1.8       www      2746:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2747: 	       return 'bad_request';
1.8       www      2748:            }
                   2749:            my $count;
                   2750:            for ($count=5;$count<$#parts;$count++) {
                   2751:                $path.="/$parts[$count]";
                   2752:                if ((-e $path)!=1) {
                   2753: 		   mkdir($path,0777);
                   2754:                }
                   2755:            }
                   2756:            my $ua=new LWP::UserAgent;
                   2757:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2758:            my $response=$ua->request($request,$transname);
                   2759:            if ($response->is_error()) {
                   2760: 	       unlink($transname);
                   2761:                my $message=$response->status_line;
1.672     albertel 2762:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2763:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2764:                return 'unavailable';
1.8       www      2765:            } else {
1.16      www      2766: 	       if ($remoteurl!~/\.meta$/) {
                   2767:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2768:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2769:                   if ($mresponse->is_error()) {
                   2770: 		      unlink($filename.'.meta');
                   2771:                       &logthis(
1.672     albertel 2772:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2773:                   }
                   2774: 	       }
1.8       www      2775:                rename($transname,$filename);
1.607     raeburn  2776:                return 'ok';
1.8       www      2777:            }
1.290     www      2778:        }
1.8       www      2779:     }
1.330     www      2780: }
                   2781: 
                   2782: # ------------------------------------------------ Get server side include body
                   2783: sub ssi_body {
1.381     albertel 2784:     my ($filelink,%form)=@_;
1.606     matthew  2785:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2786:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2787:     }
1.953     www      2788:     my $output='';
                   2789:     my $response;
1.980     raeburn  2790:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2791:        ($output,$response)=&externalssi($filelink);
1.953     www      2792:     } else {
1.1004    droeschl 2793:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2794:        $filelink .= 'inhibitmenu=yes';
1.953     www      2795:        ($output,$response)=&ssi($filelink,%form);
                   2796:     }
1.778     albertel 2797:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2798:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2799:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2800:     if (wantarray) {
                   2801:         return ($output, $response);
                   2802:     } else {
                   2803:         return $output;
                   2804:     }
1.8       www      2805: }
                   2806: 
1.15      www      2807: # --------------------------------------------------------- Server Side Include
                   2808: 
1.782     albertel 2809: sub absolute_url {
                   2810:     my ($host_name) = @_;
                   2811:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2812:     if ($host_name eq '') {
                   2813: 	$host_name = $ENV{'SERVER_NAME'};
                   2814:     }
                   2815:     return $protocol.$host_name;
                   2816: }
                   2817: 
1.942     foxr     2818: #
                   2819: #   Server side include.
                   2820: # Parameters:
                   2821: #  fn     Possibly encrypted resource name/id.
                   2822: #  form   Hash that describes how the rendering should be done
                   2823: #         and other things.
1.944     foxr     2824: # Returns:
1.950     raeburn  2825: #   Scalar context: The content of the response.
                   2826: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2827: #     
1.15      www      2828: sub ssi {
                   2829: 
1.944     foxr     2830:     my ($fn,%form)=@_;
1.15      www      2831:     my $ua=new LWP::UserAgent;
1.23      www      2832:     my $request;
1.711     albertel 2833: 
                   2834:     $form{'no_update_last_known'}=1;
1.895     albertel 2835:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2836:     if (%form) {
1.782     albertel 2837:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  2838:       $request->content(join('&',map {
                   2839:             my $name = escape($_);
                   2840:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   2841:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   2842:             : &escape($form{$_}) );
                   2843:         } keys(%form)));
1.23      www      2844:     } else {
1.782     albertel 2845:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2846:     }
                   2847: 
1.15      www      2848:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2849:     my $response= $ua->request($request);
1.944     foxr     2850:     if (wantarray) {
1.1172.2.3  raeburn  2851: 	return ($response->content, $response);
1.944     foxr     2852:     } else {
1.1172.2.3  raeburn  2853: 	return $response->content;
1.942     foxr     2854:     }
1.324     www      2855: }
                   2856: 
                   2857: sub externalssi {
                   2858:     my ($url)=@_;
                   2859:     my $ua=new LWP::UserAgent;
                   2860:     my $request=new HTTP::Request('GET',$url);
                   2861:     my $response=$ua->request($request);
1.954     raeburn  2862:     if (wantarray) {
                   2863:         return ($response->content, $response);
                   2864:     } else {
                   2865:         return $response->content;
                   2866:     }
1.15      www      2867: }
1.254     www      2868: 
1.492     albertel 2869: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2870: 
                   2871: sub allowuploaded {
                   2872:     my ($srcurl,$url)=@_;
                   2873:     $url=&clutter(&declutter($url));
                   2874:     my $dir=$url;
                   2875:     $dir=~s/\/[^\/]+$//;
                   2876:     my %httpref=();
                   2877:     my $httpurl=&hreflocation('',$url);
                   2878:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2879:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2880: }
1.477     raeburn  2881: 
1.1172.2.13  raeburn  2882: #
                   2883: # Determine if the current user should be able to edit a particular resource,
                   2884: # when viewing in course context.
                   2885: # (a) When viewing resource used to determine if "Edit" item is included in
                   2886: #     Functions.
                   2887: # (b) When displaying folder contents in course editor, used to determine if
                   2888: #     "Edit" link will be displayed alongside resource.
                   2889: #
                   2890: #  input: six args -- filename (decluttered), course number, course domain,
                   2891: #                   url, symb (if registered) and group (if this is a group
                   2892: #                   item -- e.g., bulletin board, group page etc.).
                   2893: #  output: array of five scalars --
                   2894: #          $cfile -- url for file editing if editable on current server
                   2895: #          $home -- homeserver of resource (i.e., for author if published,
                   2896: #                                           or course if uploaded.).
                   2897: #          $switchserver --  1 if server switch will be needed.
                   2898: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   2899: #          $forceview -- 1 if icon/link should be to go to view mode
                   2900: #
                   2901: 
                   2902: sub can_edit_resource {
                   2903:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2904:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2905: #
                   2906: # For aboutme pages user can only edit his/her own.
                   2907: #
                   2908:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   2909:         my ($sdom,$sname) = ($1,$2);
                   2910:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2911:             $home = $env{'user.home'};
                   2912:             $cfile = $resurl;
                   2913:             if ($env{'form.forceedit'}) {
                   2914:                 $forceview = 1;
                   2915:             } else {
                   2916:                 $forceedit = 1;
                   2917:             }
                   2918:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2919:         } else {
                   2920:             return;
                   2921:         }
                   2922:     }
                   2923: 
                   2924:     if ($env{'request.course.id'}) {
                   2925:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2926:         if ($group ne '') {
                   2927: # if this is a group homepage or group bulletin board, check group privs
                   2928:             my $allowed = 0;
                   2929:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2930:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   2931:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2932:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2933:                     $allowed = 1;
                   2934:                 }
                   2935:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2936:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2937:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2938:                     $allowed = 1;
                   2939:                 }
                   2940:             }
                   2941:             if ($allowed) {
                   2942:                 $home=&homeserver($cnum,$cdom);
                   2943:                 if ($env{'form.forceedit'}) {
                   2944:                     $forceview = 1;
                   2945:                 } else {
                   2946:                     $forceedit = 1;
                   2947:                 }
                   2948:                 $cfile = $resurl;
                   2949:             } else {
                   2950:                 return;
                   2951:             }
                   2952:         } else {
1.1172.2.15  raeburn  2953:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2954:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2955:                     return;
                   2956:                 }
                   2957:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  2958: #
                   2959: # No edit allowed where CC has switched to student role.
                   2960: #
                   2961:                 return;
                   2962:             }
                   2963:         }
                   2964:     }
                   2965: 
                   2966:     if ($file ne '') {
                   2967:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   2968:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2969:                 $uploaded = 1;
                   2970:                 $incourse = 1;
                   2971:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2972:                     $cfile = &hreflocation('',$file);
                   2973:                     if ($env{'form.forceedit'}) {
                   2974:                         $forceview = 1;
                   2975:                     } else {
                   2976:                         $forceedit = 1;
                   2977:                     }
                   2978:                 }
                   2979:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2980:                 $incourse = 1;
                   2981:                 if ($env{'form.forceedit'}) {
                   2982:                     $forceview = 1;
                   2983:                 } else {
                   2984:                     $forceedit = 1;
                   2985:                 }
                   2986:                 $cfile = $resurl;
                   2987:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   2988:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2989:                     $incourse = 1;
                   2990:                     if ($env{'form.forceedit'}) {
                   2991:                         $forceview = 1;
                   2992:                     } else {
                   2993:                         $forceedit = 1;
                   2994:                     }
                   2995:                     $cfile = $resurl;
                   2996:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   2997:                     $incourse = 1;
                   2998:                     $cfile = $resurl.'/smpedit';
                   2999:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3000:                     $incourse = 1;
                   3001:                     if ($env{'form.forceedit'}) {
                   3002:                         $forceview = 1;
                   3003:                     } else {
                   3004:                         $forceedit = 1;
                   3005:                     }
                   3006:                     $cfile = $resurl;
1.1172.2.15  raeburn  3007:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3008:                     $incourse = 1;
                   3009:                     if ($env{'form.forceedit'}) {
                   3010:                         $forceview = 1;
                   3011:                     } else {
                   3012:                         $forceedit = 1;
                   3013:                     }
                   3014:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3015:                 }
                   3016:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3017:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3018:                 if (&is_on_map($template)) {
                   3019:                     $incourse = 1;
                   3020:                     $forceview = 1;
                   3021:                     $cfile = $template;
                   3022:                 }
                   3023:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3024:                     $incourse = 1;
                   3025:                     if ($env{'form.forceedit'}) {
                   3026:                         $forceview = 1;
                   3027:                     } else {
                   3028:                         $forceedit = 1;
                   3029:                     }
                   3030:                     $cfile = $resurl;
                   3031:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3032:                 $incourse = 1;
                   3033:                 $forceview = 1;
                   3034:                 if ($symb) {
                   3035:                     my ($map,$id,$res)=&decode_symb($symb);
                   3036:                     $env{'request.symb'} = $symb;
                   3037:                     $cfile = &clutter($res);
                   3038:                 } else {
                   3039:                     $cfile = $env{'form.suppurl'};
1.1172.2.93.2  1(raebur 3040:7):                     my $escfile = &unescape($cfile);
                   3041:7):                     $escfile =~ s{^http://}{};
                   3042:7):                     $cfile = &escape("/adm/wrapper/ext/$escfile");
1.1172.2.13  raeburn  3043:                 }
1.1172.2.31  raeburn  3044:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3045:                 if ($env{'form.forceedit'}) {
                   3046:                     $forceview = 1;
                   3047:                 } else {
                   3048:                     $forceedit = 1;
                   3049:                 }
                   3050:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3051:             }
                   3052:         }
                   3053:         if ($uploaded || $incourse) {
                   3054:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3055:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3056:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3057:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3058:             # Check that the user has permission to edit this resource
                   3059:             my $setpriv = 1;
                   3060:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3061:             if (defined($cfudom)) {
                   3062:                 $home=&homeserver($cfuname,$cfudom);
                   3063:                 $cfile=$file;
                   3064:             }
                   3065:         }
                   3066:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3067:             (($home ne '') && ($home ne 'no_host'))) {
                   3068:             my @ids=&current_machine_ids();
                   3069:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3070:                 $switchserver=1;
                   3071:             }
                   3072:         }
                   3073:     }
                   3074:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3075: }
                   3076: 
                   3077: sub is_course_upload {
                   3078:     my ($file,$cnum,$cdom) = @_;
                   3079:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3080:     $uploadpath =~ s{^\/}{};
                   3081:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3082:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3083:         return 1;
                   3084:     }
                   3085:     return;
                   3086: }
                   3087: 
                   3088: sub in_course {
                   3089:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3090:     if ($hideprivileged) {
                   3091:         my $skipuser;
1.1172.2.23  raeburn  3092:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3093:         my @possdoms = ($cdom);
                   3094:         if ($coursehash{'checkforpriv'}) {
                   3095:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3096:         }
                   3097:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3098:             $skipuser = 1;
                   3099:             if ($coursehash{'nothideprivileged'}) {
                   3100:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3101:                     my $user;
                   3102:                     if ($item =~ /:/) {
                   3103:                         $user = $item;
                   3104:                     } else {
                   3105:                         $user = join(':',split(/[\@]/,$item));
                   3106:                     }
                   3107:                     if ($user eq $uname.':'.$udom) {
                   3108:                         undef($skipuser);
                   3109:                         last;
                   3110:                     }
                   3111:                 }
                   3112:             }
                   3113:             if ($skipuser) {
                   3114:                 return 0;
                   3115:             }
                   3116:         }
                   3117:     }
                   3118:     $type ||= 'any';
                   3119:     if (!defined($cdom) || !defined($cnum)) {
                   3120:         my $cid  = $env{'request.course.id'};
                   3121:         $cdom = $env{'course.'.$cid.'.domain'};
                   3122:         $cnum = $env{'course.'.$cid.'.num'};
                   3123:     }
                   3124:     my $typesref;
                   3125:     if (($type eq 'any') || ($type eq 'all')) {
                   3126:         $typesref = ['active','previous','future'];
                   3127:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3128:         $typesref = [$type];
                   3129:     }
                   3130:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3131:                               $typesref,undef,[$cdom]);
                   3132:     my ($tmp) = keys(%roles);
                   3133:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3134:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3135:     if (@course_roles > 0) {
                   3136:         return 1;
                   3137:     }
                   3138:     return 0;
                   3139: }
                   3140: 
1.478     albertel 3141: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3142: # input: action, courseID, current domain, intended
1.637     raeburn  3143: #        path to file, source of file, instruction to parse file for objects,
                   3144: #        ref to hash for embedded objects,
                   3145: #        ref to hash for codebase of java objects.
1.1095    raeburn  3146: #        reference to scalar to accommodate mime type determined
                   3147: #          from File::MMagic if $parser = parse.
1.637     raeburn  3148: #
1.485     raeburn  3149: # output: url to file (if action was uploaddoc), 
                   3150: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3151: #
1.478     albertel 3152: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3153: # course.
1.477     raeburn  3154: #
1.478     albertel 3155: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3156: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3157: #          course's home server.
1.477     raeburn  3158: #
1.478     albertel 3159: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3160: #          be copied from $source (current location) to 
                   3161: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3162: #         and will then be copied to
                   3163: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3164: #         course's home server.
1.485     raeburn  3165: #
1.481     raeburn  3166: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3167: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3168: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3169: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3170: #         in course's home server.
1.637     raeburn  3171: #
1.477     raeburn  3172: 
                   3173: sub process_coursefile {
1.1095    raeburn  3174:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3175:         $mimetype)=@_;
1.477     raeburn  3176:     my $fetchresult;
1.638     albertel 3177:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3178:     if ($action eq 'propagate') {
1.638     albertel 3179:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3180: 			     $home);
1.481     raeburn  3181:     } else {
1.477     raeburn  3182:         my $fpath = '';
                   3183:         my $fname = $file;
1.478     albertel 3184:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3185:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3186:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3187:         if ($action eq 'copy') {
                   3188:             if ($source eq '') {
                   3189:                 $fetchresult = 'no source file';
                   3190:                 return $fetchresult;
                   3191:             } else {
                   3192:                 my $destination = $filepath.'/'.$fname;
                   3193:                 rename($source,$destination);
                   3194:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3195:                                  $home);
1.481     raeburn  3196:             }
                   3197:         } elsif ($action eq 'uploaddoc') {
                   3198:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3199:             print $fh $env{'form.'.$source};
1.481     raeburn  3200:             close($fh);
1.637     raeburn  3201:             if ($parser eq 'parse') {
1.1024    raeburn  3202:                 my $mm = new File::MMagic;
1.1095    raeburn  3203:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3204:                 if ($type eq 'text/html') {
1.1024    raeburn  3205:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3206:                     unless ($parse_result eq 'ok') {
                   3207:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3208:                     }
1.637     raeburn  3209:                 }
1.1095    raeburn  3210:                 if (ref($mimetype)) {
                   3211:                     $$mimetype = $type;
                   3212:                 } 
1.637     raeburn  3213:             }
1.477     raeburn  3214:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3215:                                  $home);
1.481     raeburn  3216:             if ($fetchresult eq 'ok') {
                   3217:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3218:             } else {
                   3219:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3220:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3221:                 return '/adm/notfound.html';
                   3222:             }
1.477     raeburn  3223:         }
                   3224:     }
1.485     raeburn  3225:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3226:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3227:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3228:     }
                   3229:     return $fetchresult;
                   3230: }
                   3231: 
1.637     raeburn  3232: sub build_filepath {
                   3233:     my ($fpath) = @_;
                   3234:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3235:     unless ($fpath eq '') {
                   3236:         my @parts=split('/',$fpath);
                   3237:         foreach my $part (@parts) {
                   3238:             $filepath.= '/'.$part;
                   3239:             if ((-e $filepath)!=1) {
                   3240:                 mkdir($filepath,0777);
                   3241:             }
                   3242:         }
                   3243:     }
                   3244:     return $filepath;
                   3245: }
                   3246: 
                   3247: sub store_edited_file {
1.638     albertel 3248:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3249:     my $file = $primary_url;
                   3250:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3251:     my $fpath = '';
                   3252:     my $fname = $file;
                   3253:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3254:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3255:     my $filepath = &build_filepath($fpath);
                   3256:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3257:     print $fh $content;
                   3258:     close($fh);
1.638     albertel 3259:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3260:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3261: 			  $home);
1.637     raeburn  3262:     if ($$fetchresult eq 'ok') {
                   3263:         return '/uploaded/'.$fpath.'/'.$fname;
                   3264:     } else {
1.638     albertel 3265:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3266: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3267:         return '/adm/notfound.html';
                   3268:     }
                   3269: }
                   3270: 
1.531     albertel 3271: sub clean_filename {
1.831     albertel 3272:     my ($fname,$args)=@_;
1.315     www      3273: # Replace Windows backslashes by forward slashes
1.257     www      3274:     $fname=~s/\\/\//g;
1.831     albertel 3275:     if (!$args->{'keep_path'}) {
                   3276:         # Get rid of everything but the actual filename
                   3277: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3278:     }
1.315     www      3279: # Replace spaces by underscores
                   3280:     $fname=~s/\s+/\_/g;
                   3281: # Replace all other weird characters by nothing
1.831     albertel 3282:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3283: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3284: # numbers
                   3285:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3286:     return $fname;
                   3287: }
1.1051    raeburn  3288: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3289: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3290: # image with the same aspect ratio as the original, but with dimensions which do 
                   3291: # not exceed $resizewidth and $resizeheight.
                   3292:  
1.984     neumanie 3293: sub resizeImage {
1.1051    raeburn  3294:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3295:     my $ima = Image::Magick->new;
                   3296:     my $resized;
                   3297:     if (-e $img_path) {
                   3298:         $ima->Read($img_path);
                   3299:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3300:             my $width = $ima->Get('width');
                   3301:             my $height = $ima->Get('height');
                   3302:             if ($width > $resizewidth) {
                   3303: 	        my $factor = $width/$resizewidth;
                   3304:                 my $newheight = $height/$factor;
                   3305:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3306:                 $resized = 1;
                   3307:             }
                   3308:         }
                   3309:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3310:             my $width = $ima->Get('width');
                   3311:             my $height = $ima->Get('height');
                   3312:             if ($height > $resizeheight) {
                   3313:                 my $factor = $height/$resizeheight;
                   3314:                 my $newwidth = $width/$factor;
                   3315:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3316:                 $resized = 1;
                   3317:             }
                   3318:         }
                   3319:         if ($resized) {
                   3320:             $ima->Write($img_path);
                   3321:         }
                   3322:     }
                   3323:     return;
1.977     amueller 3324: }
                   3325: 
1.608     albertel 3326: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3327: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3328: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3329: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3330: #                                    canceloverwrite, or ''. 
                   3331: #                   if 'coursedoc': upload to the current course
                   3332: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3333: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3334: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3335: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3336: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3337: #        $allfiles - reference to hash for embedded objects
                   3338: #        $codebase - reference to hash for codebase of java objects
                   3339: #        $desuname - username for permanent storage of uploaded file
                   3340: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3341: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3342: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3343: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3344: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3345: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3346: #                    from File::MMagic.
1.858     raeburn  3347: # 
1.686     albertel 3348: # output: url of file in userspace, or error: <message> 
                   3349: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3350: 
1.531     albertel 3351: sub userfileupload {
1.1090    raeburn  3352:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3353:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3354:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3355:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3356:     $fname=&clean_filename($fname);
1.1090    raeburn  3357:     # See if there is anything left
1.257     www      3358:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3359:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3360:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3361:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3362:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3363:         my $now = time;
1.1090    raeburn  3364:         my $filepath;
1.1095    raeburn  3365:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3366:              $filepath = 'tmp/helprequests/'.$now;
                   3367:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3368:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3369:                          '_'.$env{'user.domain'}.'/pending';
                   3370:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3371:             my ($docuname,$docudom);
                   3372:             if ($destudom) {
                   3373:                 $docudom = $destudom;
                   3374:             } else {
                   3375:                 $docudom = $env{'user.domain'};
                   3376:             }
                   3377:             if ($destuname) {
                   3378:                 $docuname = $destuname;
                   3379:             } else {
                   3380:                 $docuname = $env{'user.name'};
                   3381:             }
                   3382:             if (exists($env{'form.group'})) {
                   3383:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3384:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3385:             }
                   3386:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3387:             if ($context eq 'canceloverwrite') {
                   3388:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3389:                 if (-e  $tempfile) {
                   3390:                     my @info = stat($tempfile);
                   3391:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3392:                         unlink($tempfile);
                   3393:                     }
                   3394:                 }
                   3395:                 return;
1.523     raeburn  3396:             }
                   3397:         }
1.1090    raeburn  3398:         # Create the directory if not present
1.741     raeburn  3399:         my @parts=split(/\//,$filepath);
                   3400:         my $fullpath = $perlvar{'lonDaemons'};
                   3401:         for (my $i=0;$i<@parts;$i++) {
                   3402:             $fullpath .= '/'.$parts[$i];
                   3403:             if ((-e $fullpath)!=1) {
                   3404:                 mkdir($fullpath,0777);
                   3405:             }
                   3406:         }
                   3407:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3408:         print $fh $env{'form.'.$formname};
                   3409:         close($fh);
1.1090    raeburn  3410:         if ($context eq 'existingfile') {
                   3411:             my @info = stat($fullpath.'/'.$fname);
                   3412:             return ($fullpath.'/'.$fname,$info[9]);
                   3413:         } else {
                   3414:             return $fullpath.'/'.$fname;
                   3415:         }
1.523     raeburn  3416:     }
1.995     raeburn  3417:     if ($subdir eq 'scantron') {
                   3418:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3419:     } else {
1.995     raeburn  3420:         $fname="$subdir/$fname";
                   3421:     }
1.1090    raeburn  3422:     if ($context eq 'coursedoc') {
1.638     albertel 3423: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3424: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3425:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3426:             return &finishuserfileupload($docuname,$docudom,
                   3427: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3428: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3429:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3430:         } else {
1.1172.2.21  raeburn  3431:             if ($env{'form.folder'}) {
                   3432:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3433:             }
1.638     albertel 3434:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3435: 				       $fname,$formname,$parser,
1.1095    raeburn  3436: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3437:         }
1.719     banghart 3438:     } elsif (defined($destuname)) {
                   3439:         my $docuname=$destuname;
                   3440:         my $docudom=$destudom;
1.860     raeburn  3441: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3442: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3443:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3444:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3445:     } else {
1.638     albertel 3446:         my $docuname=$env{'user.name'};
                   3447:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3448:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3449:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3450:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3451:         }
1.860     raeburn  3452: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3453: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3454:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3455:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3456:     }
1.271     www      3457: }
                   3458: 
                   3459: sub finishuserfileupload {
1.860     raeburn  3460:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3461:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3462:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3463:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3464:   
1.860     raeburn  3465:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3466:     $file=$fname;
                   3467:     if ($fname=~m|/|) {
                   3468:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3469: 	$path.=$fnamepath.'/';
                   3470:     }
1.259     www      3471:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3472:     my $count;
                   3473:     for ($count=4;$count<=$#parts;$count++) {
                   3474:         $filepath.="/$parts[$count]";
                   3475:         if ((-e $filepath)!=1) {
                   3476: 	    mkdir($filepath,0777);
                   3477:         }
                   3478:     }
1.984     neumanie 3479: 
1.258     www      3480: # Save the file
                   3481:     {
1.701     albertel 3482: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3483: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3484: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3485: 	    return '/adm/notfound.html';
                   3486: 	}
1.1090    raeburn  3487:         if ($context eq 'overwrite') {
1.1117    foxr     3488:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3489:             my $target = $filepath.'/'.$file;
                   3490:             if (-e $source) {
                   3491:                 my @info = stat($source);
                   3492:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3493:                     unless (&File::Copy::move($source,$target)) {
                   3494:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3495:                         return "Moving from $source failed";
                   3496:                     }
                   3497:                 } else {
                   3498:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3499:                 }
                   3500:             } else {
                   3501:                 return "Temporary file: $source missing";
                   3502:             }
                   3503:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3504: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3505: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3506: 	    return '/adm/notfound.html';
                   3507: 	}
1.570     albertel 3508: 	close(FH);
1.1051    raeburn  3509:         if ($resizewidth && $resizeheight) {
                   3510:             my $mm = new File::MMagic;
                   3511:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3512:             if ($mime_type =~ m{^image/}) {
                   3513: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3514:             }  
1.977     amueller 3515: 	}
1.258     www      3516:     }
1.1152    raeburn  3517:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3518:         if (ref($mimetype)) {
                   3519:             if ($$mimetype eq '') {
                   3520:                 my $mm = new File::MMagic;
                   3521:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3522:                 $$mimetype = $type;
                   3523:             }
                   3524:         }
                   3525:     }
1.637     raeburn  3526:     if ($parser eq 'parse') {
1.1152    raeburn  3527:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3528:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3529:                                                        $allfiles,$codebase);
                   3530:             unless ($parse_result eq 'ok') {
                   3531:                 &logthis('Failed to parse '.$filepath.$file.
                   3532: 	   	         ' for embedded media: '.$parse_result); 
                   3533:             }
1.637     raeburn  3534:         }
                   3535:     }
1.860     raeburn  3536:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3537:         my $input = $filepath.'/'.$file;
                   3538:         my $output = $filepath.'/'.'tn-'.$file;
                   3539:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3540:         system("convert -sample $thumbsize $input $output");
                   3541:         if (-e $filepath.'/'.'tn-'.$file) {
                   3542:             $fetchthumb  = 1; 
                   3543:         }
                   3544:     }
1.858     raeburn  3545:  
1.259     www      3546: # Notify homeserver to grep it
                   3547: #
1.984     neumanie 3548:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3549:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3550:     if ($fetchresult eq 'ok') {
1.860     raeburn  3551:         if ($fetchthumb) {
                   3552:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3553:             if ($thumbresult ne 'ok') {
                   3554:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3555:                          $docuhome.': '.$thumbresult);
                   3556:             }
                   3557:         }
1.259     www      3558: #
1.258     www      3559: # Return the URL to it
1.494     albertel 3560:         return '/uploaded/'.$path.$file;
1.263     www      3561:     } else {
1.494     albertel 3562:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3563: 		 ': '.$fetchresult);
1.263     www      3564:         return '/adm/notfound.html';
1.858     raeburn  3565:     }
1.493     albertel 3566: }
                   3567: 
1.637     raeburn  3568: sub extract_embedded_items {
1.961     raeburn  3569:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3570:     my @state = ();
1.1164    raeburn  3571:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3572:     my %javafiles = (
                   3573:                       codebase => '',
                   3574:                       code => '',
                   3575:                       archive => ''
                   3576:                     );
                   3577:     my %mediafiles = (
                   3578:                       src => '',
                   3579:                       movie => '',
                   3580:                      );
1.648     raeburn  3581:     my $p;
                   3582:     if ($content) {
                   3583:         $p = HTML::LCParser->new($content);
                   3584:     } else {
1.961     raeburn  3585:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3586:     }
1.641     albertel 3587:     while (my $t=$p->get_token()) {
1.640     albertel 3588: 	if ($t->[0] eq 'S') {
                   3589: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3590: 	    push(@state, $tagname);
1.648     raeburn  3591:             if (lc($tagname) eq 'allow') {
                   3592:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3593:             }
1.640     albertel 3594: 	    if (lc($tagname) eq 'img') {
                   3595: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3596: 	    }
1.886     albertel 3597: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3598:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3599: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3600:                 }
1.886     albertel 3601: 	    }
1.645     raeburn  3602:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3603:                 my $src;
1.645     raeburn  3604:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3605:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3606:                 } else {
1.1164    raeburn  3607:                     if ($attr->{'src'} ne '') {
                   3608:                         $src = $attr->{'src'};
                   3609:                         &add_filetype($allfiles,$src,'src');
                   3610:                     }
                   3611:                 }
                   3612:                 my $text = $p->get_trimmed_text();
                   3613:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3614:                     my @swfargs = split(/,/,$1);
                   3615:                     foreach my $item (@swfargs) {
                   3616:                         $item =~ s/["']//g;
                   3617:                         $item =~ s/^\s+//;
                   3618:                         $item =~ s/\s+$//;
                   3619:                     }
                   3620:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3621:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3622:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3623:                         } else {
                   3624:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3625:                         }
                   3626:                     }
1.645     raeburn  3627:                 }
                   3628:             }
                   3629:             if (lc($tagname) eq 'link') {
                   3630:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3631:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3632:                 }
                   3633:             }
1.640     albertel 3634: 	    if (lc($tagname) eq 'object' ||
                   3635: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3636: 		foreach my $item (keys(%javafiles)) {
                   3637: 		    $javafiles{$item} = '';
                   3638: 		}
1.1164    raeburn  3639:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3640:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3641:                 }
1.640     albertel 3642: 	    }
                   3643: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3644: 		my $name = lc($attr->{'name'});
                   3645: 		foreach my $item (keys(%javafiles)) {
                   3646: 		    if ($name eq $item) {
                   3647: 			$javafiles{$item} = $attr->{'value'};
                   3648: 			last;
                   3649: 		    }
                   3650: 		}
1.1164    raeburn  3651:                 my $pathfrom;
1.640     albertel 3652: 		foreach my $item (keys(%mediafiles)) {
                   3653: 		    if ($name eq $item) {
1.1164    raeburn  3654:                         $pathfrom = $attr->{'value'};
                   3655:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3656: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3657: 			last;
                   3658: 		    }
                   3659: 		}
1.1164    raeburn  3660:                 if ($name eq 'flashvars') {
                   3661:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3662:                 }
                   3663:                 if ($pathfrom ne '') {
                   3664:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3665:                                          $pathfrom);
                   3666:                 }
1.640     albertel 3667: 	    }
                   3668: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3669: 		foreach my $item (keys(%javafiles)) {
                   3670: 		    if ($attr->{$item}) {
                   3671: 			$javafiles{$item} = $attr->{$item};
                   3672: 			last;
                   3673: 		    }
                   3674: 		}
                   3675: 		foreach my $item (keys(%mediafiles)) {
                   3676: 		    if ($attr->{$item}) {
                   3677: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3678: 			last;
                   3679: 		    }
                   3680: 		}
1.1164    raeburn  3681:                 if (lc($tagname) eq 'embed') {
                   3682:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3683:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3684:                                              $attr->{'src'});
                   3685:                     }
                   3686:                 }
1.640     albertel 3687: 	    }
1.1172.2.35  raeburn  3688:             if (lc($tagname) eq 'iframe') {
                   3689:                 my $src = $attr->{'src'} ;
                   3690:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3691:                     &add_filetype($allfiles,$src,'src');
                   3692:                 } elsif ($src =~ m{^/}) {
                   3693:                     if ($env{'request.course.id'}) {
                   3694:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3695:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3696:                         my $url = &hreflocation('',$fullpath);
                   3697:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3698:                             my $relpath = $1;
                   3699:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3700:                                 &add_filetype($allfiles,$1,'src');
                   3701:                             }
                   3702:                         }
                   3703:                     }
                   3704:                 }
                   3705:             }
1.1164    raeburn  3706:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  3707:                 pop(@state);
1.1164    raeburn  3708:             }
1.640     albertel 3709: 	} elsif ($t->[0] eq 'E') {
                   3710: 	    my ($tagname) = ($t->[1]);
                   3711: 	    if ($javafiles{'codebase'} ne '') {
                   3712: 		$javafiles{'codebase'} .= '/';
                   3713: 	    }  
                   3714: 	    if (lc($tagname) eq 'applet' ||
                   3715: 		lc($tagname) eq 'object' ||
                   3716: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3717: 		) {
                   3718: 		foreach my $item (keys(%javafiles)) {
                   3719: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3720: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3721: 			&add_filetype($allfiles,$file,$item);
                   3722: 		    }
                   3723: 		}
                   3724: 	    } 
                   3725: 	    pop @state;
                   3726: 	}
                   3727:     }
1.1164    raeburn  3728:     foreach my $id (sort(keys(%flashvars))) {
                   3729:         if ($shockwave{$id} ne '') {
                   3730:             my @pairs = split(/\&/,$flashvars{$id});
                   3731:             foreach my $pair (@pairs) {
                   3732:                 my ($key,$value) = split(/\=/,$pair);
                   3733:                 if ($key eq 'thumb') {
                   3734:                     &add_filetype($allfiles,$value,$key);
                   3735:                 } elsif ($key eq 'content') {
                   3736:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3737:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3738:                     if ($ext ne '') {
                   3739:                         &add_filetype($allfiles,$path.$value,$ext);
                   3740:                     }
                   3741:                 }
                   3742:             }
                   3743:         }
                   3744:     }
1.637     raeburn  3745:     return 'ok';
                   3746: }
                   3747: 
1.639     albertel 3748: sub add_filetype {
                   3749:     my ($allfiles,$file,$type)=@_;
                   3750:     if (exists($allfiles->{$file})) {
                   3751: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3752: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3753: 	}
                   3754:     } else {
                   3755: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3756:     }
                   3757: }
                   3758: 
1.1164    raeburn  3759: sub embedded_dependency {
                   3760:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3761:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3762:         if (($identifier ne '') &&
                   3763:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3764:             ($pathfrom ne '')) {
                   3765:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3766:             foreach my $dep (@{$related->{$identifier}}) {
                   3767:                 &add_filetype($allfiles,$path.$dep,'object');
                   3768:             }
                   3769:         }
                   3770:     }
                   3771:     return;
                   3772: }
                   3773: 
1.493     albertel 3774: sub removeuploadedurl {
1.984     neumanie 3775:     my ($url)=@_;	
                   3776:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3777:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3778: }
                   3779: 
                   3780: sub removeuserfile {
                   3781:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3782:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3783:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3784:     if ($result eq 'ok') {	
1.798     raeburn  3785:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3786:             my $metafile = $fname.'.meta';
                   3787:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3788: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3789:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3790:             my $sqlresult = 
1.823     albertel 3791:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3792:                                         'portfolio_metadata',$group,
                   3793:                                         'delete');
1.798     raeburn  3794:         }
                   3795:     }
                   3796:     return $result;
1.257     www      3797: }
1.15      www      3798: 
1.530     albertel 3799: sub mkdiruserfile {
                   3800:     my ($docuname,$docudom,$dir)=@_;
                   3801:     my $home=&homeserver($docuname,$docudom);
                   3802:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3803: }
                   3804: 
1.531     albertel 3805: sub renameuserfile {
                   3806:     my ($docuname,$docudom,$old,$new)=@_;
                   3807:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3808:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3809:                         &escape("$old").':'.&escape("$new"),$home);
                   3810:     if ($result eq 'ok') {
                   3811:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3812:             my $oldmeta = $old.'.meta';
                   3813:             my $newmeta = $new.'.meta';
                   3814:             my $metaresult = 
                   3815:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3816: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3817:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3818:             my $sqlresult = 
1.823     albertel 3819:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3820:                                         'portfolio_metadata',$group,
                   3821:                                         'delete');
1.798     raeburn  3822:         }
                   3823:     }
                   3824:     return $result;
1.531     albertel 3825: }
                   3826: 
1.14      www      3827: # ------------------------------------------------------------------------- Log
                   3828: 
                   3829: sub log {
                   3830:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3831:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3832: }
                   3833: 
                   3834: # ------------------------------------------------------------------ Course Log
1.352     www      3835: #
                   3836: # This routine flushes several buffers of non-mission-critical nature
                   3837: #
1.157     www      3838: 
                   3839: sub flushcourselogs {
1.352     www      3840:     &logthis('Flushing log buffers');
                   3841: #
                   3842: # course logs
                   3843: # This is a log of all transactions in a course, which can be used
                   3844: # for data mining purposes
                   3845: #
                   3846: # It also collects the courseid database, which lists last transaction
                   3847: # times and course titles for all courseids
                   3848: #
                   3849:     my %courseidbuffer=();
1.921     raeburn  3850:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3851:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3852: 		          &escape($courselogs{$crsid}),
                   3853: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3854: 	    delete $courselogs{$crsid};
                   3855:         } else {
                   3856:             &logthis('Failed to flush log buffer for '.$crsid);
                   3857:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3858:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3859:                         " exceeded maximum size, deleting.</font>");
                   3860:                delete $courselogs{$crsid};
                   3861:             }
1.352     www      3862:         }
1.920     raeburn  3863:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3864:             'description' => $coursedescrbuf{$crsid},
                   3865:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3866:             'type'        => $coursetypebuf{$crsid},
                   3867:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3868:         };
1.191     harris41 3869:     }
1.352     www      3870: #
                   3871: # Write course id database (reverse lookup) to homeserver of courses 
                   3872: # Is used in pickcourse
                   3873: #
1.840     albertel 3874:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3875:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3876:                                     $courseidbuffer{$crs_home},
                   3877:                                     $crs_home,'timeonly');
1.352     www      3878:     }
                   3879: #
                   3880: # File accesses
                   3881: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3882: #
1.449     matthew  3883:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3884:         if ($entry =~ /___count$/) {
                   3885:             my ($dom,$name);
1.807     albertel 3886:             ($dom,$name,undef)=
1.811     albertel 3887: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3888:             if (! defined($dom) || $dom eq '' || 
                   3889:                 ! defined($name) || $name eq '') {
1.620     albertel 3890:                 my $cid = $env{'request.course.id'};
                   3891:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3892:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3893:             }
1.450     matthew  3894:             my $value = $accesshash{$entry};
                   3895:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3896:             my %temphash=($url => $value);
1.449     matthew  3897:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3898:             if ($result eq 'ok') {
                   3899:                 delete $accesshash{$entry};
                   3900:             }
                   3901:         } else {
1.811     albertel 3902:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3903:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3904:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3905:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3906:                 delete $accesshash{$entry};
                   3907:             }
1.185     www      3908:         }
1.191     harris41 3909:     }
1.352     www      3910: #
                   3911: # Roles
                   3912: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3913: #
1.800     albertel 3914:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3915:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3916: 	    split(/\:/,$entry);
                   3917:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3918:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3919:                 $rudom,$runame) eq 'ok') {
                   3920: 	    delete $userrolehash{$entry};
                   3921:         }
                   3922:     }
1.662     raeburn  3923: #
1.1172.2.90  raeburn  3924: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  3925: #
                   3926:     my %domrolebuffer = ();
1.1000    raeburn  3927:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3928:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3929:         if ($domrolebuffer{$rudom}) {
                   3930:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3931:                       '='.&escape($domainrolehash{$entry});
                   3932:         } else {
                   3933:             $domrolebuffer{$rudom}.=&escape($entry).
                   3934:                       '='.&escape($domainrolehash{$entry});
                   3935:         }
                   3936:         delete $domainrolehash{$entry};
                   3937:     }
                   3938:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  3939:         my %servers;
                   3940:         if (defined(&domain($dom,'primary'))) {
                   3941:             my $primary=&domain($dom,'primary');
                   3942:             my $hostname=&hostname($primary);
                   3943:             $servers{$primary} = $hostname;
                   3944:         } else {
                   3945:             %servers = &get_servers($dom,'library');
                   3946:         }
1.841     albertel 3947: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  3948: 	    if (&reply('domroleput:'.$dom.':'.
                   3949: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3950: 	        last;
                   3951: 	    } else {
1.841     albertel 3952: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3953: 	    }
1.662     raeburn  3954:         }
                   3955:     }
1.186     www      3956:     $dumpcount++;
1.157     www      3957: }
                   3958: 
                   3959: sub courselog {
                   3960:     my $what=shift;
1.158     www      3961:     $what=time.':'.$what;
1.620     albertel 3962:     unless ($env{'request.course.id'}) { return ''; }
                   3963:     $coursedombuf{$env{'request.course.id'}}=
                   3964:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3965:     $coursenumbuf{$env{'request.course.id'}}=
                   3966:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3967:     $coursehombuf{$env{'request.course.id'}}=
                   3968:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3969:     $coursedescrbuf{$env{'request.course.id'}}=
                   3970:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3971:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3972:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3973:     $courseownerbuf{$env{'request.course.id'}}=
                   3974:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3975:     $coursetypebuf{$env{'request.course.id'}}=
                   3976:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3977:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3978: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3979:     } else {
1.620     albertel 3980: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3981:     }
1.620     albertel 3982:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3983: 	&flushcourselogs();
                   3984:     }
1.158     www      3985: }
                   3986: 
                   3987: sub courseacclog {
                   3988:     my $fnsymb=shift;
1.620     albertel 3989:     unless ($env{'request.course.id'}) { return ''; }
                   3990:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3991:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3992:         $what.=':POST';
1.583     matthew  3993:         # FIXME: Probably ought to escape things....
1.800     albertel 3994: 	foreach my $key (keys(%env)) {
                   3995:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3996:                 my $formitem = $1;
                   3997:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3998:                     $what.=':'.$formitem.'='.$env{$key};
                   3999:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4000:                     $what.=':'.$formitem.'='.$env{$key};
                   4001:                 }
1.158     www      4002:             }
1.191     harris41 4003:         }
1.583     matthew  4004:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4005:         # FIXME: We should not be depending on a form parameter that someone
                   4006:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4007:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4008:             $what.= ':POST';
                   4009:             # FIXME: Probably ought to escape things....
                   4010:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4011:                                  'crsdiscuss') {
1.620     albertel 4012:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4013:             }
                   4014:         }
1.158     www      4015:     }
                   4016:     &courselog($what);
1.149     www      4017: }
                   4018: 
1.185     www      4019: sub countacc {
                   4020:     my $url=&declutter(shift);
1.458     matthew  4021:     return if (! defined($url) || $url eq '');
1.620     albertel 4022:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4023: #
                   4024: # Mark that this url was used in this course
                   4025: #
1.620     albertel 4026:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4027: #
                   4028: # Increase the access count for this resource in this child process
                   4029: #
1.281     www      4030:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4031:     $accesshash{$key}++;
1.185     www      4032: }
1.349     www      4033: 
1.361     www      4034: sub linklog {
                   4035:     my ($from,$to)=@_;
                   4036:     $from=&declutter($from);
                   4037:     $to=&declutter($to);
                   4038:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4039:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4040: }
1.1160    www      4041: 
                   4042: sub statslog {
                   4043:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4044:     if ($users<2) { return; }
                   4045:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4046:             'course'       => $env{'request.course.id'},
                   4047:             'sections'     => '"all"',
                   4048:             'num_students' => $users,
                   4049:             'part'         => $part,
                   4050:             'symb'         => $symb,
                   4051:             'mean_tries'   => $av_attempts,
                   4052:             'deg_of_diff'  => $degdiff});
                   4053:     foreach my $key (keys(%dynstore)) {
                   4054:         $accesshash{$key}=$dynstore{$key};
                   4055:     }
                   4056: }
1.361     www      4057:   
1.349     www      4058: sub userrolelog {
                   4059:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4060:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4061:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4062:        $userrolehash
                   4063:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4064:                     =$tend.':'.$tstart;
1.662     raeburn  4065:     }
1.1169    droeschl 4066:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4067:        $userrolehash
                   4068:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4069:                     =$tend.':'.$tstart;
                   4070:     }
1.1172.2.90  raeburn  4071:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4072:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4073:        $domainrolehash
                   4074:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4075:                     = $tend.':'.$tstart;
                   4076:     }
1.351     www      4077: }
                   4078: 
1.957     raeburn  4079: sub courserolelog {
                   4080:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4081:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4082:         my $cdom = $1;
                   4083:         my $cnum = $2;
                   4084:         my $sec = $3;
                   4085:         my $namespace = 'rolelog';
                   4086:         my %storehash = (
                   4087:                            role    => $trole,
                   4088:                            start   => $tstart,
                   4089:                            end     => $tend,
                   4090:                            selfenroll => $selfenroll,
                   4091:                            context    => $context,
                   4092:                         );
                   4093:         if ($trole eq 'gr') {
                   4094:             $namespace = 'groupslog';
                   4095:             $storehash{'group'} = $sec;
                   4096:         } else {
                   4097:             $storehash{'section'} = $sec;
                   4098:         }
                   4099:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4100:                    $domain,$cnum,$cdom);
                   4101:         if (($trole ne 'st') || ($sec ne '')) {
                   4102:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4103:         }
                   4104:     }
                   4105:     return;
                   4106: }
                   4107: 
1.1172.2.9  raeburn  4108: sub domainrolelog {
                   4109:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4110:     if ($area =~ m{^/($match_domain)/$}) {
                   4111:         my $cdom = $1;
                   4112:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4113:         my $namespace = 'rolelog';
                   4114:         my %storehash = (
                   4115:                            role    => $trole,
                   4116:                            start   => $tstart,
                   4117:                            end     => $tend,
                   4118:                            context => $context,
                   4119:                         );
                   4120:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4121:                    $domain,$domconfiguser,$cdom);
                   4122:     }
                   4123:     return;
                   4124: 
                   4125: }
                   4126: 
                   4127: sub coauthorrolelog {
                   4128:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4129:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4130:         my $audom = $1;
                   4131:         my $auname = $2;
                   4132:         my $namespace = 'rolelog';
                   4133:         my %storehash = (
                   4134:                            role    => $trole,
                   4135:                            start   => $tstart,
                   4136:                            end     => $tend,
                   4137:                            context => $context,
                   4138:                         );
                   4139:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4140:                    $domain,$auname,$audom);
                   4141:     }
                   4142:     return;
                   4143: }
                   4144: 
1.351     www      4145: sub get_course_adv_roles {
1.948     raeburn  4146:     my ($cid,$codes) = @_;
1.620     albertel 4147:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4148:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4149:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4150:     my %nothide=();
1.800     albertel 4151:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4152:         if ($user !~ /:/) {
                   4153: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4154:         } else {
                   4155:             $nothide{$user}=1;
                   4156:         }
1.470     www      4157:     }
1.1172.2.23  raeburn  4158:     my @possdoms = ($coursehash{'domain'});
                   4159:     if ($coursehash{'checkforpriv'}) {
                   4160:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4161:     }
1.351     www      4162:     my %returnhash=();
                   4163:     my %dumphash=
                   4164:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4165:     my $now=time;
1.997     raeburn  4166:     my %privileged;
1.1000    raeburn  4167:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4168: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4169:         if (($tstart) && ($tstart<0)) { next; }
                   4170:         if (($tend) && ($tend<$now)) { next; }
                   4171:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4172:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4173: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4174:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4175:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4176: 	if ($role eq 'cr') { next; }
1.948     raeburn  4177:         if ($codes) {
                   4178:             if ($section) { $role .= ':'.$section; }
                   4179:             if ($returnhash{$role}) {
                   4180:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4181:             } else {
                   4182:                 $returnhash{$role}=$username.':'.$domain;
                   4183:             }
1.351     www      4184:         } else {
1.988     raeburn  4185:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4186:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4187:             if ($returnhash{$key}) {
                   4188: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4189:             } else {
                   4190:                 $returnhash{$key}=$username.':'.$domain;
                   4191:             }
1.351     www      4192:         }
1.948     raeburn  4193:     }
1.400     www      4194:     return %returnhash;
                   4195: }
                   4196: 
                   4197: sub get_my_roles {
1.937     raeburn  4198:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4199:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4200:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4201:     my (%dumphash,%nothide);
1.1086    raeburn  4202:     if ($context eq 'userroles') {
1.1166    raeburn  4203:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4204:     } else {
1.1172.2.23  raeburn  4205:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4206:         if ($hidepriv) {
                   4207:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4208:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4209:                 if ($user !~ /:/) {
                   4210:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4211:                 } else {
                   4212:                     $nothide{$user} = 1;
                   4213:                 }
                   4214:             }
                   4215:         }
1.858     raeburn  4216:     }
1.400     www      4217:     my %returnhash=();
                   4218:     my $now=time;
1.999     raeburn  4219:     my %privileged;
1.800     albertel 4220:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4221:         my ($role,$tend,$tstart);
                   4222:         if ($context eq 'userroles') {
1.1149    raeburn  4223:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4224: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4225:         } else {
                   4226:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4227:         }
1.400     www      4228:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4229:         my $status = 'active';
1.939     raeburn  4230:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4231:             $status = 'previous';
                   4232:         } 
                   4233:         if (($tstart) && ($now<$tstart)) {
                   4234:             $status = 'future';
                   4235:         }
                   4236:         if (ref($types) eq 'ARRAY') {
                   4237:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4238:                 next;
                   4239:             } 
                   4240:         } else {
                   4241:             if ($status ne 'active') {
                   4242:                 next;
                   4243:             }
                   4244:         }
1.867     raeburn  4245:         my ($rolecode,$username,$domain,$section,$area);
                   4246:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4247:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4248:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4249:         } else {
                   4250:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4251:         }
1.832     raeburn  4252:         if (ref($roledoms) eq 'ARRAY') {
                   4253:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4254:                 next;
                   4255:             }
                   4256:         }
                   4257:         if (ref($roles) eq 'ARRAY') {
                   4258:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4259:                 if ($role =~ /^cr\//) {
                   4260:                     if (!grep(/^cr$/,@{$roles})) {
                   4261:                         next;
                   4262:                     }
1.1104    raeburn  4263:                 } elsif ($role =~ /^gr\//) {
                   4264:                     if (!grep(/^gr$/,@{$roles})) {
                   4265:                         next;
                   4266:                     }
1.922     raeburn  4267:                 } else {
                   4268:                     next;
                   4269:                 }
1.832     raeburn  4270:             }
1.867     raeburn  4271:         }
1.937     raeburn  4272:         if ($hidepriv) {
1.1172.2.23  raeburn  4273:             my @privroles = ('dc','su');
1.999     raeburn  4274:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4275:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4276:             } else {
1.1172.2.23  raeburn  4277:                 my $possdoms = [$domain];
                   4278:                 if (ref($roledoms) eq 'ARRAY') {
                   4279:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4280:                 }
1.1172.2.23  raeburn  4281:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4282:                     if (!$nothide{$username.':'.$domain}) {
                   4283:                         next;
                   4284:                     }
                   4285:                 }
1.937     raeburn  4286:             }
                   4287:         }
1.933     raeburn  4288:         if ($withsec) {
                   4289:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4290:                 $tstart.':'.$tend;
                   4291:         } else {
                   4292:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4293:         }
1.832     raeburn  4294:     }
1.373     www      4295:     return %returnhash;
1.399     www      4296: }
                   4297: 
1.1172.2.89  raeburn  4298: sub get_all_adhocroles {
                   4299:     my ($dom) = @_;
                   4300:     my @roles_by_num = ();
                   4301:     my %domdefaults = &get_domain_defaults($dom);
                   4302:     my (%description,%access_in_dom,%access_info);
                   4303:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4304:         my $count = 0;
                   4305:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4306:         my %ordered;
                   4307:         foreach my $role (sort(keys(%domcurrent))) {
                   4308:             my ($order,$desc,$access_in_dom);
                   4309:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4310:                 $order = $domcurrent{$role}{'order'};
                   4311:                 $desc = $domcurrent{$role}{'desc'};
                   4312:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4313:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4314:             }
                   4315:             if ($order eq '') {
                   4316:                 $order = $count;
                   4317:             }
                   4318:             $ordered{$order} = $role;
                   4319:             if ($desc ne '') {
                   4320:                 $description{$role} = $desc;
                   4321:             } else {
                   4322:                 $description{$role}= $role;
                   4323:             }
                   4324:             $count++;
                   4325:         }
                   4326:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4327:             push(@roles_by_num,$ordered{$item});
                   4328:         }
                   4329:     }
                   4330:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4331: }
                   4332: 
                   4333: sub get_my_adhocroles {
                   4334:     my ($cid,$checkreg) = @_;
                   4335:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4336:     if ($env{'request.course.id'} eq $cid) {
                   4337:         $cdom = $env{'course.'.$cid.'.domain'};
                   4338:         $cnum = $env{'course.'.$cid.'.num'};
                   4339:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4340:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4341:         $cdom = $1;
                   4342:         $cnum = $2;
                   4343:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4344:                                      $cdom,$cnum);
                   4345:     }
                   4346:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4347:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4348:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4349:         if ($rosterhash{$user} ne '') {
                   4350:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4351:             return ([],{}) if ($type eq 'auto');
                   4352:         }
                   4353:     }
                   4354:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  4355:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  4356:             my $then=$env{'user.login.time'};
                   4357:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  4358:             if (!$update) {
                   4359:                 $update = $then;
                   4360:             }
                   4361:             my @liveroles;
                   4362:             foreach my $role ('dh','da') {
                   4363:                 if ($env{"user.role.$role./$cdom/"}) {
                   4364:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   4365:                     my $limit = $update;
                   4366:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4367:                         $limit = $then;
                   4368:                     }
                   4369:                     my $activerole = 1;
                   4370:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4371:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4372:                     if ($activerole) {
                   4373:                         push(@liveroles,$role);
                   4374:                     }
                   4375:                 }
                   4376:             }
                   4377:             if (@liveroles) {
1.1172.2.89  raeburn  4378:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   4379:                     my ($accessref,$accessinfo,%access_in_dom);
                   4380:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4381:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4382:                         if (@{$roles_by_num}) {
                   4383:                             my %settings;
                   4384:                             if ($env{'request.course.id'} eq $cid) {
                   4385:                                 foreach my $envkey (keys(%env)) {
                   4386:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4387:                                         $settings{$1} = $env{$envkey};
                   4388:                                     }
                   4389:                                 }
                   4390:                             } else {
                   4391:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4392:                             }
                   4393:                             my %setincrs;
                   4394:                             if ($settings{'internal.adhocaccess'}) {
                   4395:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4396:                             }
                   4397:                             my @statuses;
                   4398:                             if ($env{'environment.inststatus'}) {
                   4399:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4400:                             }
                   4401:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4402:                             if (ref($accessref) eq 'HASH') {
                   4403:                                 %access_in_dom = %{$accessref};
                   4404:                             }
                   4405:                             foreach my $role (@{$roles_by_num}) {
                   4406:                                 my ($curraccess,@okstatus,@personnel);
                   4407:                                 if ($setincrs{$role}) {
                   4408:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4409:                                     if ($curraccess eq 'status') {
                   4410:                                         @okstatus = split(/\&/,$rest);
                   4411:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4412:                                         @personnel = split(/\&/,$rest);
                   4413:                                     }
                   4414:                                 } else {
                   4415:                                     $curraccess = $access_in_dom{$role};
                   4416:                                     if (ref($accessinfo) eq 'HASH') {
                   4417:                                         if ($curraccess eq 'status') {
                   4418:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4419:                                                 @okstatus = @{$accessinfo->{$role}};
                   4420:                                             }
                   4421:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4422:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4423:                                                 @personnel = @{$accessinfo->{$role}};
                   4424:                                             }
                   4425:                                         }
                   4426:                                     }
                   4427:                                 }
                   4428:                                 if ($curraccess eq 'none') {
                   4429:                                     next;
                   4430:                                 } elsif ($curraccess eq 'all') {
                   4431:                                     push(@possroles,$role);
1.1172.2.90  raeburn  4432:                                 } elsif ($curraccess eq 'dh') {
                   4433:                                     if (grep(/^dh$/,@liveroles)) {
                   4434:                                         push(@possroles,$role);
                   4435:                                     } else {
                   4436:                                         next;
                   4437:                                     }
                   4438:                                 } elsif ($curraccess eq 'da') {
                   4439:                                     if (grep(/^da$/,@liveroles)) {
                   4440:                                         push(@possroles,$role);
                   4441:                                     } else {
                   4442:                                         next;
                   4443:                                     }
1.1172.2.89  raeburn  4444:                                 } elsif ($curraccess eq 'status') {
                   4445:                                     if (@okstatus) {
                   4446:                                         if (!@statuses) {
                   4447:                                             if (grep(/^default$/,@okstatus)) {
                   4448:                                                 push(@possroles,$role);
                   4449:                                             }
                   4450:                                         } else {
                   4451:                                             foreach my $status (@okstatus) {
                   4452:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4453:                                                     push(@possroles,$role);
                   4454:                                                     last;
                   4455:                                                 }
                   4456:                                             }
                   4457:                                         }
                   4458:                                     }
                   4459:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4460:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4461:                                         if ($curraccess eq 'exc') {
                   4462:                                             push(@possroles,$role);
                   4463:                                         }
                   4464:                                     } elsif ($curraccess eq 'inc') {
                   4465:                                         push(@possroles,$role);
                   4466:                                     }
                   4467:                                 }
                   4468:                             }
                   4469:                         }
                   4470:                     }
                   4471:                 }
                   4472:             }
                   4473:         }
                   4474:     }
                   4475:     unless (ref($description) eq 'HASH') {
                   4476:         if (ref($roles_by_num) eq 'ARRAY') {
                   4477:             my %desc;
                   4478:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4479:             $description = \%desc;
                   4480:         } else {
                   4481:             $description = {};
                   4482:         }
                   4483:     }
                   4484:     return (\@possroles,$description);
                   4485: }
                   4486: 
1.399     www      4487: # ----------------------------------------------------- Frontpage Announcements
                   4488: #
                   4489: #
                   4490: 
                   4491: sub postannounce {
                   4492:     my ($server,$text)=@_;
1.844     albertel 4493:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4494:     unless ($text=~/\w/) { $text=''; }
                   4495:     return &reply('setannounce:'.&escape($text),$server);
                   4496: }
                   4497: 
                   4498: sub getannounce {
1.448     albertel 4499: 
                   4500:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4501: 	my $announcement='';
1.800     albertel 4502: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4503: 	close($fh);
1.399     www      4504: 	if ($announcement=~/\w/) { 
                   4505: 	    return 
                   4506:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4507:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4508: 	} else {
                   4509: 	    return '';
                   4510: 	}
                   4511:     } else {
                   4512: 	return '';
                   4513:     }
1.351     www      4514: }
1.353     www      4515: 
                   4516: # ---------------------------------------------------------- Course ID routines
                   4517: # Deal with domain's nohist_courseid.db files
                   4518: #
                   4519: 
                   4520: sub courseidput {
1.921     raeburn  4521:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4522:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4523:     my $outcome;
                   4524:     if ($caller eq 'timeonly') {
                   4525:         my $cids = '';
                   4526:         foreach my $item (keys(%$storehash)) {
                   4527:             $cids.=&escape($item).'&';
                   4528:         }
                   4529:         $cids=~s/\&$//;
                   4530:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4531:                           $coursehome);       
                   4532:     } else {
                   4533:         my $items = '';
                   4534:         foreach my $item (keys(%$storehash)) {
                   4535:             $items.= &escape($item).'='.
                   4536:                      &freeze_escape($$storehash{$item}).'&';
                   4537:         }
                   4538:         $items=~s/\&$//;
                   4539:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4540:                           $coursehome);
1.918     raeburn  4541:     }
                   4542:     if ($outcome eq 'unknown_cmd') {
                   4543:         my $what;
                   4544:         foreach my $cid (keys(%$storehash)) {
                   4545:             $what .= &escape($cid).'=';
1.921     raeburn  4546:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4547:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4548:             }
                   4549:             $what =~ s/\:$/&/;
                   4550:         }
                   4551:         $what =~ s/\&$//;  
                   4552:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4553:     } else {
                   4554:         return $outcome;
                   4555:     }
1.353     www      4556: }
                   4557: 
                   4558: sub courseiddump {
1.921     raeburn  4559:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4560:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4561:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  4562:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  4563:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4564:     my $as_hash = 1;
                   4565:     my %returnhash;
                   4566:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4567:     my %libserv = &all_library();
                   4568:     foreach my $tryserver (keys(%libserv)) {
                   4569:         if ( (  $hostidflag == 1 
                   4570: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4571: 	     || (!defined($hostidflag)) ) {
                   4572: 
1.918     raeburn  4573: 	    if (($domfilter eq '') ||
                   4574: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  4575:                 my $rep;
                   4576:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   4577:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   4578:                         join(":", (&host_domain($tryserver), $sincefilter,
                   4579:                                 &escape($descfilter), &escape($instcodefilter),
                   4580:                                 &escape($ownerfilter), &escape($coursefilter),
                   4581:                                 &escape($typefilter), &escape($regexp_ok),
                   4582:                                 $as_hash, &escape($selfenrollonly),
                   4583:                                 &escape($catfilter), $showhidden, $caller,
                   4584:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   4585:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  4586:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4587:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  4588:                 } else {
                   4589:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4590:                              $sincefilter.':'.&escape($descfilter).':'.
                   4591:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4592:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4593:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4594:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4595:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4596:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4597:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  4598:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4599:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  4600:                 }
                   4601: 
1.918     raeburn  4602:                 my @pairs=split(/\&/,$rep);
                   4603:                 foreach my $item (@pairs) {
                   4604:                     my ($key,$value)=split(/\=/,$item,2);
                   4605:                     $key = &unescape($key);
                   4606:                     next if ($key =~ /^error: 2 /);
                   4607:                     my $result = &thaw_unescape($value);
                   4608:                     if (ref($result) eq 'HASH') {
                   4609:                         $returnhash{$key}=$result;
                   4610:                     } else {
1.921     raeburn  4611:                         my @responses = split(/:/,$value);
                   4612:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4613:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4614:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4615:                         }
1.1008    raeburn  4616:                     }
1.353     www      4617:                 }
                   4618:             }
                   4619:         }
                   4620:     }
                   4621:     return %returnhash;
                   4622: }
                   4623: 
1.1055    raeburn  4624: sub courselastaccess {
                   4625:     my ($cdom,$cnum,$hostidref) = @_;
                   4626:     my %returnhash;
                   4627:     if ($cdom && $cnum) {
                   4628:         my $chome = &homeserver($cnum,$cdom);
                   4629:         if ($chome ne 'no_host') {
                   4630:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4631:             &extract_lastaccess(\%returnhash,$rep);
                   4632:         }
                   4633:     } else {
                   4634:         if (!$cdom) { $cdom=''; }
                   4635:         my %libserv = &all_library();
                   4636:         foreach my $tryserver (keys(%libserv)) {
                   4637:             if (ref($hostidref) eq 'ARRAY') {
                   4638:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4639:             } 
                   4640:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4641:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4642:                 &extract_lastaccess(\%returnhash,$rep);
                   4643:             }
                   4644:         }
                   4645:     }
                   4646:     return %returnhash;
                   4647: }
                   4648: 
                   4649: sub extract_lastaccess {
                   4650:     my ($returnhash,$rep) = @_;
                   4651:     if (ref($returnhash) eq 'HASH') {
                   4652:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4653:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4654:                  $rep eq '') {
                   4655:             my @pairs=split(/\&/,$rep);
                   4656:             foreach my $item (@pairs) {
                   4657:                 my ($key,$value)=split(/\=/,$item,2);
                   4658:                 $key = &unescape($key);
                   4659:                 next if ($key =~ /^error: 2 /);
                   4660:                 $returnhash->{$key} = &thaw_unescape($value);
                   4661:             }
                   4662:         }
                   4663:     }
                   4664:     return;
                   4665: }
                   4666: 
1.658     raeburn  4667: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4668: 
                   4669: sub dcmailput {
1.685     raeburn  4670:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4671:     my $status = &Apache::lonnet::critical(
1.740     www      4672:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4673:        &escape($message),$server);
1.662     raeburn  4674:     return $status;
                   4675: }
                   4676: 
1.658     raeburn  4677: sub dcmaildump {
                   4678:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4679:     my %returnhash=();
1.846     albertel 4680: 
                   4681:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4682:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4683:                                                          &escape($enddate).':';
                   4684: 	my @esc_senders=map { &escape($_)} @$senders;
                   4685: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4686: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4687:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4688:             if (($key) && ($value)) {
                   4689:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4690:             }
                   4691:         }
                   4692:     }
                   4693:     return %returnhash;
                   4694: }
1.662     raeburn  4695: # ---------------------------------------------------------- Domain roles
                   4696: 
                   4697: sub get_domain_roles {
                   4698:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4699:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4700:         $startdate = '.';
                   4701:     }
1.1018    raeburn  4702:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4703:         $enddate = '.';
                   4704:     }
1.922     raeburn  4705:     my $rolelist;
                   4706:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  4707:         $rolelist = join('&',@{$roles});
1.922     raeburn  4708:     }
1.662     raeburn  4709:     my %personnel = ();
1.841     albertel 4710: 
                   4711:     my %servers = &get_servers($dom,'library');
                   4712:     foreach my $tryserver (keys(%servers)) {
                   4713: 	%{$personnel{$tryserver}}=();
                   4714: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4715: 					    &escape($startdate).':'.
                   4716: 					    &escape($enddate).':'.
                   4717: 					    &escape($rolelist), $tryserver))) {
                   4718: 	    my ($key,$value) = split(/\=/,$line,2);
                   4719: 	    if (($key) && ($value)) {
                   4720: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4721: 	    }
                   4722: 	}
1.662     raeburn  4723:     }
                   4724:     return %personnel;
                   4725: }
1.658     raeburn  4726: 
1.1172.2.89  raeburn  4727: sub get_active_domroles {
                   4728:     my ($dom,$roles) = @_;
                   4729:     return () unless (ref($roles) eq 'ARRAY');
                   4730:     my $now = time;
                   4731:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   4732:     my %domroles;
                   4733:     foreach my $server (keys(%dompersonnel)) {
                   4734:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   4735:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   4736:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   4737:         }
                   4738:     }
                   4739:     return %domroles;
                   4740: }
                   4741: 
1.1057    www      4742: # ----------------------------------------------------------- Interval timing 
1.149     www      4743: 
1.1153    www      4744: {
                   4745: # Caches needed for speedup of navmaps
                   4746: # We don't want to cache this for very long at all (5 seconds at most)
                   4747: # 
                   4748: # The user for whom we cache
                   4749: my $cachedkey='';
                   4750: # The cached times for this user
                   4751: my %cachedtimes=();
                   4752: # When this was last done
1.1172.2.66  raeburn  4753: my $cachedtime='';
1.1153    www      4754: 
                   4755: sub load_all_first_access {
1.1172.2.93.2  1(raebur 4756:7):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      4757:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.93.2  1(raebur 4758:7):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   4759:7):         (!$ignorecache)) {
1.1154    raeburn  4760:         return;
                   4761:     }
                   4762:     $cachedtime=time;
                   4763:     $cachedkey=$uname.':'.$udom;
                   4764:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4765: }
                   4766: 
1.504     albertel 4767: sub get_first_access {
1.1172.2.93.2  1(raebur 4768:7):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 4769:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4770:     if ($argsymb) { $symb=$argsymb; }
                   4771:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4772:     if ($argmap) { $map = $argmap; }
1.926     albertel 4773:     if ($type eq 'course') {
                   4774: 	$res='course';
                   4775:     } elsif ($type eq 'map') {
1.588     albertel 4776: 	$res=&symbread($map);
                   4777:     } else {
                   4778: 	$res=$symb;
                   4779:     }
1.1172.2.93.2  1(raebur 4780:7):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      4781:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4782: }
                   4783: 
                   4784: sub set_first_access {
1.1162    raeburn  4785:     my ($type,$interval)=@_;
1.790     albertel 4786:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4787:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4788:     if ($type eq 'course') {
                   4789: 	$res='course';
                   4790:     } elsif ($type eq 'map') {
1.588     albertel 4791: 	$res=&symbread($map);
                   4792:     } else {
                   4793: 	$res=$symb;
                   4794:     }
1.1153    www      4795:     $cachedkey='';
1.1162    raeburn  4796:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4797:     if (!$firstaccess) {
1.1162    raeburn  4798:         my $start = time;
                   4799: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4800:                           $udom,$uname);
                   4801:         if ($putres eq 'ok') {
                   4802:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4803:                  $udom,$uname); 
                   4804:             &appenv(
                   4805:                      {
                   4806:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4807:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4808:                      }
                   4809:                   );
                   4810:         }
                   4811:         return $putres;
1.505     albertel 4812:     }
                   4813:     return 'already_set';
1.504     albertel 4814: }
1.1153    www      4815: }
1.1172.2.32  raeburn  4816: 
                   4817: sub checkout {
                   4818:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   4819:     my $now=time;
                   4820:     my $lonhost=$perlvar{'lonHostID'};
                   4821:     my $infostr=&escape(
                   4822:                  'CHECKOUTTOKEN&'.
                   4823:                  $tuname.'&'.
                   4824:                  $tudom.'&'.
                   4825:                  $tcrsid.'&'.
                   4826:                  $symb.'&'.
                   4827:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   4828:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   4829:     if ($token=~/^error\:/) {
                   4830:         &logthis("<font color=\"blue\">WARNING: ".
                   4831:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4832:                  "</font>");
                   4833:         return '';
                   4834:     }
                   4835: 
                   4836:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   4837:     $token=~tr/a-z/A-Z/;
                   4838: 
                   4839:     my %infohash=('resource.0.outtoken' => $token,
                   4840:                   'resource.0.checkouttime' => $now,
                   4841:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   4842: 
                   4843:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4844:        return '';
                   4845:     } else {
                   4846:         &logthis("<font color=\"blue\">WARNING: ".
                   4847:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4848:                  "</font>");
                   4849:     }
                   4850: 
                   4851:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4852:                          &escape('Checkout '.$infostr.' - '.
                   4853:                                                  $token)) ne 'ok') {
                   4854:         return '';
                   4855:     } else {
                   4856:         &logthis("<font color=\"blue\">WARNING: ".
                   4857:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   4858:                  "</font>");
                   4859:     }
                   4860:     return $token;
                   4861: }
                   4862: 
                   4863: # ------------------------------------------------------------ Check in an item
                   4864: 
                   4865: sub checkin {
                   4866:     my $token=shift;
                   4867:     my $now=time;
                   4868:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   4869:     $lonhost=~tr/A-Z/a-z/;
                   4870:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   4871:     $dtoken=~s/\W/\_/g;
                   4872:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   4873:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   4874: 
                   4875:     unless (($tuname) && ($tudom)) {
                   4876:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   4877:         return '';
                   4878:     }
                   4879: 
                   4880:     unless (&allowed('mgr',$tcrsid)) {
                   4881:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   4882:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   4883:         return '';
                   4884:     }
                   4885: 
                   4886:     my %infohash=('resource.0.intoken' => $token,
                   4887:                   'resource.0.checkintime' => $now,
                   4888:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   4889: 
                   4890:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   4891:        return '';
                   4892:     }
                   4893: 
                   4894:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   4895:                          &escape('Checkin - '.$token)) ne 'ok') {
                   4896:         return '';
                   4897:     }
                   4898: 
                   4899:     return ($symb,$tuname,$tudom,$tcrsid);
                   4900: }
                   4901: 
1.110     www      4902: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4903: 
                   4904: sub expirespread {
                   4905:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4906:     my $cid=$env{'request.course.id'}; 
1.110     www      4907:     if ($cid) {
                   4908:        my $now=time;
                   4909:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4910:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4911:                             $env{'course.'.$cid.'.num'}.
1.110     www      4912: 	        	    ':nohist_expirationdates:'.
                   4913:                             &escape($key).'='.$now,
1.620     albertel 4914:                             $env{'course.'.$cid.'.home'})
1.110     www      4915:     }
                   4916:     return 'ok';
1.14      www      4917: }
                   4918: 
1.109     www      4919: # ----------------------------------------------------- Devalidate Spreadsheets
                   4920: 
                   4921: sub devalidate {
1.325     www      4922:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4923:     my $cid=$env{'request.course.id'}; 
1.109     www      4924:     if ($cid) {
1.391     matthew  4925:         # delete the stored spreadsheets for
                   4926:         # - the student level sheet of this user in course's homespace
                   4927:         # - the assessment level sheet for this resource 
                   4928:         #   for this user in user's homespace
1.553     albertel 4929: 	# - current conditional state info
1.325     www      4930: 	my $key=$uname.':'.$udom.':';
1.109     www      4931:         my $status=
1.299     matthew  4932: 	    &del('nohist_calculatedsheets',
1.391     matthew  4933: 		 [$key.'studentcalc:'],
1.620     albertel 4934: 		 $env{'course.'.$cid.'.domain'},
                   4935: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4936: 		.' '.
                   4937: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4938: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4939:         unless ($status eq 'ok ok') {
                   4940:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4941:                     $uname.' at '.$udom.' for '.
1.109     www      4942: 		    $symb.': '.$status);
1.133     albertel 4943:         }
1.553     albertel 4944: 	&delenv('user.state.'.$cid);
1.109     www      4945:     }
                   4946: }
                   4947: 
1.265     albertel 4948: sub get_scalar {
                   4949:     my ($string,$end) = @_;
                   4950:     my $value;
                   4951:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4952: 	$value = $1;
                   4953:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4954: 	$value = $1;
                   4955:     }
                   4956:     return &unescape($value);
                   4957: }
                   4958: 
                   4959: sub array2str {
                   4960:   my (@array) = @_;
                   4961:   my $result=&arrayref2str(\@array);
                   4962:   $result=~s/^__ARRAY_REF__//;
                   4963:   $result=~s/__END_ARRAY_REF__$//;
                   4964:   return $result;
                   4965: }
                   4966: 
1.204     albertel 4967: sub arrayref2str {
                   4968:   my ($arrayref) = @_;
1.265     albertel 4969:   my $result='__ARRAY_REF__';
1.204     albertel 4970:   foreach my $elem (@$arrayref) {
1.265     albertel 4971:     if(ref($elem) eq 'ARRAY') {
                   4972:       $result.=&arrayref2str($elem).'&';
                   4973:     } elsif(ref($elem) eq 'HASH') {
                   4974:       $result.=&hashref2str($elem).'&';
                   4975:     } elsif(ref($elem)) {
                   4976:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4977:     } else {
                   4978:       $result.=&escape($elem).'&';
                   4979:     }
                   4980:   }
                   4981:   $result=~s/\&$//;
1.265     albertel 4982:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4983:   return $result;
                   4984: }
                   4985: 
1.168     albertel 4986: sub hash2str {
1.204     albertel 4987:   my (%hash) = @_;
                   4988:   my $result=&hashref2str(\%hash);
1.265     albertel 4989:   $result=~s/^__HASH_REF__//;
                   4990:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4991:   return $result;
                   4992: }
                   4993: 
                   4994: sub hashref2str {
                   4995:   my ($hashref)=@_;
1.265     albertel 4996:   my $result='__HASH_REF__';
1.800     albertel 4997:   foreach my $key (sort(keys(%$hashref))) {
                   4998:     if (ref($key) eq 'ARRAY') {
                   4999:       $result.=&arrayref2str($key).'=';
                   5000:     } elsif (ref($key) eq 'HASH') {
                   5001:       $result.=&hashref2str($key).'=';
                   5002:     } elsif (ref($key)) {
1.265     albertel 5003:       $result.='=';
1.800     albertel 5004:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5005:     } else {
1.1132    raeburn  5006: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5007:     }
                   5008: 
1.800     albertel 5009:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5010:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5011:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5012:       $result.=&hashref2str($hashref->{$key}).'&';
                   5013:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5014:        $result.='&';
1.800     albertel 5015:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5016:     } else {
1.800     albertel 5017:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5018:     }
                   5019:   }
1.168     albertel 5020:   $result=~s/\&$//;
1.265     albertel 5021:   $result .= '__END_HASH_REF__';
1.168     albertel 5022:   return $result;
                   5023: }
                   5024: 
                   5025: sub str2hash {
1.265     albertel 5026:     my ($string)=@_;
                   5027:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5028:     return %$hash;
                   5029: }
                   5030: 
                   5031: sub str2hashref {
1.168     albertel 5032:   my ($string) = @_;
1.265     albertel 5033: 
                   5034:   my %hash;
                   5035: 
                   5036:   if($string !~ /^__HASH_REF__/) {
                   5037:       if (! ($string eq '' || !defined($string))) {
                   5038: 	  $hash{'error'}='Not hash reference';
                   5039:       }
                   5040:       return (\%hash, $string);
                   5041:   }
                   5042: 
                   5043:   $string =~ s/^__HASH_REF__//;
                   5044: 
                   5045:   while($string !~ /^__END_HASH_REF__/) {
                   5046:       #key
                   5047:       my $key='';
                   5048:       if($string =~ /^__HASH_REF__/) {
                   5049:           ($key, $string)=&str2hashref($string);
                   5050:           if(defined($key->{'error'})) {
                   5051:               $hash{'error'}='Bad data';
                   5052:               return (\%hash, $string);
                   5053:           }
                   5054:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5055:           ($key, $string)=&str2arrayref($string);
                   5056:           if($key->[0] eq 'Array reference error') {
                   5057:               $hash{'error'}='Bad data';
                   5058:               return (\%hash, $string);
                   5059:           }
                   5060:       } else {
                   5061:           $string =~ s/^(.*?)=//;
1.267     albertel 5062: 	  $key=&unescape($1);
1.265     albertel 5063:       }
                   5064:       $string =~ s/^=//;
                   5065: 
                   5066:       #value
                   5067:       my $value='';
                   5068:       if($string =~ /^__HASH_REF__/) {
                   5069:           ($value, $string)=&str2hashref($string);
                   5070:           if(defined($value->{'error'})) {
                   5071:               $hash{'error'}='Bad data';
                   5072:               return (\%hash, $string);
                   5073:           }
                   5074:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5075:           ($value, $string)=&str2arrayref($string);
                   5076:           if($value->[0] eq 'Array reference error') {
                   5077:               $hash{'error'}='Bad data';
                   5078:               return (\%hash, $string);
                   5079:           }
                   5080:       } else {
                   5081: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5082:       }
                   5083:       $string =~ s/^&//;
                   5084: 
                   5085:       $hash{$key}=$value;
1.204     albertel 5086:   }
1.265     albertel 5087: 
                   5088:   $string =~ s/^__END_HASH_REF__//;
                   5089: 
                   5090:   return (\%hash, $string);
1.204     albertel 5091: }
                   5092: 
                   5093: sub str2array {
1.265     albertel 5094:     my ($string)=@_;
                   5095:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5096:     return @$array;
                   5097: }
                   5098: 
                   5099: sub str2arrayref {
1.204     albertel 5100:   my ($string) = @_;
1.265     albertel 5101:   my @array;
                   5102: 
                   5103:   if($string !~ /^__ARRAY_REF__/) {
                   5104:       if (! ($string eq '' || !defined($string))) {
                   5105: 	  $array[0]='Array reference error';
                   5106:       }
                   5107:       return (\@array, $string);
                   5108:   }
                   5109: 
                   5110:   $string =~ s/^__ARRAY_REF__//;
                   5111: 
                   5112:   while($string !~ /^__END_ARRAY_REF__/) {
                   5113:       my $value='';
                   5114:       if($string =~ /^__HASH_REF__/) {
                   5115:           ($value, $string)=&str2hashref($string);
                   5116:           if(defined($value->{'error'})) {
                   5117:               $array[0] ='Array reference error';
                   5118:               return (\@array, $string);
                   5119:           }
                   5120:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5121:           ($value, $string)=&str2arrayref($string);
                   5122:           if($value->[0] eq 'Array reference error') {
                   5123:               $array[0] ='Array reference error';
                   5124:               return (\@array, $string);
                   5125:           }
                   5126:       } else {
                   5127: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5128:       }
                   5129:       $string =~ s/^&//;
                   5130: 
                   5131:       push(@array, $value);
1.191     harris41 5132:   }
1.265     albertel 5133: 
                   5134:   $string =~ s/^__END_ARRAY_REF__//;
                   5135: 
                   5136:   return (\@array, $string);
1.168     albertel 5137: }
                   5138: 
1.167     albertel 5139: # -------------------------------------------------------------------Temp Store
                   5140: 
1.168     albertel 5141: sub tmpreset {
                   5142:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5143:   if (!$symb) {
                   5144:     $symb=&symbread();
1.620     albertel 5145:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5146:   }
                   5147:   $symb=escape($symb);
                   5148: 
1.620     albertel 5149:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5150:   $namespace=~s/\//\_/g;
                   5151:   $namespace=~s/\W//g;
                   5152: 
1.620     albertel 5153:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5154:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5155:   if ($domain eq 'public' && $stuname eq 'public') {
                   5156:       $stuname=$ENV{'REMOTE_ADDR'};
                   5157:   }
1.1117    foxr     5158:   my $path=LONCAPA::tempdir();
1.168     albertel 5159:   my %hash;
                   5160:   if (tie(%hash,'GDBM_File',
                   5161: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5162: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5163:     foreach my $key (keys(%hash)) {
1.180     albertel 5164:       if ($key=~ /:$symb/) {
1.168     albertel 5165: 	delete($hash{$key});
                   5166:       }
                   5167:     }
                   5168:   }
                   5169: }
                   5170: 
1.167     albertel 5171: sub tmpstore {
1.168     albertel 5172:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5173: 
                   5174:   if (!$symb) {
                   5175:     $symb=&symbread();
1.620     albertel 5176:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5177:   }
                   5178:   $symb=escape($symb);
                   5179: 
                   5180:   if (!$namespace) {
                   5181:     # I don't think we would ever want to store this for a course.
                   5182:     # it seems this will only be used if we don't have a course.
1.620     albertel 5183:     #$namespace=$env{'request.course.id'};
1.168     albertel 5184:     #if (!$namespace) {
1.620     albertel 5185:       $namespace=$env{'request.state'};
1.168     albertel 5186:     #}
                   5187:   }
                   5188:   $namespace=~s/\//\_/g;
                   5189:   $namespace=~s/\W//g;
1.620     albertel 5190:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5191:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5192:   if ($domain eq 'public' && $stuname eq 'public') {
                   5193:       $stuname=$ENV{'REMOTE_ADDR'};
                   5194:   }
1.168     albertel 5195:   my $now=time;
                   5196:   my %hash;
1.1117    foxr     5197:   my $path=LONCAPA::tempdir();
1.168     albertel 5198:   if (tie(%hash,'GDBM_File',
                   5199: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5200: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5201:     $hash{"version:$symb"}++;
                   5202:     my $version=$hash{"version:$symb"};
                   5203:     my $allkeys=''; 
                   5204:     foreach my $key (keys(%$storehash)) {
                   5205:       $allkeys.=$key.':';
1.591     albertel 5206:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5207:     }
                   5208:     $hash{"$version:$symb:timestamp"}=$now;
                   5209:     $allkeys.='timestamp';
                   5210:     $hash{"$version:keys:$symb"}=$allkeys;
                   5211:     if (untie(%hash)) {
                   5212:       return 'ok';
                   5213:     } else {
                   5214:       return "error:$!";
                   5215:     }
                   5216:   } else {
                   5217:     return "error:$!";
                   5218:   }
                   5219: }
1.167     albertel 5220: 
1.168     albertel 5221: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5222: 
1.168     albertel 5223: sub tmprestore {
                   5224:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5225: 
1.168     albertel 5226:   if (!$symb) {
                   5227:     $symb=&symbread();
1.620     albertel 5228:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5229:   }
                   5230:   $symb=escape($symb);
                   5231: 
1.620     albertel 5232:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5233: 
1.620     albertel 5234:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5235:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5236:   if ($domain eq 'public' && $stuname eq 'public') {
                   5237:       $stuname=$ENV{'REMOTE_ADDR'};
                   5238:   }
1.168     albertel 5239:   my %returnhash;
                   5240:   $namespace=~s/\//\_/g;
                   5241:   $namespace=~s/\W//g;
                   5242:   my %hash;
1.1117    foxr     5243:   my $path=LONCAPA::tempdir();
1.168     albertel 5244:   if (tie(%hash,'GDBM_File',
                   5245: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5246: 	  &GDBM_READER(),0640)) {
1.168     albertel 5247:     my $version=$hash{"version:$symb"};
                   5248:     $returnhash{'version'}=$version;
                   5249:     my $scope;
                   5250:     for ($scope=1;$scope<=$version;$scope++) {
                   5251:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5252:       my @keys=split(/:/,$vkeys);
                   5253:       my $key;
                   5254:       $returnhash{"$scope:keys"}=$vkeys;
                   5255:       foreach $key (@keys) {
1.591     albertel 5256: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5257: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5258:       }
                   5259:     }
1.168     albertel 5260:     if (!(untie(%hash))) {
                   5261:       return "error:$!";
                   5262:     }
                   5263:   } else {
                   5264:     return "error:$!";
                   5265:   }
                   5266:   return %returnhash;
1.167     albertel 5267: }
                   5268: 
1.9       www      5269: # ----------------------------------------------------------------------- Store
                   5270: 
                   5271: sub store {
1.1172.2.64  raeburn  5272:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5273:     my $home='';
                   5274: 
1.168     albertel 5275:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5276: 
1.213     www      5277:     $symb=&symbclean($symb);
1.122     albertel 5278:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5279: 
1.620     albertel 5280:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5281:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5282: 
                   5283:     &devalidate($symb,$stuname,$domain);
1.109     www      5284: 
                   5285:     $symb=escape($symb);
1.187     www      5286:     if (!$namespace) { 
1.620     albertel 5287:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5288:           return ''; 
                   5289:        } 
                   5290:     }
1.620     albertel 5291:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5292: 
                   5293:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5294:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5295: 
1.12      www      5296:     my $namevalue='';
1.800     albertel 5297:     foreach my $key (keys(%$storehash)) {
                   5298:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5299:     }
1.12      www      5300:     $namevalue=~s/\&$//;
1.187     www      5301:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5302:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5303: }
                   5304: 
1.47      www      5305: # -------------------------------------------------------------- Critical Store
                   5306: 
                   5307: sub cstore {
1.1172.2.64  raeburn  5308:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5309:     my $home='';
                   5310: 
1.168     albertel 5311:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5312: 
1.213     www      5313:     $symb=&symbclean($symb);
1.122     albertel 5314:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5315: 
1.620     albertel 5316:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5317:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5318: 
                   5319:     &devalidate($symb,$stuname,$domain);
1.109     www      5320: 
                   5321:     $symb=escape($symb);
1.187     www      5322:     if (!$namespace) { 
1.620     albertel 5323:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5324:           return ''; 
                   5325:        } 
                   5326:     }
1.620     albertel 5327:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5328: 
                   5329:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5330:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5331: 
1.47      www      5332:     my $namevalue='';
1.800     albertel 5333:     foreach my $key (keys(%$storehash)) {
                   5334:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5335:     }
1.47      www      5336:     $namevalue=~s/\&$//;
1.187     www      5337:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5338:     return critical
1.1172.2.64  raeburn  5339:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5340: }
                   5341: 
1.9       www      5342: # --------------------------------------------------------------------- Restore
                   5343: 
                   5344: sub restore {
1.124     www      5345:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5346:     my $home='';
                   5347: 
1.168     albertel 5348:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5349: 
1.122     albertel 5350:     if (!$symb) {
1.1172.2.26  raeburn  5351:         return if ($namespace eq 'courserequests');
                   5352:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5353:     } else {
1.1172.2.26  raeburn  5354:         unless ($namespace eq 'courserequests') {
                   5355:             $symb=&escape(&symbclean($symb));
                   5356:         }
1.122     albertel 5357:     }
1.188     www      5358:     if (!$namespace) { 
1.620     albertel 5359:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5360:           return ''; 
                   5361:        } 
                   5362:     }
1.620     albertel 5363:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5364:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5365:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5366:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5367: 
1.12      www      5368:     my %returnhash=();
1.800     albertel 5369:     foreach my $line (split(/\&/,$answer)) {
                   5370: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5371:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5372:     }
1.75      www      5373:     my $version;
                   5374:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5375:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5376:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5377:        }
1.75      www      5378:     }
1.13      www      5379:     return %returnhash;
1.34      www      5380: }
                   5381: 
                   5382: # ---------------------------------------------------------- Course Description
1.1118    foxr     5383: #
                   5384: #  
1.34      www      5385: 
                   5386: sub coursedescription {
1.731     albertel 5387:     my ($courseid,$args)=@_;
1.34      www      5388:     $courseid=~s/^\///;
1.49      www      5389:     $courseid=~s/\_/\//g;
1.34      www      5390:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5391:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5392:     my $normalid=$cdomain.'_'.$cnum;
                   5393:     # need to always cache even if we get errors otherwise we keep 
                   5394:     # trying and trying and trying to get the course description.
                   5395:     my %envhash=();
                   5396:     my %returnhash=();
1.731     albertel 5397:     
                   5398:     my $expiretime=600;
                   5399:     if ($env{'request.course.id'} eq $normalid) {
                   5400: 	$expiretime=120;
                   5401:     }
                   5402: 
                   5403:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5404:     if (!$args->{'freshen_cache'}
                   5405: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5406: 	foreach my $key (keys(%env)) {
                   5407: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5408: 	    my ($setting) = $1;
                   5409: 	    $returnhash{$setting} = $env{$key};
                   5410: 	}
                   5411: 	return %returnhash;
                   5412:     }
                   5413: 
1.1118    foxr     5414:     # get the data again
                   5415: 
1.731     albertel 5416:     if (!$args->{'one_time'}) {
                   5417: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5418:     }
1.811     albertel 5419: 
1.34      www      5420:     if ($chome ne 'no_host') {
1.302     albertel 5421:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5422:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5423: 	   my $username = $env{'user.name'}; # Defult username
                   5424: 	   if(defined $args->{'user'}) {
                   5425: 	       $username = $args->{'user'};
                   5426: 	   }
1.129     albertel 5427:            $returnhash{'home'}= $chome;
                   5428: 	   $returnhash{'domain'} = $cdomain;
                   5429: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5430:            if (!defined($returnhash{'type'})) {
                   5431:                $returnhash{'type'} = 'Course';
                   5432:            }
1.130     albertel 5433:            while (my ($name,$value) = each %returnhash) {
1.53      www      5434:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5435:            }
1.270     www      5436:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5437:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5438: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5439:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5440:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5441:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5442:        }
                   5443:     }
1.731     albertel 5444:     if (!$args->{'one_time'}) {
1.949     raeburn  5445: 	&appenv(\%envhash);
1.731     albertel 5446:     }
1.302     albertel 5447:     return %returnhash;
1.461     www      5448: }
                   5449: 
1.1080    raeburn  5450: sub update_released_required {
                   5451:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5452:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5453:         $cid = $env{'request.course.id'};
                   5454:         $cdom = $env{'course.'.$cid.'.domain'};
                   5455:         $cnum = $env{'course.'.$cid.'.num'};
                   5456:         $chome = $env{'course.'.$cid.'.home'};
                   5457:     }
                   5458:     if ($needsrelease) {
                   5459:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5460:         my $needsupdate;
                   5461:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5462:             $needsupdate = 1;
                   5463:         } else {
                   5464:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5465:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5466:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5467:                 $needsupdate = 1;
                   5468:             }
                   5469:         }
                   5470:         if ($needsupdate) {
                   5471:             my %needshash = (
                   5472:                              'internal.releaserequired' => $needsrelease,
                   5473:                             );
                   5474:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5475:             if ($putresult eq 'ok') {
                   5476:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5477:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5478:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5479:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5480:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5481:                 }
                   5482:             }
                   5483:         }
                   5484:     }
                   5485:     return;
                   5486: }
                   5487: 
1.461     www      5488: # -------------------------------------------------See if a user is privileged
                   5489: 
                   5490: sub privileged {
1.1172.2.23  raeburn  5491:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5492:     my $now = time;
1.1172.2.23  raeburn  5493:     my $roles;
                   5494:     if (ref($possroles) eq 'ARRAY') {
                   5495:         $roles = $possroles;
                   5496:     } else {
                   5497:         $roles = ['dc','su'];
                   5498:     }
                   5499:     if (ref($possdomains) eq 'ARRAY') {
                   5500:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5501:         foreach my $dom (@{$possdomains}) {
                   5502:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5503:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5504:                 foreach my $role (@{$roles}) {
                   5505:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5506:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5507:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5508:                             return 1 unless (($end && $end < $now) ||
                   5509:                                              ($start && $start > $now));
                   5510:                         }
                   5511:                     }
                   5512:                 }
                   5513:             }
                   5514:         }
                   5515:     } else {
                   5516:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5517:         my $now = time;
1.1170    droeschl 5518: 
1.1172.2.58  raeburn  5519:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5520:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  5521:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   5522:                 return 1 unless ($tend && $tend < $now)
                   5523:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5524:             }
1.1172.2.23  raeburn  5525:         }
                   5526:     }
1.461     www      5527:     return 0;
1.9       www      5528: }
1.1       albertel 5529: 
1.1172.2.23  raeburn  5530: sub privileged_by_domain {
                   5531:     my ($domains,$roles) = @_;
                   5532:     my %privileged = ();
                   5533:     my $cachetime = 60*60*24;
                   5534:     my $now = time;
                   5535:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5536:         return %privileged;
                   5537:     }
                   5538:     foreach my $dom (@{$domains}) {
                   5539:         next if (ref($privileged{$dom}) eq 'HASH');
                   5540:         my $needroles;
                   5541:         foreach my $role (@{$roles}) {
                   5542:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5543:             if (defined($cached)) {
                   5544:                 if (ref($result) eq 'HASH') {
                   5545:                     $privileged{$dom}{$role} = $result;
                   5546:                 }
                   5547:             } else {
                   5548:                 $needroles = 1;
                   5549:             }
                   5550:         }
                   5551:         if ($needroles) {
                   5552:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5553:             $privileged{$dom} = {};
                   5554:             foreach my $server (keys(%dompersonnel)) {
                   5555:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5556:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5557:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5558:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5559:                         next if ($end && $end < $now);
                   5560:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   5561:                             $dompersonnel{$server}{$item};
                   5562:                     }
                   5563:                 }
                   5564:             }
                   5565:             if (ref($privileged{$dom}) eq 'HASH') {
                   5566:                 foreach my $role (@{$roles}) {
                   5567:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5568:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5569:                     } else {
                   5570:                         my %hash = ();
                   5571:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5572:                     }
                   5573:                 }
                   5574:             }
                   5575:         }
                   5576:     }
                   5577:     return %privileged;
                   5578: }
                   5579: 
1.103     harris41 5580: # -------------------------------------------------------- Get user privileges
1.11      www      5581: 
                   5582: sub rolesinit {
1.1169    droeschl 5583:     my ($domain, $username) = @_;
                   5584:     my %userroles = ('user.login.time' => time);
                   5585:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5586: 
                   5587:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5588:     # also, blocking can be triggered by an activating timer
                   5589:     # it's saved in the user's %env.
                   5590:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5591:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5592:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5593:         %timerintchk, %timerintenv);
                   5594: 
1.1162    raeburn  5595:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5596:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5597:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5598:     }
1.1169    droeschl 5599: 
1.1162    raeburn  5600:     foreach my $key (keys(%timerinterval)) {
                   5601:         my ($cid,$rest) = split(/\0/,$key);
                   5602:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5603:     }
1.1169    droeschl 5604: 
1.11      www      5605:     my %allroles=();
1.1162    raeburn  5606:     my %allgroups=();
1.11      www      5607: 
1.1172.2.58  raeburn  5608:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5609:         my $role = $rolesdump{$area};
                   5610:         $area =~ s/\_\w\w$//;
                   5611: 
                   5612:         my ($trole, $tend, $tstart, $group_privs);
                   5613: 
                   5614:         if ($role =~ /^cr/) {
                   5615:         # Custom role, defined by a user 
                   5616:         # e.g., user.role.cr/msu/smith/mynewrole
                   5617:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5618:                 $trole = $1;
                   5619:                 ($tend, $tstart) = split('_', $2);
                   5620:             } else {
                   5621:                 $trole = $role;
                   5622:             }
                   5623:         } elsif ($role =~ m|^gr/|) {
                   5624:         # Role of member in a group, defined within a course/community
                   5625:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5626:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5627:             next if $tstart eq '-1';
                   5628:             ($trole, $group_privs) = split(/\//, $trole);
                   5629:             $group_privs = &unescape($group_privs);
                   5630:         } else {
                   5631:         # Just a normal role, defined in roles.tab
                   5632:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5633:         }
                   5634: 
                   5635:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5636:                  $username);
                   5637:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5638: 
                   5639:         # role expired or not available yet?
                   5640:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5641:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5642: 
                   5643:         next if $area eq '' or $trole eq '';
                   5644: 
                   5645:         my $spec = "$trole.$area";
                   5646:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5647: 
                   5648:         if ($trole =~ /^cr\//) {
                   5649:         # Custom role, defined by a user
                   5650:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5651:         } elsif ($trole eq 'gr') {
                   5652:         # Role of a member in a group, defined within a course/community
                   5653:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5654:             next;
                   5655:         } else {
                   5656:         # Normal role, defined in roles.tab
                   5657:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5658:         }
                   5659: 
                   5660:         my $cid = $tdomain.'_'.$trest;
                   5661:         unless ($firstaccchk{$cid}) {
                   5662:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5663:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5664:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5665:                         $coursetimerstarts{$cid}{$item}; 
                   5666:                 }
                   5667:             }
                   5668:             $firstaccchk{$cid} = 1;
                   5669:         }
                   5670:         unless ($timerintchk{$cid}) {
                   5671:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5672:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5673:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5674:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5675:                 }
1.12      www      5676:             }
1.1169    droeschl 5677:             $timerintchk{$cid} = 1;
1.191     harris41 5678:         }
1.11      www      5679:     }
1.1169    droeschl 5680: 
1.1172.2.91  raeburn  5681:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   5682:                                                           \%allroles, \%allgroups);
1.1169    droeschl 5683:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  5684:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 5685: 
1.1162    raeburn  5686:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5687: }
                   5688: 
1.567     raeburn  5689: sub set_arearole {
1.1172.2.19  raeburn  5690:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5691:     unless ($nolog) {
1.567     raeburn  5692: # log the associated role with the area
1.1172.2.19  raeburn  5693:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5694:     }
1.743     albertel 5695:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5696: }
                   5697: 
                   5698: sub custom_roleprivs {
                   5699:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5700:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  5701:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5702:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5703:         my ($rdummy,$roledef)=
                   5704:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5705:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5706:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5707:             if (defined($syspriv)) {
1.1043    raeburn  5708:                 if ($trest =~ /^$match_community$/) {
                   5709:                     $syspriv =~ s/bre\&S//; 
                   5710:                 }
1.567     raeburn  5711:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5712:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5713:             }
                   5714:             if ($tdomain ne '') {
                   5715:                 if (defined($dompriv)) {
                   5716:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5717:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5718:                 }
                   5719:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  5720:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   5721:                         my $rolename = $1;
                   5722:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   5723:                     }
1.567     raeburn  5724:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5725:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5726:                 }
                   5727:             }
                   5728:         }
                   5729:     }
                   5730: }
                   5731: 
1.1172.2.89  raeburn  5732: sub course_adhocrole_privs {
                   5733:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   5734:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   5735:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   5736:         my (%currprivs,%storeprivs);
                   5737:         foreach my $item (split(/:/,$coursepriv)) {
                   5738:             my ($priv,$restrict) = split(/\&/,$item);
                   5739:             $currprivs{$priv} = $restrict;
                   5740:         }
                   5741:         my (%possadd,%possremove,%full);
                   5742:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   5743:             my ($priv,$restrict)=split(/\&/,$item);
                   5744:             $full{$priv} = $restrict;
                   5745:         }
                   5746:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   5747:              next if ($item eq '');
                   5748:              my ($rule,$rest) = split(/=/,$item);
                   5749:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   5750:              foreach my $priv (split(/:/,$rest)) {
                   5751:                  if ($priv ne '') {
                   5752:                      if ($rule eq 'off') {
                   5753:                          $possremove{$priv} = 1;
                   5754:                      } else {
                   5755:                          $possadd{$priv} = 1;
                   5756:                      }
                   5757:                  }
                   5758:              }
                   5759:          }
                   5760:          foreach my $priv (sort(keys(%full))) {
                   5761:              if (exists($currprivs{$priv})) {
                   5762:                  unless (exists($possremove{$priv})) {
                   5763:                      $storeprivs{$priv} = $currprivs{$priv};
                   5764:                  }
                   5765:              } elsif (exists($possadd{$priv})) {
                   5766:                  $storeprivs{$priv} = $full{$priv};
                   5767:              }
                   5768:          }
                   5769:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   5770:      }
                   5771:      return $coursepriv;
                   5772: }
                   5773: 
1.678     raeburn  5774: sub group_roleprivs {
                   5775:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5776:     my $access = 1;
                   5777:     my $now = time;
                   5778:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5779:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5780:     if ($access) {
1.811     albertel 5781:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5782:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5783:     }
                   5784: }
1.567     raeburn  5785: 
                   5786: sub standard_roleprivs {
                   5787:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5788:     if (defined($pr{$trole.':s'})) {
                   5789:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5790:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5791:     }
                   5792:     if ($tdomain ne '') {
                   5793:         if (defined($pr{$trole.':d'})) {
                   5794:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5795:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5796:         }
                   5797:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5798:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5799:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5800:         }
                   5801:     }
                   5802: }
                   5803: 
                   5804: sub set_userprivs {
1.1064    raeburn  5805:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5806:     my $author=0;
                   5807:     my $adv=0;
1.1172.2.91  raeburn  5808:     my $rar=0;
1.678     raeburn  5809:     my %grouproles = ();
                   5810:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5811:         my @groupkeys; 
1.1000    raeburn  5812:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5813:             push(@groupkeys,$role);
                   5814:         }
                   5815:         if (ref($groups_roles) eq 'HASH') {
                   5816:             foreach my $key (keys(%{$groups_roles})) {
                   5817:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5818:                     push(@groupkeys,$key);
                   5819:                 }
                   5820:             }
                   5821:         }
                   5822:         if (@groupkeys > 0) {
                   5823:             foreach my $role (@groupkeys) {
                   5824:                 my ($trole,$area,$sec,$extendedarea);
                   5825:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5826:                     $trole = $1;
                   5827:                     $area = $2;
                   5828:                     $sec = $3;
                   5829:                     $extendedarea = $area.$sec;
                   5830:                     if (exists($$allgroups{$area})) {
                   5831:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5832:                             my $spec = $trole.'.'.$extendedarea;
                   5833:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5834:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5835:                         }
1.678     raeburn  5836:                     }
                   5837:                 }
                   5838:             }
                   5839:         }
                   5840:     }
1.800     albertel 5841:     foreach my $group (keys(%grouproles)) {
                   5842:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5843:     }
1.800     albertel 5844:     foreach my $role (keys(%{$allroles})) {
                   5845:         my %thesepriv;
1.941     raeburn  5846:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5847:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5848:             if ($item ne '') {
                   5849:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5850:                 if ($restrictions eq '') {
                   5851:                     $thesepriv{$privilege}='F';
                   5852:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5853:                     $thesepriv{$privilege}.=$restrictions;
                   5854:                 }
                   5855:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  5856:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  5857:             }
                   5858:         }
                   5859:         my $thesestr='';
1.1104    raeburn  5860:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5861: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5862: 	}
                   5863:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5864:     }
1.1172.2.91  raeburn  5865:     return ($author,$adv,$rar);
1.567     raeburn  5866: }
                   5867: 
1.994     raeburn  5868: sub role_status {
1.1104    raeburn  5869:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5870:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  5871:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5872:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5873:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  5874:             $$where = '/'.$two;
1.994     raeburn  5875:             $$trolecode=$$role.'.'.$$where;
                   5876:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5877:             $$tstatus='is';
1.1104    raeburn  5878:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5879:                 $$tstatus='future';
1.1034    raeburn  5880:                 if ($$tstart<$now) {
                   5881:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5882:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5883:                             my (%allroles,%allgroups,$group_privs,
                   5884:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5885:                             my %userroles = (
                   5886:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5887:                             );
1.1064    raeburn  5888:                             @rolecodes = ('cm'); 
1.1002    raeburn  5889:                             my $spec=$$role.'.'.$$where;
                   5890:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5891:                             if ($$role =~ /^cr\//) {
                   5892:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5893:                                 push(@rolecodes,'cr');
1.1002    raeburn  5894:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5895:                                 push(@rolecodes,$$role);
1.1002    raeburn  5896:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5897:                                                     $env{'user.name'});
1.1064    raeburn  5898:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5899:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5900:                                 $group_privs = &unescape($group_privs);
                   5901:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5902:                                 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  5903:                                 &get_groups_roles($tdomain,$trest,
                   5904:                                                   \%course_roles,\@rolecodes,
                   5905:                                                   \%groups_roles);
1.1002    raeburn  5906:                             } else {
1.1064    raeburn  5907:                                 push(@rolecodes,$$role);
1.1002    raeburn  5908:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5909:                             }
1.1172.2.91  raeburn  5910:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   5911:                                                                    \%groups_roles);
1.1064    raeburn  5912:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  5913:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  5914:                         }
                   5915:                     }
1.1034    raeburn  5916:                     $$tstatus = 'is';
1.1002    raeburn  5917:                 }
1.994     raeburn  5918:             }
                   5919:             if ($$tend) {
1.1104    raeburn  5920:                 if ($$tend<$update) {
1.994     raeburn  5921:                     $$tstatus='expired';
                   5922:                 } elsif ($$tend<$now) {
                   5923:                     $$tstatus='will_not';
                   5924:                 }
                   5925:             }
                   5926:         }
                   5927:     }
                   5928: }
                   5929: 
1.1104    raeburn  5930: sub get_groups_roles {
                   5931:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5932:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5933:                   (ref($rolecodes) eq 'ARRAY') && 
                   5934:                   (ref($groups_roles) eq 'HASH')); 
                   5935:     if (keys(%{$cdom_courseroles}) > 0) {
                   5936:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5937:         if ($cdom ne '' && $cnum ne '') {
                   5938:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5939:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5940:                     my $crsrole = $1;
                   5941:                     my $crssec = $2;
                   5942:                     if ($crsrole =~ /^cr/) {
                   5943:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5944:                             push(@{$rolecodes},'cr');
                   5945:                         }
                   5946:                     } else {
                   5947:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5948:                             push(@{$rolecodes},$crsrole);
                   5949:                         }
                   5950:                     }
                   5951:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5952:                     if ($crssec ne '') {
                   5953:                         $rolekey .= "/$crssec";
                   5954:                     }
                   5955:                     $rolekey .= './';
                   5956:                     $groups_roles->{$rolekey} = $rolecodes;
                   5957:                 }
                   5958:             }
                   5959:         }
                   5960:     }
                   5961:     return;
                   5962: }
                   5963: 
                   5964: sub delete_env_groupprivs {
                   5965:     my ($where,$courseroles,$possroles) = @_;
                   5966:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5967:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5968:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5969:         %{$courseroles->{$udom}} =
                   5970:             &get_my_roles('','','userroles',['active'],
                   5971:                           $possroles,[$udom],1);
                   5972:     }
                   5973:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5974:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5975:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5976:             my $area = '/'.$cdom.'/'.$cnum;
                   5977:             my $privkey = "user.priv.$crsrole.$area";
                   5978:             if ($crssec ne '') {
                   5979:                 $privkey .= '/'.$crssec;
                   5980:             }
                   5981:             $privkey .= ".$area/$group";
                   5982:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5983:         }
                   5984:     }
                   5985:     return;
                   5986: }
                   5987: 
1.994     raeburn  5988: sub check_adhoc_privs {
1.1172.2.86  raeburn  5989:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  5990:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  5991:     if ($sec) {
                   5992:         $cckey .= '/'.$sec;
                   5993:     }
1.1172.2.9  raeburn  5994:     my $setprivs;
1.994     raeburn  5995:     if ($env{$cckey}) {
                   5996:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5997:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5998:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  5999:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6000:             $setprivs = 1;
1.994     raeburn  6001:         }
                   6002:     } else {
1.1172.2.87  raeburn  6003:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6004:         $setprivs = 1;
1.994     raeburn  6005:     }
1.1172.2.9  raeburn  6006:     return $setprivs;
1.994     raeburn  6007: }
                   6008: 
                   6009: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6010: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6011:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6012:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6013:     if ($sec ne '') {
                   6014:         $area .= '/'.$sec;
                   6015:     }
1.994     raeburn  6016:     my $spec = $role.'.'.$area;
                   6017:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6018:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6019:     my %rolehash = ();
1.1172.2.89  raeburn  6020:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6021:         my $rolename = $1;
1.1172.2.84  raeburn  6022:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6023:         my %domdef = &get_domain_defaults($dcdom);
                   6024:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6025:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6026:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6027:             }
                   6028:         }
1.1172.2.84  raeburn  6029:     } else {
                   6030:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6031:     }
1.1172.2.91  raeburn  6032:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6033:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6034:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6035:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6036:         &appenv( {'request.role'        => $spec,
                   6037:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6038:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6039:                  }
                   6040:                );
                   6041:         my $tadv=0;
                   6042:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6043:         &appenv({'request.role.adv'    => $tadv});
                   6044:     }
1.994     raeburn  6045: }
                   6046: 
1.12      www      6047: # --------------------------------------------------------------- get interface
                   6048: 
                   6049: sub get {
1.131     albertel 6050:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6051:    my $items='';
1.800     albertel 6052:    foreach my $item (@$storearr) {
                   6053:        $items.=&escape($item).'&';
1.191     harris41 6054:    }
1.12      www      6055:    $items=~s/\&$//;
1.620     albertel 6056:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6057:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6058:    my $uhome=&homeserver($uname,$udomain);
                   6059: 
1.133     albertel 6060:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6061:    my @pairs=split(/\&/,$rep);
1.273     albertel 6062:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6063:      return @pairs;
                   6064:    }
1.15      www      6065:    my %returnhash=();
1.42      www      6066:    my $i=0;
1.800     albertel 6067:    foreach my $item (@$storearr) {
                   6068:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6069:       $i++;
1.191     harris41 6070:    }
1.15      www      6071:    return %returnhash;
1.27      www      6072: }
                   6073: 
                   6074: # --------------------------------------------------------------- del interface
                   6075: 
                   6076: sub del {
1.133     albertel 6077:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6078:    my $items='';
1.800     albertel 6079:    foreach my $item (@$storearr) {
                   6080:        $items.=&escape($item).'&';
1.191     harris41 6081:    }
1.984     neumanie 6082: 
1.27      www      6083:    $items=~s/\&$//;
1.620     albertel 6084:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6085:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6086:    my $uhome=&homeserver($uname,$udomain);
                   6087:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6088: }
                   6089: 
                   6090: # -------------------------------------------------------------- dump interface
                   6091: 
1.1172.2.22  raeburn  6092: sub unserialize {
                   6093:     my ($rep, $escapedkeys) = @_;
                   6094: 
                   6095:     return {} if $rep =~ /^error/;
                   6096: 
                   6097:     my %returnhash=();
                   6098:     foreach my $item (split(/\&/,$rep)) {
                   6099:         my ($key, $value) = split(/=/, $item, 2);
                   6100:         $key = unescape($key) unless $escapedkeys;
                   6101:         next if $key =~ /^error: 2 /;
                   6102:         $returnhash{$key} = &thaw_unescape($value);
                   6103:     }
                   6104:     return \%returnhash;
                   6105: }
                   6106: 
                   6107: # see Lond::dump_with_regexp
                   6108: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6109: sub dump {
1.1172.2.22  raeburn  6110:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6111:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6112:     if (!$uname) { $uname=$env{'user.name'}; }
                   6113:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6114: 
1.1172.2.55  raeburn  6115:     if ($regexp) {
                   6116:         $regexp=&escape($regexp);
                   6117:     } else {
                   6118:         $regexp='.';
                   6119:     }
1.1172.2.22  raeburn  6120:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6121:         # user is hosted on this machine
1.1172.2.55  raeburn  6122:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6123:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6124:         return %{&unserialize($reply, $escapedkeys)};
                   6125:     }
1.1166    raeburn  6126:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6127:     my @pairs=split(/\&/,$rep);
                   6128:     my %returnhash=();
1.1098    foxr     6129:     if (!($rep =~ /^error/ )) {
                   6130: 	foreach my $item (@pairs) {
                   6131: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6132:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6133: 	    next if ($key =~ /^error: 2 /);
                   6134: 	    $returnhash{$key}=&thaw_unescape($value);
                   6135: 	}
1.755     albertel 6136:     }
                   6137:     return %returnhash;
1.407     www      6138: }
                   6139: 
1.1098    foxr     6140: 
1.717     albertel 6141: # --------------------------------------------------------- dumpstore interface
                   6142: 
                   6143: sub dumpstore {
                   6144:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6145:    # same as dump but keys must be escaped. They may contain colon separated
                   6146:    # lists of values that may themself contain colons (e.g. symbs).
                   6147:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6148: }
                   6149: 
1.407     www      6150: # -------------------------------------------------------------- keys interface
                   6151: 
                   6152: sub getkeys {
                   6153:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6154:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6155:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6156:    my $uhome=&homeserver($uname,$udomain);
                   6157:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6158:    my @keyarray=();
1.800     albertel 6159:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6160:       next if ($key =~ /^error: 2 /);
1.800     albertel 6161:       push(@keyarray,&unescape($key));
1.407     www      6162:    }
                   6163:    return @keyarray;
1.318     matthew  6164: }
                   6165: 
1.319     matthew  6166: # --------------------------------------------------------------- currentdump
                   6167: sub currentdump {
1.328     matthew  6168:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6169:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6170:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6171:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6172:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6173:    my $rep;
                   6174: 
                   6175:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6176:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6177:                    $courseid)));
                   6178:    } else {
                   6179:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6180:    }
                   6181: 
1.318     matthew  6182:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6183:    #
1.318     matthew  6184:    my %returnhash=();
1.319     matthew  6185:    #
1.1172.2.93.2  1(raebur 6186:7):    if ($rep eq 'unknown_cmd') {
1.319     matthew  6187:        # an old lond will not know currentdump
                   6188:        # Do a dump and make it look like a currentdump
1.822     albertel 6189:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6190:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6191:        my %hash = @tmp;
                   6192:        @tmp=();
1.424     matthew  6193:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6194:    } else {
                   6195:        my @pairs=split(/\&/,$rep);
1.800     albertel 6196:        foreach my $pair (@pairs) {
                   6197:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6198:            my ($symb,$param) = split(/:/,$key);
                   6199:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6200:                                                         &thaw_unescape($value);
1.319     matthew  6201:        }
1.191     harris41 6202:    }
1.12      www      6203:    return %returnhash;
1.424     matthew  6204: }
                   6205: 
                   6206: sub convert_dump_to_currentdump{
                   6207:     my %hash = %{shift()};
                   6208:     my %returnhash;
                   6209:     # Code ripped from lond, essentially.  The only difference
                   6210:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6211:     # we might run in to problems with parameter names =~ /^v\./
                   6212:     while (my ($key,$value) = each(%hash)) {
                   6213:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6214: 	$symb  = &unescape($symb);
                   6215: 	$param = &unescape($param);
1.424     matthew  6216:         next if ($v eq 'version' || $symb eq 'keys');
                   6217:         next if (exists($returnhash{$symb}) &&
                   6218:                  exists($returnhash{$symb}->{$param}) &&
                   6219:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6220:         $returnhash{$symb}->{$param}=$value;
                   6221:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6222:     }
                   6223:     #
                   6224:     # Remove all of the keys in the hashes which keep track of
                   6225:     # the version of the parameter.
                   6226:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6227:         # use a foreach because we are going to delete from the hash.
                   6228:         foreach my $key (keys(%$param_hash)) {
                   6229:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6230:         }
                   6231:     }
                   6232:     return \%returnhash;
1.12      www      6233: }
                   6234: 
1.627     albertel 6235: # ------------------------------------------------------ critical inc interface
                   6236: 
                   6237: sub cinc {
                   6238:     return &inc(@_,'critical');
                   6239: }
                   6240: 
1.449     matthew  6241: # --------------------------------------------------------------- inc interface
                   6242: 
                   6243: sub inc {
1.627     albertel 6244:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6245:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6246:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6247:     my $uhome=&homeserver($uname,$udomain);
                   6248:     my $items='';
                   6249:     if (! ref($store)) {
                   6250:         # got a single value, so use that instead
                   6251:         $items = &escape($store).'=&';
                   6252:     } elsif (ref($store) eq 'SCALAR') {
                   6253:         $items = &escape($$store).'=&';        
                   6254:     } elsif (ref($store) eq 'ARRAY') {
                   6255:         $items = join('=&',map {&escape($_);} @{$store});
                   6256:     } elsif (ref($store) eq 'HASH') {
                   6257:         while (my($key,$value) = each(%{$store})) {
                   6258:             $items.= &escape($key).'='.&escape($value).'&';
                   6259:         }
                   6260:     }
                   6261:     $items=~s/\&$//;
1.627     albertel 6262:     if ($critical) {
                   6263: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6264:     } else {
                   6265: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6266:     }
1.449     matthew  6267: }
                   6268: 
1.12      www      6269: # --------------------------------------------------------------- put interface
                   6270: 
                   6271: sub put {
1.134     albertel 6272:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6273:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6274:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6275:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6276:    my $items='';
1.800     albertel 6277:    foreach my $item (keys(%$storehash)) {
                   6278:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6279:    }
1.12      www      6280:    $items=~s/\&$//;
1.134     albertel 6281:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6282: }
                   6283: 
1.631     albertel 6284: # ------------------------------------------------------------ newput interface
                   6285: 
                   6286: sub newput {
                   6287:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6288:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6289:    if (!$uname) { $uname=$env{'user.name'}; }
                   6290:    my $uhome=&homeserver($uname,$udomain);
                   6291:    my $items='';
                   6292:    foreach my $key (keys(%$storehash)) {
                   6293:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6294:    }
                   6295:    $items=~s/\&$//;
                   6296:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6297: }
                   6298: 
                   6299: # ---------------------------------------------------------  putstore interface
                   6300: 
1.524     raeburn  6301: sub putstore {
1.1172.2.59  raeburn  6302:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6303:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6304:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6305:    my $uhome=&homeserver($uname,$udomain);
                   6306:    my $items='';
1.715     albertel 6307:    foreach my $key (keys(%$storehash)) {
                   6308:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6309:    }
1.715     albertel 6310:    $items=~s/\&$//;
1.716     albertel 6311:    my $esc_symb=&escape($symb);
                   6312:    my $esc_v=&escape($version);
1.715     albertel 6313:    my $reply =
1.716     albertel 6314:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6315: 	      $uhome);
1.1172.2.59  raeburn  6316:    if (($tolog) && ($reply eq 'ok')) {
                   6317:        my $namevalue='';
                   6318:        foreach my $key (keys(%{$storehash})) {
                   6319:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6320:        }
                   6321:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6322:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6323:                      '&version='.$esc_v.
                   6324:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6325:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6326:    }
1.715     albertel 6327:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6328:        # gfall back to way things use to be done
1.715     albertel 6329:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6330: 			    $uname);
1.524     raeburn  6331:    }
1.715     albertel 6332:    return $reply;
                   6333: }
                   6334: 
                   6335: sub old_putstore {
1.716     albertel 6336:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6337:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6338:     if (!$uname) { $uname=$env{'user.name'}; }
                   6339:     my $uhome=&homeserver($uname,$udomain);
                   6340:     my %newstorehash;
1.800     albertel 6341:     foreach my $item (keys(%$storehash)) {
                   6342: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6343: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6344:     }
                   6345:     my $items='';
                   6346:     my %allitems = ();
1.800     albertel 6347:     foreach my $item (keys(%newstorehash)) {
                   6348: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6349: 	    my $key = $1.':keys:'.$2;
                   6350: 	    $allitems{$key} .= $3.':';
                   6351: 	}
1.800     albertel 6352: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6353:     }
1.800     albertel 6354:     foreach my $item (keys(%allitems)) {
                   6355: 	$allitems{$item} =~ s/\:$//;
                   6356: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6357:     }
                   6358:     $items=~s/\&$//;
                   6359:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6360: }
                   6361: 
1.47      www      6362: # ------------------------------------------------------ critical put interface
                   6363: 
                   6364: sub cput {
1.134     albertel 6365:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6366:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6367:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6368:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6369:    my $items='';
1.800     albertel 6370:    foreach my $item (keys(%$storehash)) {
                   6371:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6372:    }
1.47      www      6373:    $items=~s/\&$//;
1.134     albertel 6374:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6375: }
                   6376: 
                   6377: # -------------------------------------------------------------- eget interface
                   6378: 
                   6379: sub eget {
1.133     albertel 6380:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6381:    my $items='';
1.800     albertel 6382:    foreach my $item (@$storearr) {
                   6383:        $items.=&escape($item).'&';
1.191     harris41 6384:    }
1.12      www      6385:    $items=~s/\&$//;
1.620     albertel 6386:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6387:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6388:    my $uhome=&homeserver($uname,$udomain);
                   6389:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6390:    my @pairs=split(/\&/,$rep);
                   6391:    my %returnhash=();
1.42      www      6392:    my $i=0;
1.800     albertel 6393:    foreach my $item (@$storearr) {
                   6394:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6395:       $i++;
1.191     harris41 6396:    }
1.12      www      6397:    return %returnhash;
                   6398: }
                   6399: 
1.667     albertel 6400: # ------------------------------------------------------------ tmpput interface
                   6401: sub tmpput {
1.802     raeburn  6402:     my ($storehash,$server,$context)=@_;
1.667     albertel 6403:     my $items='';
1.800     albertel 6404:     foreach my $item (keys(%$storehash)) {
                   6405: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6406:     }
                   6407:     $items=~s/\&$//;
1.802     raeburn  6408:     if (defined($context)) {
                   6409:         $items .= ':'.&escape($context);
                   6410:     }
1.667     albertel 6411:     return &reply("tmpput:$items",$server);
                   6412: }
                   6413: 
                   6414: # ------------------------------------------------------------ tmpget interface
                   6415: sub tmpget {
1.688     albertel 6416:     my ($token,$server)=@_;
                   6417:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6418:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6419:     my %returnhash;
1.1172.2.85  raeburn  6420:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6421:         return %returnhash;
                   6422:     }
1.667     albertel 6423:     foreach my $item (split(/\&/,$rep)) {
                   6424: 	my ($key,$value)=split(/=/,$item);
                   6425: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6426:     }
                   6427:     return %returnhash;
                   6428: }
                   6429: 
1.1113    raeburn  6430: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6431: sub tmpdel {
                   6432:     my ($token,$server)=@_;
                   6433:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6434:     return &reply("tmpdel:$token",$server);
                   6435: }
                   6436: 
1.1172.2.13  raeburn  6437: # ------------------------------------------------------------ get_timebased_id
                   6438: 
                   6439: sub get_timebased_id {
                   6440:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6441:         $maxtries) = @_;
                   6442:     my ($newid,$error,$dellock);
                   6443:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   6444:         return ('','ok','invalid call to get suffix');
                   6445:     }
                   6446: 
                   6447: # set defaults for any optional args for which values were not supplied
                   6448:     if ($who eq '') {
                   6449:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6450:     }
                   6451:     if (!$locktries) {
                   6452:         $locktries = 3;
                   6453:     }
                   6454:     if (!$maxtries) {
                   6455:         $maxtries = 10;
                   6456:     }
                   6457: 
                   6458:     if (($cdom eq '') || ($cnum eq '')) {
                   6459:         if ($env{'request.course.id'}) {
                   6460:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6461:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6462:         }
                   6463:         if (($cdom eq '') || ($cnum eq '')) {
                   6464:             return ('','ok','call to get suffix not in course context');
                   6465:         }
                   6466:     }
                   6467: 
                   6468: # construct locking item
                   6469:     my $lockhash = {
                   6470:                       $prefix."\0".'locked_'.$keyid => $who,
                   6471:                    };
                   6472:     my $tries = 0;
                   6473: 
                   6474: # attempt to get lock on nohist_$namespace file
                   6475:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6476:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6477:         $tries ++;
                   6478:         sleep 1;
                   6479:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6480:     }
                   6481: 
                   6482: # attempt to get unique identifier, based on current timestamp
                   6483:     if ($gotlock eq 'ok') {
                   6484:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6485:         my $id = time;
                   6486:         $newid = $id;
1.1172.2.56  raeburn  6487:         if ($idtype eq 'addcode') {
                   6488:             $newid .= &sixnum_code();
                   6489:         }
1.1172.2.13  raeburn  6490:         my $idtries = 0;
                   6491:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6492:             if ($idtype eq 'concat') {
                   6493:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  6494:             } elsif ($idtype eq 'addcode') {
                   6495:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  6496:             } else {
                   6497:                 $newid ++;
                   6498:             }
                   6499:             $idtries ++;
                   6500:         }
                   6501:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6502:             my %new_item =  (
                   6503:                               $prefix."\0".$newid => $who,
                   6504:                             );
                   6505:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6506:                                                  $cdom,$cnum);
                   6507:             if ($putresult ne 'ok') {
                   6508:                 undef($newid);
                   6509:                 $error = 'error saving new item: '.$putresult;
                   6510:             }
                   6511:         } else {
1.1172.2.56  raeburn  6512:              undef($newid);
1.1172.2.13  raeburn  6513:              $error = ('error: no unique suffix available for the new item ');
                   6514:         }
                   6515: #  remove lock
                   6516:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6517:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6518:     } else {
                   6519:         $error = "error: could not obtain lockfile\n";
                   6520:         $dellock = 'ok';
1.1172.2.58  raeburn  6521:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6522:             $dellock = 'nolock';
                   6523:         }
1.1172.2.13  raeburn  6524:     }
                   6525:     return ($newid,$dellock,$error);
                   6526: }
                   6527: 
1.1172.2.56  raeburn  6528: sub sixnum_code {
                   6529:     my $code;
                   6530:     for (0..6) {
                   6531:         $code .= int( rand(9) );
                   6532:     }
                   6533:     return $code;
                   6534: }
                   6535: 
1.765     albertel 6536: # -------------------------------------------------- portfolio access checking
                   6537: 
                   6538: sub portfolio_access {
1.1172.2.77  raeburn  6539:     my ($requrl,$clientip) = @_;
1.765     albertel 6540:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  6541:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6542:     if ($result) {
                   6543:         my %setters;
                   6544:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6545:             my ($startblock,$endblock) =
                   6546:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6547:             if ($startblock && $endblock) {
                   6548:                 return 'B';
                   6549:             }
                   6550:         } else {
                   6551:             my ($startblock,$endblock) =
                   6552:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6553:             if ($startblock && $endblock) {
                   6554:                 return 'B';
                   6555:             }
                   6556:         }
                   6557:     }
1.765     albertel 6558:     if ($result eq 'ok') {
1.766     albertel 6559:        return 'F';
1.765     albertel 6560:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6561:        return 'A';
1.765     albertel 6562:     }
1.766     albertel 6563:     return '';
1.765     albertel 6564: }
                   6565: 
                   6566: sub get_portfolio_access {
1.1172.2.77  raeburn  6567:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6568: 
                   6569:     if (!ref($access_hash)) {
                   6570: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6571: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6572: 						   $file_name);
                   6573: 	$access_hash = $access_controls{$file_name};
                   6574:     }
                   6575: 
1.1172.2.77  raeburn  6576:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6577:     my $now = time;
                   6578:     if (ref($access_hash) eq 'HASH') {
                   6579:         foreach my $key (keys(%{$access_hash})) {
                   6580:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6581:             if ($start > $now) {
                   6582:                 next;
                   6583:             }
                   6584:             if ($end && $end<$now) {
                   6585:                 next;
                   6586:             }
                   6587:             if ($scope eq 'public') {
                   6588:                 $public = $key;
                   6589:                 last;
                   6590:             } elsif ($scope eq 'guest') {
                   6591:                 $guest = $key;
                   6592:             } elsif ($scope eq 'domains') {
                   6593:                 push(@domains,$key);
                   6594:             } elsif ($scope eq 'users') {
                   6595:                 push(@users,$key);
                   6596:             } elsif ($scope eq 'course') {
                   6597:                 push(@courses,$key);
                   6598:             } elsif ($scope eq 'group') {
                   6599:                 push(@groups,$key);
1.1172.2.77  raeburn  6600:             } elsif ($scope eq 'ip') {
                   6601:                 push(@ips,$key);
1.765     albertel 6602:             }
                   6603:         }
                   6604:         if ($public) {
                   6605:             return 'ok';
1.1172.2.77  raeburn  6606:         } elsif (@ips > 0) {
                   6607:             my $allowed;
                   6608:             foreach my $ipkey (@ips) {
                   6609:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6610:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6611:                         $allowed = 1;
                   6612:                         last;
                   6613:                     }
                   6614:                 }
                   6615:             }
                   6616:             if ($allowed) {
                   6617:                 return 'ok';
                   6618:             }
1.765     albertel 6619:         }
                   6620:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6621:             if ($guest) {
                   6622:                 return $guest;
                   6623:             }
                   6624:         } else {
                   6625:             if (@domains > 0) {
                   6626:                 foreach my $domkey (@domains) {
                   6627:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6628:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6629:                             return 'ok';
                   6630:                         }
                   6631:                     }
                   6632:                 }
                   6633:             }
                   6634:             if (@users > 0) {
                   6635:                 foreach my $userkey (@users) {
1.865     raeburn  6636:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6637:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6638:                             if (ref($item) eq 'HASH') {
                   6639:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6640:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6641:                                     return 'ok';
                   6642:                                 }
                   6643:                             }
                   6644:                         }
                   6645:                     } 
1.765     albertel 6646:                 }
                   6647:             }
                   6648:             my %roleshash;
                   6649:             my @courses_and_groups = @courses;
                   6650:             push(@courses_and_groups,@groups); 
                   6651:             if (@courses_and_groups > 0) {
                   6652:                 my (%allgroups,%allroles); 
                   6653:                 my ($start,$end,$role,$sec,$group);
                   6654:                 foreach my $envkey (%env) {
1.1060    raeburn  6655:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6656:                         my $cid = $2.'_'.$3; 
                   6657:                         if ($1 eq 'gr') {
                   6658:                             $group = $4;
                   6659:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6660:                         } else {
                   6661:                             if ($4 eq '') {
                   6662:                                 $sec = 'none';
                   6663:                             } else {
                   6664:                                 $sec = $4;
                   6665:                             }
                   6666:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6667:                         }
1.811     albertel 6668:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6669:                         my $cid = $2.'_'.$3;
                   6670:                         if ($4 eq '') {
                   6671:                             $sec = 'none';
                   6672:                         } else {
                   6673:                             $sec = $4;
                   6674:                         }
                   6675:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6676:                     }
                   6677:                 }
                   6678:                 if (keys(%allroles) == 0) {
                   6679:                     return;
                   6680:                 }
                   6681:                 foreach my $key (@courses_and_groups) {
                   6682:                     my %content = %{$$access_hash{$key}};
                   6683:                     my $cnum = $content{'number'};
                   6684:                     my $cdom = $content{'domain'};
                   6685:                     my $cid = $cdom.'_'.$cnum;
                   6686:                     if (!exists($allroles{$cid})) {
                   6687:                         next;
                   6688:                     }    
                   6689:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6690:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6691:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6692:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6693:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6694:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6695:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6696:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6697:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6698:                                         if (grep/^all$/,@sections) {
                   6699:                                             return 'ok';
                   6700:                                         } else {
                   6701:                                             if (grep/^$sec$/,@sections) {
                   6702:                                                 return 'ok';
                   6703:                                             }
                   6704:                                         }
                   6705:                                     }
                   6706:                                 }
                   6707:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6708:                                     if (grep/^none$/,@groups) {
                   6709:                                         return 'ok';
                   6710:                                     }
                   6711:                                 } else {
                   6712:                                     if (grep/^all$/,@groups) {
                   6713:                                         return 'ok';
                   6714:                                     } 
                   6715:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6716:                                         if (grep/^$group$/,@groups) {
                   6717:                                             return 'ok';
                   6718:                                         }
                   6719:                                     }
                   6720:                                 } 
                   6721:                             }
                   6722:                         }
                   6723:                     }
                   6724:                 }
                   6725:             }
                   6726:             if ($guest) {
                   6727:                 return $guest;
                   6728:             }
                   6729:         }
                   6730:     }
                   6731:     return;
                   6732: }
                   6733: 
                   6734: sub course_group_datechecker {
                   6735:     my ($dates,$now,$status) = @_;
                   6736:     my ($start,$end) = split(/\./,$dates);
                   6737:     if (!$start && !$end) {
                   6738:         return 'ok';
                   6739:     }
                   6740:     if (grep/^active$/,@{$status}) {
                   6741:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6742:             return 'ok';
                   6743:         }
                   6744:     }
                   6745:     if (grep/^previous$/,@{$status}) {
                   6746:         if ($end > $now ) {
                   6747:             return 'ok';
                   6748:         }
                   6749:     }
                   6750:     if (grep/^future$/,@{$status}) {
                   6751:         if ($start > $now) {
                   6752:             return 'ok';
                   6753:         }
                   6754:     }
                   6755:     return; 
                   6756: }
                   6757: 
                   6758: sub parse_portfolio_url {
                   6759:     my ($url) = @_;
                   6760: 
                   6761:     my ($type,$udom,$unum,$group,$file_name);
                   6762:     
1.823     albertel 6763:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6764: 	$type = 1;
                   6765:         $udom = $1;
                   6766:         $unum = $2;
                   6767:         $file_name = $3;
1.823     albertel 6768:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6769: 	$type = 2;
                   6770:         $udom = $1;
                   6771:         $unum = $2;
                   6772:         $group = $3;
                   6773:         $file_name = $3.'/'.$4;
                   6774:     }
                   6775:     if (wantarray) {
                   6776: 	return ($type,$udom,$unum,$file_name,$group);
                   6777:     }
                   6778:     return $type;
                   6779: }
                   6780: 
                   6781: sub is_portfolio_url {
                   6782:     my ($url) = @_;
                   6783:     return scalar(&parse_portfolio_url($url));
                   6784: }
                   6785: 
1.798     raeburn  6786: sub is_portfolio_file {
                   6787:     my ($file) = @_;
1.820     raeburn  6788:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6789:         return 1;
                   6790:     }
                   6791:     return;
                   6792: }
                   6793: 
1.976     raeburn  6794: sub usertools_access {
1.1084    raeburn  6795:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6796:     my ($access,%tools);
                   6797:     if ($context eq '') {
                   6798:         $context = 'tools';
                   6799:     }
                   6800:     if ($context eq 'requestcourses') {
                   6801:         %tools = (
                   6802:                       official   => 1,
                   6803:                       unofficial => 1,
1.1006    raeburn  6804:                       community  => 1,
1.1172.2.37  raeburn  6805:                       textbook   => 1,
1.985     raeburn  6806:                  );
1.1172.2.9  raeburn  6807:     } elsif ($context eq 'requestauthor') {
                   6808:         %tools = (
                   6809:                       requestauthor => 1,
                   6810:                  );
1.985     raeburn  6811:     } else {
                   6812:         %tools = (
                   6813:                       aboutme   => 1,
                   6814:                       blog      => 1,
1.1172.2.6  raeburn  6815:                       webdav    => 1,
1.985     raeburn  6816:                       portfolio => 1,
                   6817:                  );
                   6818:     }
1.976     raeburn  6819:     return if (!defined($tools{$tool}));
                   6820: 
1.1172.2.35  raeburn  6821:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6822:         $udom = $env{'user.domain'};
                   6823:         $uname = $env{'user.name'};
                   6824:     }
                   6825: 
1.978     raeburn  6826:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6827:         if ($action ne 'reload') {
1.985     raeburn  6828:             if ($context eq 'requestcourses') {
                   6829:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  6830:             } elsif ($context eq 'requestauthor') {
                   6831:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6832:             } else {
                   6833:                 return $env{'environment.availabletools.'.$tool};
                   6834:             }
                   6835:         }
1.976     raeburn  6836:     }
                   6837: 
1.1172.2.9  raeburn  6838:     my ($toolstatus,$inststatus,$envkey);
                   6839:     if ($context eq 'requestauthor') {
                   6840:         $envkey = $context;
                   6841:     } else {
                   6842:         $envkey = $context.'.'.$tool;
                   6843:     }
1.976     raeburn  6844: 
1.985     raeburn  6845:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6846:          ($action ne 'reload')) {
1.1172.2.9  raeburn  6847:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6848:         $inststatus = $env{'environment.inststatus'};
                   6849:     } else {
1.1084    raeburn  6850:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  6851:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6852:             $inststatus = $userenvref->{'inststatus'};
                   6853:         } else {
1.1172.2.9  raeburn  6854:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6855:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6856:             $inststatus = $userenv{'inststatus'};
                   6857:         }
1.976     raeburn  6858:     }
                   6859: 
                   6860:     if ($toolstatus ne '') {
                   6861:         if ($toolstatus) {
                   6862:             $access = 1;
                   6863:         } else {
                   6864:             $access = 0;
                   6865:         }
                   6866:         return $access;
                   6867:     }
                   6868: 
1.1084    raeburn  6869:     my ($is_adv,%domdef);
                   6870:     if (ref($is_advref) eq 'HASH') {
                   6871:         $is_adv = $is_advref->{'is_adv'};
                   6872:     } else {
                   6873:         $is_adv = &is_advanced_user($udom,$uname);
                   6874:     }
                   6875:     if (ref($domdefref) eq 'HASH') {
                   6876:         %domdef = %{$domdefref};
                   6877:     } else {
                   6878:         %domdef = &get_domain_defaults($udom);
                   6879:     }
1.976     raeburn  6880:     if (ref($domdef{$tool}) eq 'HASH') {
                   6881:         if ($is_adv) {
                   6882:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6883:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6884:                     $access = 1;
                   6885:                 } else {
                   6886:                     $access = 0;
                   6887:                 }
                   6888:                 return $access;
                   6889:             }
                   6890:         }
                   6891:         if ($inststatus ne '') {
                   6892:             my ($hasaccess,$hasnoaccess);
                   6893:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6894:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6895:                     if ($domdef{$tool}{$affiliation}) {
                   6896:                         $hasaccess = 1;
                   6897:                     } else {
                   6898:                         $hasnoaccess = 1;
                   6899:                     }
                   6900:                 }
                   6901:             }
                   6902:             if ($hasaccess || $hasnoaccess) {
                   6903:                 if ($hasaccess) {
                   6904:                     $access = 1;
                   6905:                 } elsif ($hasnoaccess) {
                   6906:                     $access = 0; 
                   6907:                 }
                   6908:                 return $access;
                   6909:             }
                   6910:         } else {
                   6911:             if ($domdef{$tool}{'default'} ne '') {
                   6912:                 if ($domdef{$tool}{'default'}) {
                   6913:                     $access = 1;
                   6914:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6915:                     $access = 0;
                   6916:                 }
                   6917:                 return $access;
                   6918:             }
                   6919:         }
                   6920:     } else {
1.1172.2.6  raeburn  6921:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6922:             $access = 1;
                   6923:         } else {
                   6924:             $access = 0;
                   6925:         }
1.976     raeburn  6926:         return $access;
                   6927:     }
                   6928: }
                   6929: 
1.1050    raeburn  6930: sub is_course_owner {
                   6931:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6932:     if (($udom eq '') || ($uname eq '')) {
                   6933:         $udom = $env{'user.domain'};
                   6934:         $uname = $env{'user.name'};
                   6935:     }
                   6936:     unless (($udom eq '') || ($uname eq '')) {
                   6937:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6938:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6939:                 return 1;
                   6940:             } else {
                   6941:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6942:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6943:                     return 1;
                   6944:                 }
                   6945:             }
                   6946:         }
                   6947:     }
                   6948:     return;
                   6949: }
                   6950: 
1.976     raeburn  6951: sub is_advanced_user {
                   6952:     my ($udom,$uname) = @_;
1.1085    raeburn  6953:     if ($udom ne '' && $uname ne '') {
                   6954:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6955:             if (wantarray) {
                   6956:                 return ($env{'user.adv'},$env{'user.author'});
                   6957:             } else {
                   6958:                 return $env{'user.adv'};
                   6959:             }
1.1085    raeburn  6960:         }
                   6961:     }
1.976     raeburn  6962:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6963:     my %allroles;
1.1128    raeburn  6964:     my ($is_adv,$is_author);
1.976     raeburn  6965:     foreach my $role (keys(%roleshash)) {
                   6966:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6967:         my $area = '/'.$tdomain.'/'.$trest;
                   6968:         if ($sec ne '') {
                   6969:             $area .= '/'.$sec;
                   6970:         }
                   6971:         if (($area ne '') && ($trole ne '')) {
                   6972:             my $spec=$trole.'.'.$area;
                   6973:             if ($trole =~ /^cr\//) {
                   6974:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6975:             } elsif ($trole ne 'gr') {
                   6976:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6977:             }
1.1128    raeburn  6978:             if ($trole eq 'au') {
                   6979:                 $is_author = 1;
                   6980:             }
1.976     raeburn  6981:         }
                   6982:     }
                   6983:     foreach my $role (keys(%allroles)) {
                   6984:         last if ($is_adv);
                   6985:         foreach my $item (split(/:/,$allroles{$role})) {
                   6986:             if ($item ne '') {
                   6987:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6988:                 if ($privilege eq 'adv') {
                   6989:                     $is_adv = 1;
                   6990:                     last;
                   6991:                 }
                   6992:             }
                   6993:         }
                   6994:     }
1.1128    raeburn  6995:     if (wantarray) {
                   6996:         return ($is_adv,$is_author);
                   6997:     }
1.976     raeburn  6998:     return $is_adv;
                   6999: }
1.798     raeburn  7000: 
1.1035    raeburn  7001: sub check_can_request {
1.1036    raeburn  7002:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7003:     my $canreq = 0;
                   7004:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7005:     my @options = ('approval','validate','autolimit');
                   7006:     my $optregex = join('|',@options);
                   7007:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7008:         foreach my $type (@{$types}) {
                   7009:             if (&usertools_access($env{'user.name'},
                   7010:                                   $env{'user.domain'},
                   7011:                                   $type,undef,'requestcourses')) {
                   7012:                 $canreq ++;
1.1036    raeburn  7013:                 if (ref($request_domains) eq 'HASH') {
                   7014:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7015:                 }
1.1035    raeburn  7016:                 if ($dom eq $env{'user.domain'}) {
                   7017:                     $can_request->{$type} = 1;
                   7018:                 }
                   7019:             }
                   7020:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7021:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7022:                 if (@curr > 0) {
1.1036    raeburn  7023:                     foreach my $item (@curr) {
                   7024:                         if (ref($request_domains) eq 'HASH') {
                   7025:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7026:                             if ($otherdom ne '') {
                   7027:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7028:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7029:                                         push(@{$request_domains->{$type}},$otherdom);
                   7030:                                     }
                   7031:                                 } else {
                   7032:                                     push(@{$request_domains->{$type}},$otherdom);
                   7033:                                 }
                   7034:                             }
                   7035:                         }
                   7036:                     }
                   7037:                     unless($dom eq $env{'user.domain'}) {
                   7038:                         $canreq ++;
1.1035    raeburn  7039:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7040:                             $can_request->{$type} = 1;
                   7041:                         }
                   7042:                     }
                   7043:                 }
                   7044:             }
                   7045:         }
                   7046:     }
                   7047:     return $canreq;
                   7048: }
                   7049: 
1.341     www      7050: # ---------------------------------------------- Custom access rule evaluation
                   7051: 
                   7052: sub customaccess {
                   7053:     my ($priv,$uri)=@_;
1.807     albertel 7054:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7055:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7056:     $udom = &LONCAPA::clean_domain($udom);
                   7057:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7058:     my $access=0;
1.800     albertel 7059:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7060: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7061: 	if ($type eq 'user') {
                   7062: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7063: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7064: 		if ($tdom) {
                   7065: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7066: 		}
1.896     albertel 7067: 		if ($tuname) {
                   7068: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7069: 		}
                   7070: 		$access=($effect eq 'allow');
                   7071: 		last;
                   7072: 	    }
                   7073: 	} else {
                   7074: 	    if ($role) {
                   7075: 		if ($role ne $urole) { next; }
                   7076: 	    }
                   7077: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7078: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7079: 		if ($tdom) {
                   7080: 		    if ($tdom ne $udom) { next; }
                   7081: 		}
                   7082: 		if ($tcrs) {
                   7083: 		    if ($tcrs ne $ucrs) { next; }
                   7084: 		}
                   7085: 		if ($tsec) {
                   7086: 		    if ($tsec ne $usec) { next; }
                   7087: 		}
                   7088: 		$access=($effect eq 'allow');
                   7089: 		last;
                   7090: 	    }
                   7091: 	    if ($realm eq '' && $role eq '') {
                   7092: 		$access=($effect eq 'allow');
                   7093: 	    }
1.402     bowersj2 7094: 	}
1.341     www      7095:     }
                   7096:     return $access;
                   7097: }
                   7098: 
1.103     harris41 7099: # ------------------------------------------------- Check for a user privilege
1.12      www      7100: 
                   7101: sub allowed {
1.1172.2.65  raeburn  7102:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7103:     my $ver_orguri=$uri;
1.439     www      7104:     $uri=&deversion($uri);
1.152     www      7105:     my $orguri=$uri;
1.52      www      7106:     $uri=&declutter($uri);
1.809     raeburn  7107: 
1.810     raeburn  7108:     if ($priv eq 'evb') {
                   7109: # Evade communication block restrictions for specified role in a course
                   7110:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7111:             return $1;
                   7112:         } else {
                   7113:             return;
                   7114:         }
                   7115:     }
                   7116: 
1.620     albertel 7117:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7118: # Free bre access to adm and meta resources
1.775     albertel 7119:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7120: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7121: 	&& ($priv eq 'bre')) {
1.14      www      7122: 	return 'F';
1.159     www      7123:     }
                   7124: 
1.545     banghart 7125: # Free bre access to user's own portfolio contents
1.714     raeburn  7126:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7127:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7128: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7129:         my %setters;
                   7130:         my ($startblock,$endblock) = 
                   7131:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7132:         if ($startblock && $endblock) {
                   7133:             return 'B';
                   7134:         } else {
                   7135:             return 'F';
                   7136:         }
1.545     banghart 7137:     }
                   7138: 
1.762     raeburn  7139: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7140:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7141:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7142:         if (exists($env{'request.course.id'})) {
                   7143:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7144:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7145:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7146:                 my $courseprivid=$env{'request.course.id'};
                   7147:                 $courseprivid=~s/\_/\//;
                   7148:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7149:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7150:                     return $1; 
1.762     raeburn  7151:                 } else {
                   7152:                     if ($env{'request.course.sec'}) {
                   7153:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7154:                     }
                   7155:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7156:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7157:                         return $2;
                   7158:                     }
1.714     raeburn  7159:                 }
                   7160:             }
                   7161:         }
                   7162:     }
                   7163: 
1.159     www      7164: # Free bre to public access
                   7165: 
                   7166:     if ($priv eq 'bre') {
1.238     www      7167:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7168: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7169:            return 'F'; 
                   7170:         }
1.238     www      7171:         if ($copyright eq 'priv') {
                   7172:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7173: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7174: 		return '';
                   7175:             }
                   7176:         }
                   7177:         if ($copyright eq 'domain') {
                   7178:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7179: 	    unless (($env{'user.domain'} eq $1) ||
                   7180:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7181: 		return '';
                   7182:             }
1.262     matthew  7183:         }
1.620     albertel 7184:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7185:             # Library role, so allow browsing of resources in this domain.
                   7186:             return 'F';
1.238     www      7187:         }
1.341     www      7188:         if ($copyright eq 'custom') {
                   7189: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7190:         }
1.14      www      7191:     }
1.264     matthew  7192:     # Domain coordinator is trying to create a course
1.620     albertel 7193:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7194:         # uri is the requested domain in this case.
                   7195:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7196:         # a role of dc for the domain in question.
1.620     albertel 7197:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7198:     }
1.29      www      7199: 
1.52      www      7200:     my $thisallowed='';
                   7201:     my $statecond=0;
                   7202:     my $courseprivid='';
                   7203: 
1.1039    raeburn  7204:     my $ownaccess;
1.1043    raeburn  7205:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7206:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7207:         if ($uri eq '') {
                   7208:             $ownaccess = 1;
                   7209:         } else {
                   7210:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7211:                 my $udom = $env{'user.domain'};
                   7212:                 my $uname = $env{'user.name'};
                   7213:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7214:                     $ownaccess = 1;
1.1040    raeburn  7215:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7216:                     unless ($uri =~ m{\.\./}) {
                   7217:                         $ownaccess = 1;
                   7218:                     }
                   7219:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7220:                     my $now = time;
                   7221:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7222:                         my $adom = $1;
                   7223:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7224:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7225:                                 my ($start,$end) = split('.',$env{$key});
                   7226:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7227:                                     $ownaccess = 1;
                   7228:                                     last;
                   7229:                                 }
                   7230:                             }
                   7231:                         }
                   7232:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7233:                         my $adom = $1;
                   7234:                         my $aname = $2;
1.1042    raeburn  7235:                         foreach my $role ('ca','aa') { 
                   7236:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7237:                                 my ($start,$end) =
                   7238:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7239:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7240:                                     $ownaccess = 1;
                   7241:                                     last;
                   7242:                                 }
1.1039    raeburn  7243:                             }
                   7244:                         }
                   7245:                     }
                   7246:                 }
                   7247:             }
                   7248:         }
                   7249:     }
                   7250: 
1.52      www      7251: # Course
                   7252: 
1.620     albertel 7253:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7254:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7255:             $thisallowed.=$1;
                   7256:         }
1.52      www      7257:     }
1.29      www      7258: 
1.52      www      7259: # Domain
                   7260: 
1.620     albertel 7261:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7262:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7263:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7264:             $thisallowed.=$1;
                   7265:         }
1.12      www      7266:     }
1.52      www      7267: 
1.1141    raeburn  7268: # User who is not author or co-author might still be able to edit
                   7269: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7270:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7271:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7272:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7273:             $thisallowed.=$1;
                   7274:         }
                   7275:     }
                   7276: 
1.52      www      7277: # Course: uri itself is a course
1.66      www      7278:     my $courseuri=$uri;
                   7279:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7280:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7281: 
1.620     albertel 7282:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7283:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7284:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7285:             $thisallowed.=$1;
                   7286:         }
1.12      www      7287:     }
1.29      www      7288: 
1.665     albertel 7289: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7290: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7291:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7292: 	$thisallowed='';
1.671     raeburn  7293:         my ($match)=&is_on_map($uri);
                   7294:         if ($match) {
                   7295:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7296:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7297:                 my $value = $1;
                   7298:                 if ($noblockcheck) {
                   7299:                     $thisallowed.=$value;
1.1162    raeburn  7300:                 } else {
1.1172.2.65  raeburn  7301:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7302:                     if (@blockers > 0) {
                   7303:                         $thisallowed = 'B';
                   7304:                     } else {
                   7305:                         $thisallowed.=$value;
                   7306:                     }
1.1162    raeburn  7307:                 }
1.671     raeburn  7308:             }
                   7309:         } else {
1.705     albertel 7310:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7311:             if ($refuri) {
                   7312:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7313:                     $thisallowed='F';
1.671     raeburn  7314:                 } else {
                   7315:                     $refuri=&declutter($refuri);
                   7316:                     my ($match) = &is_on_map($refuri);
                   7317:                     if ($match) {
1.1172.2.65  raeburn  7318:                         if ($noblockcheck) {
1.1162    raeburn  7319:                             $thisallowed='F';
1.1172.2.65  raeburn  7320:                         } else {
                   7321:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7322:                             if (@blockers > 0) {
                   7323:                                 $thisallowed = 'B';
                   7324:                             } else {
                   7325:                                 $thisallowed='F';
                   7326:                             }
1.1162    raeburn  7327:                         }
1.671     raeburn  7328:                     }
1.669     raeburn  7329:                 }
1.671     raeburn  7330:             }
                   7331:         }
1.314     www      7332:     }
1.492     albertel 7333: 
1.766     albertel 7334:     if ($priv eq 'bre'
                   7335: 	&& $thisallowed ne 'F' 
                   7336: 	&& $thisallowed ne '2'
                   7337: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7338: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7339:     }
                   7340:     
1.52      www      7341: # Full access at system, domain or course-wide level? Exit.
1.29      www      7342:     if ($thisallowed=~/F/) {
                   7343: 	return 'F';
                   7344:     }
                   7345: 
1.52      www      7346: # If this is generating or modifying users, exit with special codes
1.29      www      7347: 
1.643     www      7348:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7349: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7350: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7351: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7352: 	    unless ($auname) { return $thisallowed; }
                   7353: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7354: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7355: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7356: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7357: 	}
1.52      www      7358: 	return $thisallowed;
                   7359:     }
                   7360: #
1.103     harris41 7361: # Gathered so far: system, domain and course wide privileges
1.52      www      7362: #
                   7363: # Course: See if uri or referer is an individual resource that is part of 
                   7364: # the course
                   7365: 
1.620     albertel 7366:     if ($env{'request.course.id'}) {
1.232     www      7367: 
1.620     albertel 7368:        $courseprivid=$env{'request.course.id'};
                   7369:        if ($env{'request.course.sec'}) {
                   7370:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7371:        }
                   7372:        $courseprivid=~s/\_/\//;
                   7373:        my $checkreferer=1;
1.232     www      7374:        my ($match,$cond)=&is_on_map($uri);
                   7375:        if ($match) {
                   7376:            $statecond=$cond;
1.620     albertel 7377:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7378:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7379:                my $value = $1;
                   7380:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7381:                    if ($noblockcheck) {
1.1162    raeburn  7382:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7383:                    } else {
                   7384:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7385:                        if (@blockers > 0) {
                   7386:                            $thisallowed = 'B';
                   7387:                        } else {
                   7388:                            $thisallowed.=$value;
                   7389:                        }
1.1162    raeburn  7390:                    }
                   7391:                } else {
                   7392:                    $thisallowed.=$value;
                   7393:                }
1.52      www      7394:                $checkreferer=0;
                   7395:            }
1.29      www      7396:        }
1.83      www      7397:        
1.148     www      7398:        if ($checkreferer) {
1.620     albertel 7399: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7400:             unless ($refuri) {
1.800     albertel 7401:                 foreach my $key (keys(%env)) {
                   7402: 		    if ($key=~/^httpref\..*\*/) {
                   7403: 			my $pattern=$key;
1.156     www      7404:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7405:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7406:                         $pattern=~s/\//\\\//g;
1.152     www      7407:                         if ($orguri=~/$pattern/) {
1.800     albertel 7408: 			    $refuri=$env{$key};
1.148     www      7409:                         }
                   7410:                     }
1.191     harris41 7411:                 }
1.148     www      7412:             }
1.232     www      7413: 
1.148     www      7414:          if ($refuri) { 
1.152     www      7415: 	  $refuri=&declutter($refuri);
1.232     www      7416:           my ($match,$cond)=&is_on_map($refuri);
                   7417:             if ($match) {
                   7418:               my $refstatecond=$cond;
1.620     albertel 7419:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7420:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7421:                   my $value = $1;
                   7422:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7423:                       if ($noblockcheck) {
1.1162    raeburn  7424:                           $thisallowed.=$value;
1.1172.2.65  raeburn  7425:                       } else {
                   7426:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7427:                           if (@blockers > 0) {
                   7428:                               $thisallowed = 'B';
                   7429:                           } else {
                   7430:                               $thisallowed.=$value;
                   7431:                           }
1.1162    raeburn  7432:                       }
                   7433:                   } else {
                   7434:                       $thisallowed.=$value;
                   7435:                   }
1.53      www      7436:                   $uri=$refuri;
                   7437:                   $statecond=$refstatecond;
1.52      www      7438:               }
                   7439:           }
1.148     www      7440:         }
1.29      www      7441:        }
1.52      www      7442:    }
1.29      www      7443: 
1.52      www      7444: #
1.103     harris41 7445: # Gathered now: all privileges that could apply, and condition number
1.52      www      7446: # 
                   7447: #
                   7448: # Full or no access?
                   7449: #
1.29      www      7450: 
1.52      www      7451:     if ($thisallowed=~/F/) {
                   7452: 	return 'F';
                   7453:     }
1.29      www      7454: 
1.52      www      7455:     unless ($thisallowed) {
                   7456:         return '';
                   7457:     }
1.29      www      7458: 
1.52      www      7459: # Restrictions exist, deal with them
                   7460: #
                   7461: #   C:according to course preferences
                   7462: #   R:according to resource settings
                   7463: #   L:unless locked
                   7464: #   X:according to user session state
                   7465: #
                   7466: 
                   7467: # Possibly locked functionality, check all courses
1.54      www      7468: # Locks might take effect only after 10 minutes cache expiration for other
                   7469: # courses, and 2 minutes for current course
1.52      www      7470: 
                   7471:     my $envkey;
                   7472:     if ($thisallowed=~/L/) {
1.1000    raeburn  7473:         foreach $envkey (keys(%env)) {
1.54      www      7474:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7475:                my $courseid=$2;
                   7476:                my $roleid=$1.'.'.$2;
1.92      www      7477:                $courseid=~s/^\///;
1.54      www      7478:                my $expiretime=600;
1.620     albertel 7479:                if ($env{'request.role'} eq $roleid) {
1.54      www      7480: 		  $expiretime=120;
                   7481:                }
                   7482: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7483:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7484:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7485: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7486:                }
1.620     albertel 7487:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7488:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7489: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7490:                        &log($env{'user.domain'},$env{'user.name'},
                   7491:                             $env{'user.home'},
1.57      www      7492:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7493:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7494:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7495: 		       return '';
                   7496:                    }
                   7497:                }
1.620     albertel 7498:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7499:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7500: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7501:                        &log($env{'user.domain'},$env{'user.name'},
                   7502:                             $env{'user.home'},
1.57      www      7503:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7504:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7505:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7506: 		       return '';
                   7507:                    }
                   7508:                }
                   7509: 	   }
1.29      www      7510:        }
1.52      www      7511:     }
                   7512:    
                   7513: #
                   7514: # Rest of the restrictions depend on selected course
                   7515: #
                   7516: 
1.620     albertel 7517:     unless ($env{'request.course.id'}) {
1.766     albertel 7518: 	if ($thisallowed eq 'A') {
                   7519: 	    return 'A';
1.814     raeburn  7520:         } elsif ($thisallowed eq 'B') {
                   7521:             return 'B';
1.766     albertel 7522: 	} else {
                   7523: 	    return '1';
                   7524: 	}
1.52      www      7525:     }
1.29      www      7526: 
1.52      www      7527: #
                   7528: # Now user is definitely in a course
                   7529: #
1.53      www      7530: 
                   7531: 
                   7532: # Course preferences
                   7533: 
                   7534:    if ($thisallowed=~/C/) {
1.620     albertel 7535:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7536:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7537:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7538: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7539: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7540: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7541: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7542: 			$env{'request.course.id'});
                   7543: 	   }
1.237     www      7544:            return '';
                   7545:        }
                   7546: 
1.620     albertel 7547:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7548: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7549: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7550: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7551: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7552: 			$env{'request.course.id'});
                   7553: 	   }
1.54      www      7554:            return '';
                   7555:        }
1.53      www      7556:    }
                   7557: 
                   7558: # Resource preferences
                   7559: 
                   7560:    if ($thisallowed=~/R/) {
1.620     albertel 7561:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7562:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7563: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7564: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7565: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7566: 	   }
                   7567: 	   return '';
1.54      www      7568:        }
1.53      www      7569:    }
1.30      www      7570: 
1.246     www      7571: # Restricted by state or randomout?
1.30      www      7572: 
1.52      www      7573:    if ($thisallowed=~/X/) {
1.620     albertel 7574:       if ($env{'acc.randomout'}) {
1.579     albertel 7575: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7576:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7577:             return ''; 
                   7578:          }
1.247     www      7579:       }
                   7580:       if (&condval($statecond)) {
1.52      www      7581: 	 return '2';
                   7582:       } else {
                   7583:          return '';
                   7584:       }
                   7585:    }
1.30      www      7586: 
1.766     albertel 7587:     if ($thisallowed eq 'A') {
                   7588: 	return 'A';
1.814     raeburn  7589:     } elsif ($thisallowed eq 'B') {
                   7590:         return 'B';
1.766     albertel 7591:     }
1.52      www      7592:    return 'F';
1.232     www      7593: }
1.1162    raeburn  7594: 
1.1172.2.13  raeburn  7595: # ------------------------------------------- Check construction space access
                   7596: 
                   7597: sub constructaccess {
                   7598:     my ($url,$setpriv)=@_;
                   7599: 
                   7600: # We do not allow editing of previous versions of files
                   7601:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7602: 
                   7603: # Get username and domain from URL
                   7604:     my ($ownername,$ownerdomain,$ownerhome);
                   7605: 
                   7606:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  7607:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  7608: 
                   7609: # The URL does not really point to any authorspace, forget it
                   7610:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7611: 
                   7612: # Now we need to see if the user has access to the authorspace of
                   7613: # $ownername at $ownerdomain
                   7614: 
                   7615:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7616: # Real author for this?
                   7617:        $ownerhome = $env{'user.home'};
                   7618:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7619:           return ($ownername,$ownerdomain,$ownerhome);
                   7620:        }
                   7621:     } else {
                   7622: # Co-author for this?
                   7623:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7624:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7625:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7626:             return ($ownername,$ownerdomain,$ownerhome);
                   7627:         }
                   7628:     }
                   7629: 
                   7630: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7631: # we might as well leave
                   7632:    unless ($setpriv) { return ''; }
                   7633: 
                   7634: # Backdoor access?
                   7635:     my $allowed=&allowed('eco',$ownerdomain);
                   7636: # Nope
                   7637:     unless ($allowed) { return ''; }
                   7638: # Looks like we may have access, but could be locked by the owner of the construction space
                   7639:     if ($allowed eq 'U') {
                   7640:         my %blocked=&get('environment',['domcoord.author'],
                   7641:                          $ownerdomain,$ownername);
                   7642: # Is blocked by owner
                   7643:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7644:     }
                   7645:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7646: # Grant temporary access
                   7647:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  7648:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  7649:         if (!$update) { $update = $then; }
                   7650:         my $refresh=$env{'user.refresh.time'};
                   7651:         if (!$refresh) { $refresh = $update; }
                   7652:         my $now = time;
                   7653:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7654:                            $now,'ca','constructaccess');
                   7655:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7656:         return($ownername,$ownerdomain,$ownerhome);
                   7657:     }
                   7658: # No business here
                   7659:     return '';
                   7660: }
                   7661: 
1.1172.2.66  raeburn  7662: # ----------------------------------------------------------- Content Blocking
                   7663: 
                   7664: {
                   7665: # Caches for faster Course Contents display where content blocking
                   7666: # is in operation (i.e., interval param set) for timed quiz.
                   7667: #
                   7668: # User for whom data are being temporarily cached.
                   7669: my $cacheduser='';
                   7670: # Cached blockers for this user (a hash of blocking items).
                   7671: my %cachedblockers=();
                   7672: # When the data were last cached.
                   7673: my $cachedlast='';
                   7674: 
                   7675: sub load_all_blockers {
                   7676:     my ($uname,$udom,$blocks)=@_;
                   7677:     if (($uname ne '') && ($udom ne '')) {
                   7678:         if (($cacheduser eq $uname.':'.$udom) &&
                   7679:             (abs($cachedlast-time)<5)) {
                   7680:             return;
                   7681:         }
                   7682:     }
                   7683:     $cachedlast=time;
                   7684:     $cacheduser=$uname.':'.$udom;
                   7685:     %cachedblockers = &get_commblock_resources($blocks);
                   7686: }
                   7687: 
1.1162    raeburn  7688: sub get_comm_blocks {
                   7689:     my ($cdom,$cnum) = @_;
                   7690:     if ($cdom eq '' || $cnum eq '') {
                   7691:         return unless ($env{'request.course.id'});
                   7692:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7693:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7694:     }
                   7695:     my %commblocks;
                   7696:     my $hashid=$cdom.'_'.$cnum;
                   7697:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7698:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7699:         %commblocks = %{$blocksref};
                   7700:     } else {
                   7701:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7702:         my $cachetime = 600;
                   7703:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7704:     }
                   7705:     return %commblocks;
                   7706: }
                   7707: 
1.1172.2.66  raeburn  7708: sub get_commblock_resources {
                   7709:     my ($blocks) = @_;
                   7710:     my %blockers = ();
                   7711:     return %blockers unless ($env{'request.course.id'});
                   7712:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7713:     my %commblocks;
                   7714:     if (ref($blocks) eq 'HASH') {
                   7715:         %commblocks = %{$blocks};
                   7716:     } else {
                   7717:         %commblocks = &get_comm_blocks();
                   7718:     }
1.1172.2.66  raeburn  7719:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  7720:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  7721:     return %blockers unless (ref($navmap));
                   7722:     my $now = time;
1.1162    raeburn  7723:     foreach my $block (keys(%commblocks)) {
                   7724:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7725:             my ($start,$end) = ($1,$2);
                   7726:             if ($start <= $now && $end >= $now) {
                   7727:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7728:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7729:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  7730:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7731:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  7732:                             }
                   7733:                         }
                   7734:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  7735:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7736:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7737:                             }
                   7738:                         }
                   7739:                     }
                   7740:                 }
                   7741:             }
                   7742:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7743:             my $item = $1;
1.1163    raeburn  7744:             my @to_test;
1.1162    raeburn  7745:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7746:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  7747:                     my @interval;
                   7748:                     my $type = 'map';
                   7749:                     if ($item eq 'course') {
                   7750:                         $type = 'course';
                   7751:                         @interval=&EXT("resource.0.interval");
                   7752:                     } else {
                   7753:                         if ($item =~ /___\d+___/) {
                   7754:                             $type = 'resource';
                   7755:                             @interval=&EXT("resource.0.interval",$item);
                   7756:                             if (ref($navmap)) {
                   7757:                                 my $res = $navmap->getBySymb($item);
                   7758:                                 push(@to_test,$res);
                   7759:                             }
1.1162    raeburn  7760:                         } else {
1.1172.2.66  raeburn  7761:                             my $mapsymb = &symbread($item,1);
                   7762:                             if ($mapsymb) {
                   7763:                                 if (ref($navmap)) {
                   7764:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7765:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7766:                                     foreach my $res (@to_test) {
                   7767:                                         my $symb = $res->symb();
                   7768:                                         next if ($symb eq $mapsymb);
                   7769:                                         if ($symb ne '') {
                   7770:                                             @interval=&EXT("resource.0.interval",$symb);
                   7771:                                             if ($interval[1] eq 'map') {
                   7772:                                                 last;
1.1162    raeburn  7773:                                             }
                   7774:                                         }
                   7775:                                     }
                   7776:                                 }
                   7777:                             }
                   7778:                         }
1.1172.2.66  raeburn  7779:                     }
1.1172.2.93.2  1(raebur 7780:7):                     if ($interval[0] =~ /^(\d+)/) {
                   7781:7):                         my $timelimit = $1;
1.1172.2.66  raeburn  7782:                         my $first_access;
                   7783:                         if ($type eq 'resource') {
                   7784:                             $first_access=&get_first_access($interval[1],$item);
                   7785:                         } elsif ($type eq 'map') {
                   7786:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7787:                         } else {
                   7788:                             $first_access=&get_first_access($interval[1]);
                   7789:                         }
                   7790:                         if ($first_access) {
1.1172.2.93.2  1(raebur 7791:7):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  7792:                             if ($timesup > $now) {
                   7793:                                 my $activeblock;
                   7794:                                 foreach my $res (@to_test) {
                   7795:                                     if ($res->answerable()) {
                   7796:                                         $activeblock = 1;
                   7797:                                         last;
                   7798:                                     }
                   7799:                                 }
                   7800:                                 if ($activeblock) {
                   7801:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7802:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7803:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7804:                                          }
                   7805:                                     }
                   7806:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7807:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7808:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7809:                                         }
1.1162    raeburn  7810:                                     }
                   7811:                                 }
                   7812:                             }
                   7813:                         }
                   7814:                     }
                   7815:                 }
                   7816:             }
                   7817:         }
                   7818:     }
1.1172.2.66  raeburn  7819:     return %blockers;
1.1162    raeburn  7820: }
                   7821: 
1.1172.2.66  raeburn  7822: sub has_comm_blocking {
                   7823:     my ($priv,$symb,$uri,$blocks) = @_;
                   7824:     my @blockers;
                   7825:     return unless ($env{'request.course.id'});
                   7826:     return unless ($priv eq 'bre');
                   7827:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7828:     return if ($env{'request.state'} eq 'construct');
                   7829:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7830:     return unless (keys(%cachedblockers) > 0);
                   7831:     my (%possibles,@symbs);
                   7832:     if (!$symb) {
                   7833:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7834:     }
1.1172.2.66  raeburn  7835:     if ($symb) {
                   7836:         @symbs = ($symb);
                   7837:     } elsif (keys(%possibles)) {
                   7838:         @symbs = keys(%possibles);
                   7839:     }
                   7840:     my $noblock;
                   7841:     foreach my $symb (@symbs) {
                   7842:         last if ($noblock);
                   7843:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7844:         foreach my $block (keys(%cachedblockers)) {
                   7845:             if ($block =~ /^firstaccess____(.+)$/) {
                   7846:                 my $item = $1;
                   7847:                 if (($item eq $map) || ($item eq $symb)) {
                   7848:                     $noblock = 1;
                   7849:                     last;
                   7850:                 }
1.1162    raeburn  7851:             }
1.1172.2.66  raeburn  7852:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7853:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7854:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7855:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7856:                             push(@blockers,$block);
                   7857:                         }
                   7858:                     }
                   7859:                 }
                   7860:             }
                   7861:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7862:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7863:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7864:                         push(@blockers,$block);
                   7865:                     }
                   7866:                 }
1.1162    raeburn  7867:             }
                   7868:         }
                   7869:     }
1.1172.2.66  raeburn  7870:     return if ($noblock);
                   7871:     return @blockers;
                   7872: }
1.1162    raeburn  7873: }
                   7874: 
1.1172.2.66  raeburn  7875: # -------------------------------- Deversion and split uri into path an filename
                   7876: 
1.1133    foxr     7877: #
1.1172.2.66  raeburn  7878: #   Removes the version from a URI and
1.1133    foxr     7879: #   splits it in to its filename and path to the filename.
                   7880: #   Seems like File::Basename could have done this more clearly.
                   7881: #   Parameters:
                   7882: #      $uri   - input URI
                   7883: #   Returns:
                   7884: #     Two element list consisting of 
                   7885: #     $pathname  - the URI up to and excluding the trailing /
                   7886: #     $filename  - The part of the URI following the last /
                   7887: #  NOTE:
                   7888: #    Another realization of this is simply:
                   7889: #    use File::Basename;
                   7890: #    ...
                   7891: #    $uri = shift;
                   7892: #    $filename = basename($uri);
                   7893: #    $path     = dirname($uri);
                   7894: #    return ($filename, $path);
                   7895: #
                   7896: #     The implementation below is probably faster however.
                   7897: #
1.710     albertel 7898: sub split_uri_for_cond {
                   7899:     my $uri=&deversion(&declutter(shift));
                   7900:     my @uriparts=split(/\//,$uri);
                   7901:     my $filename=pop(@uriparts);
                   7902:     my $pathname=join('/',@uriparts);
                   7903:     return ($pathname,$filename);
                   7904: }
1.232     www      7905: # --------------------------------------------------- Is a resource on the map?
                   7906: 
                   7907: sub is_on_map {
1.710     albertel 7908:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7909:     #Trying to find the conditional for the file
1.620     albertel 7910:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7911: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7912:     if ($match) {
1.289     bowersj2 7913: 	return (1,$1);
                   7914:     } else {
1.434     www      7915: 	return (0,0);
1.289     bowersj2 7916:     }
1.12      www      7917: }
                   7918: 
1.427     www      7919: # --------------------------------------------------------- Get symb from alias
                   7920: 
                   7921: sub get_symb_from_alias {
                   7922:     my $symb=shift;
                   7923:     my ($map,$resid,$url)=&decode_symb($symb);
                   7924: # Already is a symb
                   7925:     if ($url) { return $symb; }
                   7926: # Must be an alias
                   7927:     my $aliassymb='';
                   7928:     my %bighash;
1.620     albertel 7929:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7930:                             &GDBM_READER(),0640)) {
                   7931:         my $rid=$bighash{'mapalias_'.$symb};
                   7932: 	if ($rid) {
                   7933: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7934: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7935: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7936: 	}
                   7937:         untie %bighash;
                   7938:     }
                   7939:     return $aliassymb;
                   7940: }
                   7941: 
1.12      www      7942: # ----------------------------------------------------------------- Define Role
                   7943: 
                   7944: sub definerole {
                   7945:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  7946:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 7947:     foreach my $role (split(':',$sysrole)) {
                   7948: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7949:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7950:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7951: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7952:                return "refused:s:$crole&$cqual"; 
                   7953:             }
                   7954:         }
1.191     harris41 7955:     }
1.800     albertel 7956:     foreach my $role (split(':',$domrole)) {
                   7957: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7958:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7959:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7960: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7961:                return "refused:d:$crole&$cqual"; 
                   7962:             }
                   7963:         }
1.191     harris41 7964:     }
1.800     albertel 7965:     foreach my $role (split(':',$courole)) {
                   7966: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7967:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7968:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7969: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7970:                return "refused:c:$crole&$cqual"; 
                   7971:             }
                   7972:         }
1.191     harris41 7973:     }
1.1172.2.84  raeburn  7974:     my $uhome;
                   7975:     if (($uname ne '') && ($udom ne '')) {
                   7976:         $uhome = &homeserver($uname,$udom);
                   7977:         return $uhome if ($uhome eq 'no_host');
                   7978:     } else {
                   7979:         $uname = $env{'user.name'};
                   7980:         $udom = $env{'user.domain'};
                   7981:         $uhome = $env{'user.home'};
                   7982:     }
1.620     albertel 7983:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  7984:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      7985:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  7986:     return reply($command,$uhome);
1.12      www      7987:   } else {
                   7988:     return 'refused';
                   7989:   }
1.105     harris41 7990: }
                   7991: 
                   7992: # ---------------- Make a metadata query against the network of library servers
                   7993: 
                   7994: sub metadata_query {
1.1172.2.33  raeburn  7995:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7996:     my %rhash;
1.845     albertel 7997:     my %libserv = &all_library();
1.244     matthew  7998:     my @server_list = (defined($server_array) ? @$server_array
                   7999:                                               : keys(%libserv) );
                   8000:     for my $server (@server_list) {
1.1172.2.33  raeburn  8001:         my $domains = '';
                   8002:         if (ref($domains_hash) eq 'HASH') {
                   8003:             $domains = $domains_hash->{$server};    
                   8004:         }
1.118     harris41 8005: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8006: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8007: 	    $rhash{$server}=$reply;
                   8008: 	}
                   8009: 	else {
                   8010: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8011: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8012: 			     $server);
                   8013: 	    $rhash{$server}=$reply;
                   8014: 	}
1.112     harris41 8015:     }
1.118     harris41 8016:     return \%rhash;
1.240     www      8017: }
                   8018: 
                   8019: # ----------------------------------------- Send log queries and wait for reply
                   8020: 
                   8021: sub log_query {
                   8022:     my ($uname,$udom,$query,%filters)=@_;
                   8023:     my $uhome=&homeserver($uname,$udom);
                   8024:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8025:     my $uhost=&hostname($uhome);
1.800     albertel 8026:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8027:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8028:                        $uhome);
1.479     albertel 8029:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8030:     return get_query_reply($queryid);
                   8031: }
                   8032: 
1.818     raeburn  8033: # -------------------------- Update MySQL table for portfolio file
                   8034: 
                   8035: sub update_portfolio_table {
1.821     raeburn  8036:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8037:     if ($group ne '') {
                   8038:         $file_name =~s /^\Q$group\E//;
                   8039:     }
1.818     raeburn  8040:     my $homeserver = &homeserver($uname,$udom);
                   8041:     my $queryid=
1.821     raeburn  8042:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8043:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8044:     my $reply = &get_query_reply($queryid);
                   8045:     return $reply;
                   8046: }
                   8047: 
1.899     raeburn  8048: # -------------------------- Update MySQL allusers table
                   8049: 
                   8050: sub update_allusers_table {
                   8051:     my ($uname,$udom,$names) = @_;
                   8052:     my $homeserver = &homeserver($uname,$udom);
                   8053:     my $queryid=
                   8054:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8055:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8056:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8057:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8058:                'generation='.&escape($names->{'generation'}).'%%'.
                   8059:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8060:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8061:     return;
1.899     raeburn  8062: }
                   8063: 
1.508     raeburn  8064: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8065: 
                   8066: sub fetch_enrollment_query {
1.511     raeburn  8067:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8068:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8069:     my $maxtries = 1;
1.508     raeburn  8070:     if ($context eq 'automated') {
                   8071:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8072:         $sleep = 2;
                   8073:         $loopmax = 100;
1.547     raeburn  8074:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8075:     } else {
                   8076:         $homeserver = &homeserver($cnum,$dom);
                   8077:     }
1.838     albertel 8078:     my $host=&hostname($homeserver);
1.506     raeburn  8079:     my $cmd = '';
1.1000    raeburn  8080:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8081:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8082:     }
                   8083:     $cmd =~ s/%%$//;
                   8084:     $cmd = &escape($cmd);
                   8085:     my $query = 'fetchenrollment';
1.620     albertel 8086:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8087:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8088:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8089:         return 'error: '.$queryid;
                   8090:     }
1.1172.2.93  raeburn  8091:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8092:     my $tries = 1;
                   8093:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8094:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8095:         $tries ++;
                   8096:     }
1.526     raeburn  8097:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8098:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8099:     } else {
1.901     albertel 8100:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8101:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8102:             foreach my $line (@responses) {
                   8103:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8104:                 $$replyref{$key} = $value;
                   8105:             }
                   8106:         } else {
1.1117    foxr     8107:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8108:             foreach my $line (@responses) {
                   8109:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8110:                 $$replyref{$key} = $value;
                   8111:                 if ($value > 0) {
1.800     albertel 8112:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8113:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8114:                         my $destname = $pathname.'/'.$filename;
                   8115:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8116:                         if ($xml_classlist =~ /^error/) {
                   8117:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8118:                         } else {
1.506     raeburn  8119:                             if ( open(FILE,">$destname") ) {
                   8120:                                 print FILE &unescape($xml_classlist);
                   8121:                                 close(FILE);
1.526     raeburn  8122:                             } else {
                   8123:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8124:                             }
                   8125:                         }
                   8126:                     }
                   8127:                 }
                   8128:             }
                   8129:         }
                   8130:         return 'ok';
                   8131:     }
                   8132:     return 'error';
                   8133: }
                   8134: 
1.242     www      8135: sub get_query_reply {
1.1172.2.79  raeburn  8136:     my ($queryid,$sleep,$loopmax) = @_;
                   8137:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8138:         $sleep = 0.2;
                   8139:     }
                   8140:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8141:         $loopmax = 100;
                   8142:     }
1.1117    foxr     8143:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8144:     my $reply='';
1.1172.2.79  raeburn  8145:     for (1..$loopmax) {
                   8146: 	sleep($sleep);
1.240     www      8147:         if (-e $replyfile.'.end') {
1.448     albertel 8148: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 8149: 		$reply = join('',<$fh>);
                   8150: 		close($fh);
1.240     www      8151: 	   } else { return 'error: reply_file_error'; }
1.242     www      8152:            return &unescape($reply);
                   8153: 	}
1.240     www      8154:     }
1.242     www      8155:     return 'timeout:'.$queryid;
1.240     www      8156: }
                   8157: 
                   8158: sub courselog_query {
1.241     www      8159: #
                   8160: # possible filters:
                   8161: # url: url or symb
                   8162: # username
                   8163: # domain
                   8164: # action: view, submit, grade
                   8165: # start: timestamp
                   8166: # end: timestamp
                   8167: #
1.240     www      8168:     my (%filters)=@_;
1.620     albertel 8169:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8170:     if ($filters{'url'}) {
                   8171: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8172:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8173:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8174:     }
1.620     albertel 8175:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8176:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8177:     return &log_query($cname,$cdom,'courselog',%filters);
                   8178: }
                   8179: 
                   8180: sub userlog_query {
1.858     raeburn  8181: #
                   8182: # possible filters:
                   8183: # action: log check role
                   8184: # start: timestamp
                   8185: # end: timestamp
                   8186: #
1.240     www      8187:     my ($uname,$udom,%filters)=@_;
                   8188:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8189: }
                   8190: 
1.506     raeburn  8191: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8192: 
                   8193: sub auto_run {
1.508     raeburn  8194:     my ($cnum,$cdom) = @_;
1.876     raeburn  8195:     my $response = 0;
                   8196:     my $settings;
                   8197:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8198:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8199:         $settings = $domconfig{'autoenroll'};
                   8200:         if ($settings->{'run'} eq '1') {
                   8201:             $response = 1;
                   8202:         }
                   8203:     } else {
1.934     raeburn  8204:         my $homeserver;
                   8205:         if (&is_course($cdom,$cnum)) {
                   8206:             $homeserver = &homeserver($cnum,$cdom);
                   8207:         } else {
                   8208:             $homeserver = &domain($cdom,'primary');
                   8209:         }
                   8210:         if ($homeserver ne 'no_host') {
                   8211:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8212:         }
1.876     raeburn  8213:     }
1.506     raeburn  8214:     return $response;
                   8215: }
1.776     albertel 8216: 
1.506     raeburn  8217: sub auto_get_sections {
1.508     raeburn  8218:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8219:     my $homeserver;
                   8220:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8221:         $homeserver = &homeserver($cnum,$cdom);
                   8222:     }
                   8223:     if (!defined($homeserver)) { 
                   8224:         if ($cdom =~ /^$match_domain$/) {
                   8225:             $homeserver = &domain($cdom,'primary');
                   8226:         }
                   8227:     }
                   8228:     my @secs;
                   8229:     if (defined($homeserver)) {
                   8230:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8231:         unless ($response eq 'refused') {
                   8232:             @secs = split(/:/,$response);
                   8233:         }
1.506     raeburn  8234:     }
                   8235:     return @secs;
                   8236: }
1.776     albertel 8237: 
1.506     raeburn  8238: sub auto_new_course {
1.1099    raeburn  8239:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8240:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8241:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8242:     return $response;
                   8243: }
1.776     albertel 8244: 
1.506     raeburn  8245: sub auto_validate_courseID {
1.508     raeburn  8246:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8247:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8248:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8249:     return $response;
                   8250: }
1.776     albertel 8251: 
1.1007    raeburn  8252: sub auto_validate_instcode {
1.1020    raeburn  8253:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8254:     my ($homeserver,$response);
                   8255:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8256:         $homeserver = &homeserver($cnum,$cdom);
                   8257:     }
                   8258:     if (!defined($homeserver)) {
                   8259:         if ($cdom =~ /^$match_domain$/) {
                   8260:             $homeserver = &domain($cdom,'primary');
                   8261:         }
                   8262:     }
1.1065    raeburn  8263:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8264:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8265:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8266:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8267: }
                   8268: 
1.506     raeburn  8269: sub auto_create_password {
1.873     raeburn  8270:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8271:     my ($homeserver,$response);
1.506     raeburn  8272:     my $create_passwd = 0;
                   8273:     my $authchk = '';
1.873     raeburn  8274:     if ($udom =~ /^$match_domain$/) {
                   8275:         $homeserver = &domain($udom,'primary');
                   8276:     }
                   8277:     if ($homeserver eq '') {
                   8278:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8279:             $homeserver = &homeserver($cnum,$cdom);
                   8280:         }
                   8281:     }
                   8282:     if ($homeserver eq '') {
                   8283:         $authchk = 'nodomain';
1.506     raeburn  8284:     } else {
1.873     raeburn  8285:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8286:         if ($response eq 'refused') {
                   8287:             $authchk = 'refused';
                   8288:         } else {
1.901     albertel 8289:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8290:         }
1.506     raeburn  8291:     }
                   8292:     return ($authparam,$create_passwd,$authchk);
                   8293: }
                   8294: 
1.706     raeburn  8295: sub auto_photo_permission {
                   8296:     my ($cnum,$cdom,$students) = @_;
                   8297:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8298:     my ($outcome,$perm_reqd,$conditions) = 
                   8299: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8300:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8301: 	return (undef,undef);
                   8302:     }
1.706     raeburn  8303:     return ($outcome,$perm_reqd,$conditions);
                   8304: }
                   8305: 
                   8306: sub auto_checkphotos {
                   8307:     my ($uname,$udom,$pid) = @_;
                   8308:     my $homeserver = &homeserver($uname,$udom);
                   8309:     my ($result,$resulttype);
                   8310:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8311: 				   &escape($uname).':'.&escape($pid),
                   8312: 				   $homeserver));
1.709     albertel 8313:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8314: 	return (undef,undef);
                   8315:     }
1.706     raeburn  8316:     if ($outcome) {
                   8317:         ($result,$resulttype) = split(/:/,$outcome);
                   8318:     } 
                   8319:     return ($result,$resulttype);
                   8320: }
                   8321: 
                   8322: sub auto_photochoice {
                   8323:     my ($cnum,$cdom) = @_;
                   8324:     my $homeserver = &homeserver($cnum,$cdom);
                   8325:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8326: 						       &escape($cdom),
                   8327: 						       $homeserver)));
1.709     albertel 8328:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8329: 	return (undef,undef);
                   8330:     }
1.706     raeburn  8331:     return ($update,$comment);
                   8332: }
                   8333: 
                   8334: sub auto_photoupdate {
                   8335:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8336:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8337:     my $host=&hostname($homeserver);
1.706     raeburn  8338:     my $cmd = '';
                   8339:     my $maxtries = 1;
1.800     albertel 8340:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8341:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8342:     }
                   8343:     $cmd =~ s/%%$//;
                   8344:     $cmd = &escape($cmd);
                   8345:     my $query = 'institutionalphotos';
                   8346:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8347:     unless ($queryid=~/^\Q$host\E\_/) {
                   8348:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8349:         return 'error: '.$queryid;
                   8350:     }
                   8351:     my $reply = &get_query_reply($queryid);
                   8352:     my $tries = 1;
                   8353:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8354:         $reply = &get_query_reply($queryid);
                   8355:         $tries ++;
                   8356:     }
                   8357:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8358:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8359:     } else {
                   8360:         my @responses = split(/:/,$reply);
                   8361:         my $outcome = shift(@responses); 
                   8362:         foreach my $item (@responses) {
                   8363:             my ($key,$value) = split(/=/,$item);
                   8364:             $$photo{$key} = $value;
                   8365:         }
                   8366:         return $outcome;
                   8367:     }
                   8368:     return 'error';
                   8369: }
                   8370: 
1.521     raeburn  8371: sub auto_instcode_format {
1.793     albertel 8372:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8373: 	$cat_order) = @_;
1.521     raeburn  8374:     my $courses = '';
1.772     raeburn  8375:     my @homeservers;
1.521     raeburn  8376:     if ($caller eq 'global') {
1.841     albertel 8377: 	my %servers = &get_servers($codedom,'library');
                   8378: 	foreach my $tryserver (keys(%servers)) {
                   8379: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8380: 		push(@homeservers,$tryserver);
                   8381: 	    }
1.584     raeburn  8382:         }
1.1022    raeburn  8383:     } elsif ($caller eq 'requests') {
                   8384:         if ($codedom =~ /^$match_domain$/) {
                   8385:             my $chome = &domain($codedom,'primary');
                   8386:             unless ($chome eq 'no_host') {
                   8387:                 push(@homeservers,$chome);
                   8388:             }
                   8389:         }
1.521     raeburn  8390:     } else {
1.772     raeburn  8391:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8392:     }
1.793     albertel 8393:     foreach my $code (keys(%{$instcodes})) {
                   8394:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8395:     }
                   8396:     chop($courses);
1.772     raeburn  8397:     my $ok_response = 0;
                   8398:     my $response;
                   8399:     while (@homeservers > 0 && $ok_response == 0) {
                   8400:         my $server = shift(@homeservers); 
                   8401:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8402:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8403:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8404: 		split(/:/,$response);
1.772     raeburn  8405:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8406:             push(@{$codetitles},&str2array($codetitles_str));
                   8407:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8408:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8409:             $ok_response = 1;
                   8410:         }
                   8411:     }
                   8412:     if ($ok_response) {
1.521     raeburn  8413:         return 'ok';
1.772     raeburn  8414:     } else {
                   8415:         return $response;
1.521     raeburn  8416:     }
                   8417: }
                   8418: 
1.792     raeburn  8419: sub auto_instcode_defaults {
                   8420:     my ($domain,$returnhash,$code_order) = @_;
                   8421:     my @homeservers;
1.841     albertel 8422: 
                   8423:     my %servers = &get_servers($domain,'library');
                   8424:     foreach my $tryserver (keys(%servers)) {
                   8425: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8426: 	    push(@homeservers,$tryserver);
                   8427: 	}
1.792     raeburn  8428:     }
1.841     albertel 8429: 
1.792     raeburn  8430:     my $response;
1.841     albertel 8431:     foreach my $server (@homeservers) {
1.792     raeburn  8432:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8433:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8434: 	
                   8435: 	foreach my $pair (split(/\&/,$response)) {
                   8436: 	    my ($name,$value)=split(/\=/,$pair);
                   8437: 	    if ($name eq 'code_order') {
                   8438: 		@{$code_order} = split(/\&/,&unescape($value));
                   8439: 	    } else {
                   8440: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8441: 	    }
                   8442: 	}
                   8443: 	return 'ok';
1.792     raeburn  8444:     }
1.841     albertel 8445: 
                   8446:     return $response;
1.1003    raeburn  8447: }
                   8448: 
                   8449: sub auto_possible_instcodes {
1.1007    raeburn  8450:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8451:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8452:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8453:         return;
                   8454:     }
1.1003    raeburn  8455:     my (@homeservers,$uhome);
                   8456:     if (defined(&domain($domain,'primary'))) {
                   8457:         $uhome=&domain($domain,'primary');
                   8458:         push(@homeservers,&domain($domain,'primary'));
                   8459:     } else {
                   8460:         my %servers = &get_servers($domain,'library');
                   8461:         foreach my $tryserver (keys(%servers)) {
                   8462:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8463:                 push(@homeservers,$tryserver);
                   8464:             }
                   8465:         }
                   8466:     }
                   8467:     my $response;
                   8468:     foreach my $server (@homeservers) {
                   8469:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8470:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8471:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8472:             split(':',$response);
                   8473:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8474:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8475:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8476:             my ($name,$value)=split('=',$item);
                   8477:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8478:         }
                   8479:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8480:             my ($name,$value)=split('=',$item);
                   8481:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8482:         }
                   8483:         return 'ok';
                   8484:     }
                   8485:     return $response;
                   8486: }
1.792     raeburn  8487: 
1.1010    raeburn  8488: sub auto_courserequest_checks {
                   8489:     my ($dom) = @_;
1.1020    raeburn  8490:     my ($homeserver,%validations);
                   8491:     if ($dom =~ /^$match_domain$/) {
                   8492:         $homeserver = &domain($dom,'primary');
                   8493:     }
                   8494:     unless ($homeserver eq 'no_host') {
                   8495:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8496:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8497:             my @items = split(/&/,$response);
                   8498:             foreach my $item (@items) {
                   8499:                 my ($key,$value) = split('=',$item);
                   8500:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8501:             }
                   8502:         }
                   8503:     }
1.1010    raeburn  8504:     return %validations; 
                   8505: }
                   8506: 
1.1020    raeburn  8507: sub auto_courserequest_validation {
1.1172.2.43  raeburn  8508:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8509:     my ($homeserver,$response);
                   8510:     if ($dom =~ /^$match_domain$/) {
                   8511:         $homeserver = &domain($dom,'primary');
                   8512:     }
1.1172.2.43  raeburn  8513:     unless ($homeserver eq 'no_host') {
                   8514:         my $customdata;
                   8515:         if (ref($custominfo) eq 'HASH') {
                   8516:             $customdata = &freeze_escape($custominfo);
                   8517:         }
1.1020    raeburn  8518:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8519:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  8520:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8521:                                     $customdata,$homeserver));
1.1020    raeburn  8522:     }
                   8523:     return $response;
                   8524: }
                   8525: 
1.777     albertel 8526: sub auto_validate_class_sec {
1.918     raeburn  8527:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8528:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8529:     my $ownerlist;
                   8530:     if (ref($owners) eq 'ARRAY') {
                   8531:         $ownerlist = join(',',@{$owners});
                   8532:     } else {
                   8533:         $ownerlist = $owners;
                   8534:     }
1.773     raeburn  8535:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8536:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8537:     return $response;
                   8538: }
                   8539: 
1.1172.2.38  raeburn  8540: sub auto_crsreq_update {
                   8541:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  8542:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  8543:     my ($homeserver,%crsreqresponse);
                   8544:     if ($cdom =~ /^$match_domain$/) {
                   8545:         $homeserver = &domain($cdom,'primary');
                   8546:     }
                   8547:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8548:         my $info;
                   8549:         if (ref($inbound) eq 'HASH') {
                   8550:             $info = &freeze_escape($inbound);
                   8551:         }
                   8552:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8553:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8554:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  8555:                             &escape($title).':'.&escape($code).':'.
                   8556:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  8557:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8558:             my @items = split(/&/,$response);
                   8559:             foreach my $item (@items) {
                   8560:                 my ($key,$value) = split('=',$item);
                   8561:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8562:             }
                   8563:         }
                   8564:     }
                   8565:     return \%crsreqresponse;
                   8566: }
                   8567: 
1.1172.2.78  raeburn  8568: sub auto_export_grades {
                   8569:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8570:     my ($homeserver,%exportresponse);
                   8571:     if ($cdom =~ /^$match_domain$/) {
                   8572:         $homeserver = &domain($cdom,'primary');
                   8573:     }
                   8574:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8575:         my $info;
                   8576:         if (ref($inforef) eq 'HASH') {
                   8577:             $info = &freeze_escape($inforef);
                   8578:         }
                   8579:         if (ref($gradesref) eq 'HASH') {
                   8580:             my $grades = &freeze_escape($gradesref);
                   8581:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8582:                                 $info.':'.$grades,$homeserver);
                   8583:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8584:                 my @items = split(/&/,$response);
                   8585:                 foreach my $item (@items) {
                   8586:                     my ($key,$value) = split('=',$item);
                   8587:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8588:                 }
                   8589:             }
                   8590:         }
                   8591:     }
                   8592:     return \%exportresponse;
                   8593: }
                   8594: 
1.1172.2.68  raeburn  8595: sub check_instcode_cloning {
                   8596:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8597:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8598:         return;
                   8599:     }
                   8600:     my $canclone;
                   8601:     if (@{$code_order} > 0) {
                   8602:         my $instcoderegexp ='^';
                   8603:         my @clonecodes = split(/\&/,$cloner);
                   8604:         foreach my $item (@{$code_order}) {
                   8605:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8606:                 foreach my $pair (@clonecodes) {
                   8607:                     my ($key,$val) = split(/\=/,$pair,2);
                   8608:                     $val = &unescape($val);
                   8609:                     if ($key eq $item) {
                   8610:                         $instcoderegexp .= '('.$val.')';
                   8611:                         last;
                   8612:                     }
                   8613:                 }
                   8614:             } else {
                   8615:                 $instcoderegexp .= $codedefaults->{$item};
                   8616:             }
                   8617:         }
                   8618:         $instcoderegexp .= '$';
                   8619:         my (@from,@to);
                   8620:         eval {
                   8621:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8622:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8623:         };
                   8624:         if ((@from > 0) && (@to > 0)) {
                   8625:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8626:             if (!@diffs) {
                   8627:                 $canclone = 1;
                   8628:             }
                   8629:         }
                   8630:     }
                   8631:     return $canclone;
                   8632: }
                   8633: 
                   8634: sub default_instcode_cloning {
                   8635:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8636:     my (%codedefaults,@code_order,$canclone);
                   8637:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8638:         %codedefaults = %{$codedefaultsref};
                   8639:         @code_order = @{$codeorderref};
                   8640:     } elsif ($clonedom) {
                   8641:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8642:     }
                   8643:     if (($domdefclone) && (@code_order)) {
                   8644:         my @clonecodes = split(/\+/,$domdefclone);
                   8645:         my $instcoderegexp ='^';
                   8646:         foreach my $item (@code_order) {
                   8647:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8648:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8649:             } else {
                   8650:                 $instcoderegexp .= $codedefaults{$item};
                   8651:             }
                   8652:         }
                   8653:         $instcoderegexp .= '$';
                   8654:         my (@from,@to);
                   8655:         eval {
                   8656:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8657:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8658:         };
                   8659:         if ((@from > 0) && (@to > 0)) {
                   8660:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8661:             if (!@diffs) {
                   8662:                 $canclone = 1;
                   8663:             }
                   8664:         }
                   8665:     }
                   8666:     return $canclone;
                   8667: }
                   8668: 
1.679     raeburn  8669: # ------------------------------------------------------- Course Group routines
                   8670: 
                   8671: sub get_coursegroups {
1.809     raeburn  8672:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8673:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8674: }
                   8675: 
1.679     raeburn  8676: sub modify_coursegroup {
                   8677:     my ($cdom,$cnum,$groupsettings) = @_;
                   8678:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8679: }
                   8680: 
1.809     raeburn  8681: sub toggle_coursegroup_status {
                   8682:     my ($cdom,$cnum,$group,$action) = @_;
                   8683:     my ($from_namespace,$to_namespace);
                   8684:     if ($action eq 'delete') {
                   8685:         $from_namespace = 'coursegroups';
                   8686:         $to_namespace = 'deleted_groups';
                   8687:     } else {
                   8688:         $from_namespace = 'deleted_groups';
                   8689:         $to_namespace = 'coursegroups';
                   8690:     }
                   8691:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8692:     if (my $tmp = &error(%curr_group)) {
                   8693:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8694:         return ('read error',$tmp);
                   8695:     } else {
                   8696:         my %savedsettings = %curr_group; 
1.809     raeburn  8697:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8698:         my $deloutcome;
                   8699:         if ($result eq 'ok') {
1.809     raeburn  8700:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8701:         } else {
                   8702:             return ('write error',$result);
                   8703:         }
                   8704:         if ($deloutcome eq 'ok') {
                   8705:             return 'ok';
                   8706:         } else {
                   8707:             return ('delete error',$deloutcome);
                   8708:         }
                   8709:     }
                   8710: }
                   8711: 
1.679     raeburn  8712: sub modify_group_roles {
1.957     raeburn  8713:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8714:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8715:     my $role = 'gr/'.&escape($userprivs);
                   8716:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8717:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8718:     if ($result eq 'ok') {
                   8719:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8720:     }
1.679     raeburn  8721:     return $result;
                   8722: }
                   8723: 
                   8724: sub modify_coursegroup_membership {
                   8725:     my ($cdom,$cnum,$membership) = @_;
                   8726:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8727:     return $result;
                   8728: }
                   8729: 
1.682     raeburn  8730: sub get_active_groups {
                   8731:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8732:     my $now = time;
                   8733:     my %groups = ();
                   8734:     foreach my $key (keys(%env)) {
1.811     albertel 8735:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8736:             my ($start,$end) = split(/\./,$env{$key});
                   8737:             if (($end!=0) && ($end<$now)) { next; }
                   8738:             if (($start!=0) && ($start>$now)) { next; }
                   8739:             if ($1 eq $cdom && $2 eq $cnum) {
                   8740:                 $groups{$3} = $env{$key} ;
                   8741:             }
                   8742:         }
                   8743:     }
                   8744:     return %groups;
                   8745: }
                   8746: 
1.683     raeburn  8747: sub get_group_membership {
                   8748:     my ($cdom,$cnum,$group) = @_;
                   8749:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8750: }
                   8751: 
                   8752: sub get_users_groups {
                   8753:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8754:     my @usersgroups;
1.683     raeburn  8755:     my $cachetime=1800;
                   8756: 
                   8757:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8758:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8759:     if (defined($cached)) {
1.734     albertel 8760:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8761:     } else {  
                   8762:         $grouplist = '';
1.816     raeburn  8763:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8764:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8765:         my $access_end = $env{'course.'.$courseid.
                   8766:                               '.default_enrollment_end_date'};
                   8767:         my $now = time;
                   8768:         foreach my $key (keys(%roleshash)) {
                   8769:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8770:                 my $group = $1;
                   8771:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8772:                     my $start = $2;
                   8773:                     my $end = $1;
                   8774:                     if ($start == -1) { next; } # deleted from group
                   8775:                     if (($start!=0) && ($start>$now)) { next; }
                   8776:                     if (($end!=0) && ($end<$now)) {
                   8777:                         if ($access_end && $access_end < $now) {
                   8778:                             if ($access_end - $end < 86400) {
                   8779:                                 push(@usersgroups,$group);
1.733     raeburn  8780:                             }
                   8781:                         }
1.817     raeburn  8782:                         next;
1.733     raeburn  8783:                     }
1.817     raeburn  8784:                     push(@usersgroups,$group);
1.683     raeburn  8785:                 }
                   8786:             }
                   8787:         }
1.817     raeburn  8788:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8789:         $grouplist = join(':',@usersgroups);
                   8790:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8791:     }
1.733     raeburn  8792:     return @usersgroups;
1.683     raeburn  8793: }
                   8794: 
                   8795: sub devalidate_getgroups_cache {
                   8796:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8797:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8798: 
1.683     raeburn  8799:     my $hashid="$udom:$uname:$courseid";
                   8800:     &devalidate_cache_new('getgroups',$hashid);
                   8801: }
                   8802: 
1.12      www      8803: # ------------------------------------------------------------------ Plain Text
                   8804: 
                   8805: sub plaintext {
1.988     raeburn  8806:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8807:     if ($short =~ m{^cr/}) {
1.758     albertel 8808: 	return (split('/',$short))[-1];
                   8809:     }
1.742     raeburn  8810:     if (!defined($cid)) {
                   8811:         $cid = $env{'request.course.id'};
                   8812:     }
                   8813:     my %rolenames = (
1.1008    raeburn  8814:                       Course    => 'std',
                   8815:                       Community => 'alt1',
1.742     raeburn  8816:                     );
1.1037    raeburn  8817:     if ($cid ne '') {
                   8818:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8819:             unless ($forcedefault) {
                   8820:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8821:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8822:                 return &Apache::lonlocal::mt($roletext);
                   8823:             }
                   8824:         }
                   8825:     }
                   8826:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8827:         (defined($rolenames{$type})) && 
                   8828:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8829:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8830:     } elsif ($cid ne '') {
                   8831:         my $crstype = $env{'course.'.$cid.'.type'};
                   8832:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8833:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8834:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8835:         }
1.742     raeburn  8836:     }
1.1037    raeburn  8837:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8838: }
                   8839: 
                   8840: # ----------------------------------------------------------------- Assign Role
                   8841: 
                   8842: sub assignrole {
1.957     raeburn  8843:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8844:         $context)=@_;
1.21      www      8845:     my $mrole;
                   8846:     if ($role =~ /^cr\//) {
1.393     www      8847:         my $cwosec=$url;
1.811     albertel 8848:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8849: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8850:            my $refused = 1;
                   8851:            if ($context eq 'requestcourses') {
                   8852:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8853:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8854:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8855:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8856:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8857:                            if ($crsenv{'internal.courseowner'} eq
                   8858:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8859:                                $refused = '';
                   8860:                            }
                   8861:                        }
                   8862:                    }
                   8863:                }
                   8864:            }
                   8865:            if ($refused) {
                   8866:                &logthis('Refused custom assignrole: '.
                   8867:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8868:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8869:                return 'refused';
                   8870:            }
1.104     www      8871:         }
1.21      www      8872:         $mrole='cr';
1.678     raeburn  8873:     } elsif ($role =~ /^gr\//) {
                   8874:         my $cwogrp=$url;
1.811     albertel 8875:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8876:         unless (&allowed('mdg',$cwogrp)) {
                   8877:             &logthis('Refused group assignrole: '.
                   8878:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8879:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8880:             return 'refused';
                   8881:         }
                   8882:         $mrole='gr';
1.21      www      8883:     } else {
1.82      www      8884:         my $cwosec=$url;
1.811     albertel 8885:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8886:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8887:             my $refused;
                   8888:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8889:                 if (!(&allowed('c'.$role,$url))) {
                   8890:                     $refused = 1;
                   8891:                 }
                   8892:             } else {
                   8893:                 $refused = 1;
                   8894:             }
1.947     raeburn  8895:             if ($refused) {
1.1045    raeburn  8896:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8897:                 if (!$selfenroll && $context eq 'course') {
                   8898:                     my %crsenv;
                   8899:                     if ($role eq 'cc' || $role eq 'co') {
                   8900:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8901:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8902:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8903:                                 if ($crsenv{'internal.courseowner'} eq 
                   8904:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8905:                                     $refused = '';
                   8906:                                 }
                   8907:                             }
                   8908:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8909:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8910:                                 if ($crsenv{'internal.courseowner'} eq 
                   8911:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8912:                                     $refused = '';
                   8913:                                 }
                   8914:                             }
                   8915:                         }
                   8916:                     }
                   8917:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8918:                     $refused = '';
1.1017    raeburn  8919:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8920:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8921:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8922:                         my $wrongcc;
                   8923:                         if ($cnum =~ /^$match_community$/) {
                   8924:                             $wrongcc = 1 if ($role eq 'cc');
                   8925:                         } else {
                   8926:                             $wrongcc = 1 if ($role eq 'co');
                   8927:                         }
                   8928:                         unless ($wrongcc) {
                   8929:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8930:                             if ($crsenv{'internal.courseowner'} eq 
                   8931:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8932:                                 $refused = '';
                   8933:                             }
1.1017    raeburn  8934:                         }
                   8935:                     }
1.1172.2.9  raeburn  8936:                 } elsif ($context eq 'requestauthor') {
                   8937:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   8938:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8939:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8940:                             $refused = '';
                   8941:                         } else {
                   8942:                             my %domdefaults = &get_domain_defaults($udom);
                   8943:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8944:                                 my $checkbystatus;
                   8945:                                 if ($env{'user.adv'}) {
                   8946:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8947:                                     if ($disposition eq 'automatic') {
                   8948:                                         $refused = '';
                   8949:                                     } elsif ($disposition eq '') {
                   8950:                                         $checkbystatus = 1;
                   8951:                                     }
                   8952:                                 } else {
                   8953:                                     $checkbystatus = 1;
                   8954:                                 }
                   8955:                                 if ($checkbystatus) {
                   8956:                                     if ($env{'environment.inststatus'}) {
                   8957:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8958:                                         foreach my $type (@inststatuses) {
                   8959:                                             if (($type ne '') &&
                   8960:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8961:                                                 $refused = '';
                   8962:                                             }
                   8963:                                         }
                   8964:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8965:                                         $refused = '';
                   8966:                                     }
                   8967:                                 }
                   8968:                             }
                   8969:                         }
                   8970:                     }
1.1017    raeburn  8971:                 }
                   8972:                 if ($refused) {
1.947     raeburn  8973:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8974:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8975: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8976:                     return 'refused';
                   8977:                 }
1.932     raeburn  8978:             }
1.1131    raeburn  8979:         } elsif ($role eq 'au') {
                   8980:             if ($url ne '/'.$udom.'/') {
                   8981:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8982:                          ' to assign author role for '.$uname.':'.$udom.
                   8983:                          ' in domain: '.$url.' refused (wrong domain).');
                   8984:                 return 'refused';
                   8985:             }
1.104     www      8986:         }
1.21      www      8987:         $mrole=$role;
                   8988:     }
1.620     albertel 8989:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8990:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8991:     if ($end) { $command.='_'.$end; }
1.21      www      8992:     if ($start) {
                   8993: 	if ($end) { 
1.81      www      8994:            $command.='_'.$start; 
1.21      www      8995:         } else {
1.81      www      8996:            $command.='_0_'.$start;
1.21      www      8997:         }
                   8998:     }
1.739     raeburn  8999:     my $origstart = $start;
                   9000:     my $origend = $end;
1.957     raeburn  9001:     my $delflag;
1.357     www      9002: # actually delete
                   9003:     if ($deleteflag) {
1.373     www      9004: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9005: # modify command to delete the role
1.620     albertel 9006:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9007:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9008: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9009: # set start and finish to negative values for userrolelog
                   9010:            $start=-1;
                   9011:            $end=-1;
1.957     raeburn  9012:            $delflag = 1;
1.357     www      9013:         }
                   9014:     }
                   9015: # send command
1.349     www      9016:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9017: # log new user role if status is ok
1.349     www      9018:     if ($answer eq 'ok') {
1.663     raeburn  9019: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9020:         if (($role eq 'cc') || ($role eq 'in') ||
                   9021:             ($role eq 'ep') || ($role eq 'ad') ||
                   9022:             ($role eq 'ta') || ($role eq 'st') ||
                   9023:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9024:             ($role eq 'co')) {
1.1172.2.13  raeburn  9025: # for course roles, perform group memberships changes triggered by role change.
                   9026:             unless ($role =~ /^gr/) {
                   9027:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9028:                                                  $origstart,$selfenroll,$context);
                   9029:             }
1.1172.2.9  raeburn  9030:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9031:                            $selfenroll,$context);
                   9032:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9033:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9034:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9035:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9036:                            $context);
                   9037:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9038:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9039:                              $context);
                   9040:         }
1.1053    raeburn  9041:         if ($role eq 'cc') {
                   9042:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9043:         }
1.349     www      9044:     }
                   9045:     return $answer;
1.169     harris41 9046: }
                   9047: 
1.1053    raeburn  9048: sub autoupdate_coowners {
                   9049:     my ($url,$end,$start,$uname,$udom) = @_;
                   9050:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9051:     if (($cdom ne '') && ($cnum ne '')) {
                   9052:         my $now = time;
                   9053:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9054:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9055:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9056:             my $instcode = $coursehash{'internal.coursecode'};
                   9057:             if ($instcode ne '') {
1.1056    raeburn  9058:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9059:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9060:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9061:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9062:                         if ($result eq 'valid') {
                   9063:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9064:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9065:                                     push(@newcoowners,$coowner);
                   9066:                                 }
                   9067:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9068:                                     push(@newcoowners,$uname.':'.$udom);
                   9069:                                 }
                   9070:                                 @newcoowners = sort(@newcoowners);
                   9071:                             } else {
                   9072:                                 push(@newcoowners,$uname.':'.$udom);
                   9073:                             }
                   9074:                         } else {
                   9075:                             if ($coursehash{'internal.co-owners'}) {
                   9076:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9077:                                     unless ($coowner eq $uname.':'.$udom) {
                   9078:                                         push(@newcoowners,$coowner);
                   9079:                                     }
                   9080:                                 }
                   9081:                                 unless (@newcoowners > 0) {
                   9082:                                     $delcoowners = 1;
                   9083:                                     $coowners = '';
                   9084:                                 }
                   9085:                             }
                   9086:                         }
                   9087:                         if (@newcoowners || $delcoowners) {
                   9088:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9089:                                             $delcoowners,@newcoowners);
                   9090:                         }
                   9091:                     }
                   9092:                 }
                   9093:             }
                   9094:         }
                   9095:     }
                   9096: }
                   9097: 
                   9098: sub store_coowners {
                   9099:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9100:     my $cid = $cdom.'_'.$cnum;
                   9101:     my ($coowners,$delresult,$putresult);
                   9102:     if (@newcoowners) {
                   9103:         $coowners = join(',',@newcoowners);
                   9104:         my %coownershash = (
                   9105:                             'internal.co-owners' => $coowners,
                   9106:                            );
                   9107:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9108:         if ($putresult eq 'ok') {
                   9109:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9110:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9111:             }
                   9112:         }
                   9113:     }
                   9114:     if ($delcoowners) {
                   9115:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9116:         if ($delresult eq 'ok') {
                   9117:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9118:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9119:             }
                   9120:         }
                   9121:     }
                   9122:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9123:         my %crsinfo =
                   9124:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9125:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9126:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9127:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9128:         }
                   9129:     }
                   9130: }
                   9131: 
1.169     harris41 9132: # -------------------------------------------------- Modify user authentication
1.197     www      9133: # Overrides without validation
                   9134: 
1.169     harris41 9135: sub modifyuserauth {
                   9136:     my ($udom,$uname,$umode,$upass)=@_;
                   9137:     my $uhome=&homeserver($uname,$udom);
1.197     www      9138:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9139:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9140:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9141:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9142:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9143: 		     &escape($upass),$uhome);
1.620     albertel 9144:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9145:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9146:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9147:     &log($udom,,$uname,$uhome,
1.620     albertel 9148:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9149:                                      $env{'user.name'}.', '.$umode.
1.197     www      9150:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9151:     unless ($reply eq 'ok') {
1.197     www      9152:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9153: 	return 'error: '.$reply;
                   9154:     }   
1.170     harris41 9155:     return 'ok';
1.80      www      9156: }
                   9157: 
1.81      www      9158: # --------------------------------------------------------------- Modify a user
1.80      www      9159: 
1.81      www      9160: sub modifyuser {
1.206     matthew  9161:     my ($udom,    $uname, $uid,
                   9162:         $umode,   $upass, $first,
                   9163:         $middle,  $last,  $gene,
1.1058    raeburn  9164:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9165:     $udom= &LONCAPA::clean_domain($udom);
                   9166:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9167:     my $showcandelete = 'none';
                   9168:     if (ref($candelete) eq 'ARRAY') {
                   9169:         if (@{$candelete} > 0) {
                   9170:             $showcandelete = join(', ',@{$candelete});
                   9171:         }
                   9172:     }
1.81      www      9173:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9174:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9175: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9176:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9177:                                      ' desiredhome not specified'). 
1.620     albertel 9178:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9179:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9180:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9181:     my $newuser;
                   9182:     if ($uhome eq 'no_host') {
                   9183:         $newuser = 1;
                   9184:     }
1.80      www      9185: # ----------------------------------------------------------------- Create User
1.406     albertel 9186:     if (($uhome eq 'no_host') && 
                   9187: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9188:         my $unhome='';
1.844     albertel 9189:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9190:             $unhome = $desiredhome;
1.620     albertel 9191: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9192: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9193:         } else { # load balancing routine for determining $unhome
1.81      www      9194:             my $loadm=10000000;
1.841     albertel 9195: 	    my %servers = &get_servers($udom,'library');
                   9196: 	    foreach my $tryserver (keys(%servers)) {
                   9197: 		my $answer=reply('load',$tryserver);
                   9198: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9199: 		    $loadm=$answer;
                   9200: 		    $unhome=$tryserver;
                   9201: 		}
1.80      www      9202: 	    }
                   9203:         }
                   9204:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9205: 	    return 'error: unable to find a home server for '.$uname.
                   9206:                    ' in domain '.$udom;
1.80      www      9207:         }
                   9208:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9209:                          &escape($upass),$unhome);
                   9210: 	unless ($reply eq 'ok') {
                   9211:             return 'error: '.$reply;
                   9212:         }   
1.230     stredwic 9213:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9214:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9215: 	    return 'error: unable verify users home machine.';
1.80      www      9216:         }
1.209     matthew  9217:     }   # End of creation of new user
1.80      www      9218: # ---------------------------------------------------------------------- Add ID
                   9219:     if ($uid) {
                   9220:        $uid=~tr/A-Z/a-z/;
                   9221:        my %uidhash=&idrget($udom,$uname);
1.196     www      9222:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9223:          && (!$forceid)) {
1.80      www      9224: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9225: 	      return 'error: user id "'.$uid.'" does not match '.
                   9226:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9227:           }
                   9228:        } else {
                   9229: 	  &idput($udom,($uname => $uid));
                   9230:        }
                   9231:     }
                   9232: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9233:     my @tmp=&get('environment',
1.899     raeburn  9234: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9235:                     'permanentemail','inststatus'],
1.134     albertel 9236: 		   $udom,$uname);
1.1075    raeburn  9237:     my (%names,%oldnames);
1.313     matthew  9238:     if ($tmp[0] =~ m/^error:.*/) { 
                   9239:         %names=(); 
                   9240:     } else {
                   9241:         %names = @tmp;
1.1075    raeburn  9242:         %oldnames = %names;
1.313     matthew  9243:     }
1.388     www      9244: #
1.1058    raeburn  9245: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9246: # of users did not contain them), do not overwrite existing values
                   9247: # unless field is in $candelete array ref.  
                   9248: #
                   9249: 
                   9250:     my @fields = ('firstname','middlename','lastname','generation',
                   9251:                   'permanentemail','id');
                   9252:     my %newvalues;
                   9253:     if (ref($candelete) eq 'ARRAY') {
                   9254:         foreach my $field (@fields) {
                   9255:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9256:                 if ($field eq 'firstname') {
                   9257:                     $names{$field} = $first;
                   9258:                 } elsif ($field eq 'middlename') {
                   9259:                     $names{$field} = $middle;
                   9260:                 } elsif ($field eq 'lastname') {
                   9261:                     $names{$field} = $last;
                   9262:                 } elsif ($field eq 'generation') { 
                   9263:                     $names{$field} = $gene;
                   9264:                 } elsif ($field eq 'permanentemail') {
                   9265:                     $names{$field} = $email;
                   9266:                 } elsif ($field eq 'id') {
                   9267:                     $names{$field}  = $uid;
                   9268:                 }
                   9269:             }
                   9270:         }
                   9271:     }
1.388     www      9272:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9273:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9274:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9275:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9276:     if ($email) {
                   9277:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9278:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9279:     }
1.899     raeburn  9280:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9281:     if (defined($inststatus)) {
                   9282:         $names{'inststatus'} = '';
                   9283:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9284:         if (ref($usertypes) eq 'HASH') {
                   9285:             my @okstatuses; 
                   9286:             foreach my $item (split(/:/,$inststatus)) {
                   9287:                 if (defined($usertypes->{$item})) {
                   9288:                     push(@okstatuses,$item);  
                   9289:                 }
                   9290:             }
                   9291:             if (@okstatuses) {
                   9292:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9293:             }
                   9294:         }
                   9295:     }
1.1075    raeburn  9296:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9297:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9298:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9299:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9300:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9301:     } else {
                   9302:         $logmsg .= ' during self creation';
                   9303:     }
1.1075    raeburn  9304:     my $changed;
                   9305:     if ($newuser) {
                   9306:         $changed = 1;
                   9307:     } else {
                   9308:         foreach my $field (@fields) {
                   9309:             if ($names{$field} ne $oldnames{$field}) {
                   9310:                 $changed = 1;
                   9311:                 last;
                   9312:             }
                   9313:         }
                   9314:     }
                   9315:     unless ($changed) {
                   9316:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9317:         &logthis($logmsg);
                   9318:         return 'ok';
                   9319:     }
                   9320:     my $reply = &put('environment', \%names, $udom,$uname);
                   9321:     if ($reply ne 'ok') { 
                   9322:         return 'error: '.$reply;
                   9323:     }
1.1087    raeburn  9324:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9325:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9326:     }
1.1075    raeburn  9327:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9328:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9329:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9330:     &logthis($logmsg);
1.134     albertel 9331:     return 'ok';
1.80      www      9332: }
                   9333: 
1.81      www      9334: # -------------------------------------------------------------- Modify student
1.80      www      9335: 
1.81      www      9336: sub modifystudent {
                   9337:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9338:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9339:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9340:     if (!$cid) {
1.620     albertel 9341: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9342: 	    return 'not_in_class';
                   9343: 	}
1.80      www      9344:     }
                   9345: # --------------------------------------------------------------- Make the user
1.81      www      9346:     my $reply=&modifyuser
1.209     matthew  9347: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9348:          $desiredhome,$email,$inststatus);
1.80      www      9349:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9350:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9351:     # student's environment
1.297     matthew  9352:     $uid = undef if (!$forceid);
1.455     albertel 9353:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9354: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9355:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9356:     return $reply;
                   9357: }
                   9358: 
                   9359: sub modify_student_enrollment {
1.1172.2.23  raeburn  9360:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9361:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9362:     my ($cdom,$cnum,$chome);
                   9363:     if (!$cid) {
1.620     albertel 9364: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9365: 	    return 'not_in_class';
                   9366: 	}
1.620     albertel 9367: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9368: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9369:     } else {
                   9370: 	($cdom,$cnum)=split(/_/,$cid);
                   9371:     }
1.620     albertel 9372:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9373:     if (!$chome) {
1.457     raeburn  9374: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9375:     }
1.455     albertel 9376:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9377:     # Make sure the user exists
1.81      www      9378:     my $uhome=&homeserver($uname,$udom);
                   9379:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9380: 	return 'error: no such user';
                   9381:     }
1.297     matthew  9382:     # Get student data if we were not given enough information
                   9383:     if (!defined($first)  || $first  eq '' || 
                   9384:         !defined($last)   || $last   eq '' || 
                   9385:         !defined($uid)    || $uid    eq '' || 
                   9386:         !defined($middle) || $middle eq '' || 
                   9387:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9388:         # They did not supply us with enough data to enroll the student, so
                   9389:         # we need to pick up more information.
1.297     matthew  9390:         my %tmp = &get('environment',
1.294     matthew  9391:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9392:                        ,$udom,$uname);
                   9393: 
1.800     albertel 9394:         #foreach my $key (keys(%tmp)) {
                   9395:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9396:         #}
1.294     matthew  9397:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9398:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9399:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9400:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9401:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9402:     }
1.556     albertel 9403:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9404:     my $user = "$uname:$udom";
                   9405:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9406:     my $reply=cput('classlist',
1.1148    raeburn  9407: 		   {$user => 
1.1172.2.76  raeburn  9408: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9409: 		   $cdom,$cnum);
1.1148    raeburn  9410:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9411:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9412:     } else { 
1.81      www      9413: 	return 'error: '.$reply;
                   9414:     }
1.297     matthew  9415:     # Add student role to user
1.83      www      9416:     my $uurl='/'.$cid;
1.81      www      9417:     $uurl=~s/\_/\//g;
                   9418:     if ($usec) {
                   9419: 	$uurl.='/'.$usec;
                   9420:     }
1.1148    raeburn  9421:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9422:                              $selfenroll,$context);
                   9423:     if ($result ne 'ok') {
                   9424:         if ($old_entry{$user} ne '') {
                   9425:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9426:         } else {
                   9427:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9428:         }
                   9429:     }
                   9430:     return $result; 
1.21      www      9431: }
                   9432: 
1.556     albertel 9433: sub format_name {
                   9434:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9435:     my $name;
                   9436:     if ($first ne 'lastname') {
                   9437: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9438:     } else {
                   9439: 	if ($lastname=~/\S/) {
                   9440: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9441: 	    $name=~s/\s+,/,/;
                   9442: 	} else {
                   9443: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9444: 	}
                   9445:     }
                   9446:     $name=~s/^\s+//;
                   9447:     $name=~s/\s+$//;
                   9448:     $name=~s/\s+/ /g;
                   9449:     return $name;
                   9450: }
                   9451: 
1.84      www      9452: # ------------------------------------------------- Write to course preferences
                   9453: 
                   9454: sub writecoursepref {
                   9455:     my ($courseid,%prefs)=@_;
                   9456:     $courseid=~s/^\///;
                   9457:     $courseid=~s/\_/\//g;
                   9458:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9459:     my $chome=homeserver($cnum,$cdomain);
                   9460:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9461: 	return 'error: no such course';
                   9462:     }
                   9463:     my $cstring='';
1.800     albertel 9464:     foreach my $pref (keys(%prefs)) {
                   9465: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9466:     }
1.84      www      9467:     $cstring=~s/\&$//;
                   9468:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9469: }
                   9470: 
                   9471: # ---------------------------------------------------------- Make/modify course
                   9472: 
                   9473: sub createcourse {
1.741     raeburn  9474:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9475:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9476:     $url=&declutter($url);
                   9477:     my $cid='';
1.1028    raeburn  9478:     if ($context eq 'requestcourses') {
                   9479:         my $can_create = 0;
                   9480:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9481:         if ($udom eq $ownerdom) {
                   9482:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9483:                                   $context)) {
                   9484:                 $can_create = 1;
                   9485:             }
                   9486:         } else {
                   9487:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9488:                                            $category);
                   9489:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9490:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9491:                 if (@curr > 0) {
                   9492:                     my @options = qw(approval validate autolimit);
                   9493:                     my $optregex = join('|',@options);
                   9494:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9495:                         $can_create = 1;
                   9496:                     }
                   9497:                 }
                   9498:             }
                   9499:         }
                   9500:         if ($can_create) {
                   9501:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9502:                 unless (&allowed('ccc',$udom)) {
                   9503:                     return 'refused'; 
                   9504:                 }
1.1017    raeburn  9505:             }
                   9506:         } else {
                   9507:             return 'refused';
                   9508:         }
1.1028    raeburn  9509:     } elsif (!&allowed('ccc',$udom)) {
                   9510:         return 'refused';
1.84      www      9511:     }
1.1011    raeburn  9512: # --------------------------------------------------------------- Get Unique ID
                   9513:     my $uname;
                   9514:     if ($cnum =~ /^$match_courseid$/) {
                   9515:         my $chome=&homeserver($cnum,$udom,'true');
                   9516:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9517:             $uname = $cnum;
                   9518:         } else {
1.1038    raeburn  9519:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9520:         }
                   9521:     } else {
1.1038    raeburn  9522:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9523:     }
                   9524:     return $uname if ($uname =~ /^error/);
                   9525: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9526:     if (!defined($course_server)) {
                   9527:         if (defined(&domain($udom,'primary'))) {
                   9528:             $course_server = &domain($udom,'primary');
                   9529:         } else {
                   9530:             $course_server = $env{'user.home'}; 
                   9531:         }
                   9532:     }
                   9533:     my %host_servers =
                   9534:         &Apache::lonnet::get_servers($udom,'library');
                   9535:     unless ($host_servers{$course_server}) {
                   9536:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9537:     }
1.84      www      9538: # ------------------------------------------------------------- Make the course
                   9539:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9540:                       $course_server);
1.84      www      9541:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9542:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9543:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9544: 	return 'error: no such course';
                   9545:     }
1.271     www      9546: # ----------------------------------------------------------------- Course made
1.516     raeburn  9547: # log existence
1.1029    raeburn  9548:     my $now = time;
1.918     raeburn  9549:     my $newcourse = {
                   9550:                     $udom.'_'.$uname => {
1.921     raeburn  9551:                                      description => $description,
                   9552:                                      inst_code   => $inst_code,
                   9553:                                      owner       => $course_owner,
                   9554:                                      type        => $crstype,
1.1029    raeburn  9555:                                      creator     => $env{'user.name'}.':'.
                   9556:                                                     $env{'user.domain'},
                   9557:                                      created     => $now,
                   9558:                                      context     => $context,
1.918     raeburn  9559:                                                 },
                   9560:                     };
1.921     raeburn  9561:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9562: # set toplevel url
1.271     www      9563:     my $topurl=$url;
                   9564:     unless ($nonstandard) {
                   9565: # ------------------------------------------ For standard courses, make top url
                   9566:         my $mapurl=&clutter($url);
1.278     www      9567:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9568:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9569: <map>
                   9570: <resource id="1" type="start"></resource>
                   9571: <resource id="2" src="$mapurl"></resource>
                   9572: <resource id="3" type="finish"></resource>
                   9573: <link index="1" from="1" to="2"></link>
                   9574: <link index="2" from="2" to="3"></link>
                   9575: </map>
                   9576: ENDINITMAP
                   9577:         $topurl=&declutter(
1.638     albertel 9578:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9579:                           );
                   9580:     }
                   9581: # ----------------------------------------------------------- Write preferences
1.84      www      9582:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9583:                      ('description'              => $description,
                   9584:                       'url'                      => $topurl,
                   9585:                       'internal.creator'         => $env{'user.name'}.':'.
                   9586:                                                     $env{'user.domain'},
                   9587:                       'internal.created'         => $now,
                   9588:                       'internal.creationcontext' => $context)
                   9589:                     );
1.84      www      9590:     return '/'.$udom.'/'.$uname;
                   9591: }
                   9592: 
1.1011    raeburn  9593: # ------------------------------------------------------------------- Create ID
                   9594: sub generate_coursenum {
1.1038    raeburn  9595:     my ($udom,$crstype) = @_;
1.1011    raeburn  9596:     my $domdesc = &domain($udom);
                   9597:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9598:     my $first;
                   9599:     if ($crstype eq 'Community') {
                   9600:         $first = '0';
                   9601:     } else {
                   9602:         $first = int(1+rand(9)); 
                   9603:     } 
                   9604:     my $uname=$first.
1.1011    raeburn  9605:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9606:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9607:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9608: # ----------------------------------------------- Make sure that does not exist
                   9609:     my $uhome=&homeserver($uname,$udom,'true');
                   9610:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9611:         if ($crstype eq 'Community') {
                   9612:             $first = '0';
                   9613:         } else {
                   9614:             $first = int(1+rand(9));
                   9615:         }
                   9616:         $uname=$first.
1.1011    raeburn  9617:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9618:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9619:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9620:         $uhome=&homeserver($uname,$udom,'true');
                   9621:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9622:             return 'error: unable to generate unique course-ID';
                   9623:         }
                   9624:     }
                   9625:     return $uname;
                   9626: }
                   9627: 
1.813     albertel 9628: sub is_course {
1.1167    droeschl 9629:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9630:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9631: 
                   9632:     return unless $cdom and $cnum;
                   9633: 
                   9634:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9635:         '.');
                   9636: 
1.1172.2.23  raeburn  9637:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9638:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9639: }
                   9640: 
1.1015    raeburn  9641: sub store_userdata {
                   9642:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9643:     my $result;
1.1016    raeburn  9644:     if ($datakey ne '') {
1.1013    raeburn  9645:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9646:             if ($udom eq '' || $uname eq '') {
                   9647:                 $udom = $env{'user.domain'};
                   9648:                 $uname = $env{'user.name'};
                   9649:             }
                   9650:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9651:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9652:                 $result = 'error: no_host';
                   9653:             } else {
                   9654:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9655:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9656: 
                   9657:                 my $namevalue='';
                   9658:                 foreach my $key (keys(%{$storehash})) {
                   9659:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9660:                 }
                   9661:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  9662:                 unless ($namespace eq 'courserequests') {
                   9663:                     $datakey = &escape($datakey);
                   9664:                 }
1.1105    raeburn  9665:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9666:                                   $namevalue,$uhome);
1.1013    raeburn  9667:             }
                   9668:         } else {
                   9669:             $result = 'error: data to store was not a hash reference'; 
                   9670:         }
                   9671:     } else {
                   9672:         $result= 'error: invalid requestkey'; 
                   9673:     }
                   9674:     return $result;
                   9675: }
                   9676: 
1.21      www      9677: # ---------------------------------------------------------- Assign Custom Role
                   9678: 
                   9679: sub assigncustomrole {
1.957     raeburn  9680:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9681:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9682:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9683: }
                   9684: 
                   9685: # ----------------------------------------------------------------- Revoke Role
                   9686: 
                   9687: sub revokerole {
1.957     raeburn  9688:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9689:     my $now=time;
1.965     raeburn  9690:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9691: }
                   9692: 
                   9693: # ---------------------------------------------------------- Revoke Custom Role
                   9694: 
                   9695: sub revokecustomrole {
1.957     raeburn  9696:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9697:     my $now=time;
1.357     www      9698:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9699:            $deleteflag,$selfenroll,$context);
1.17      www      9700: }
                   9701: 
1.533     banghart 9702: # ------------------------------------------------------------ Disk usage
1.535     albertel 9703: sub diskusage {
1.955     raeburn  9704:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9705:     $directorypath =~ s/\/$//;
                   9706:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9707:                        .&escape($getpropath).':'.&escape($uname).':'
                   9708:                        .&escape($udom),homeserver($uname,$udom));
                   9709:     if ($listing eq 'unknown_cmd') {
                   9710:         if ($getpropath) {
                   9711:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9712:         }
                   9713:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9714:     }
1.514     albertel 9715:     return $listing;
1.512     banghart 9716: }
                   9717: 
1.566     banghart 9718: sub is_locked {
1.1096    raeburn  9719:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9720:     my @check;
                   9721:     my $is_locked;
1.1093    raeburn  9722:     push (@check,$file_name);
1.613     albertel 9723:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9724: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9725:     my ($tmp)=keys(%locked);
                   9726:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9727:     
1.566     banghart 9728:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9729:         $is_locked = 'false';
                   9730:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9731:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9732:                $is_locked = 'true';
1.1096    raeburn  9733:                if (ref($which) eq 'ARRAY') {
                   9734:                    push(@{$which},$entry);
                   9735:                } else {
                   9736:                    last;
                   9737:                }
1.745     raeburn  9738:            }
                   9739:        }
1.566     banghart 9740:     } else {
                   9741:         $is_locked = 'false';
                   9742:     }
1.1093    raeburn  9743:     return $is_locked;
1.566     banghart 9744: }
                   9745: 
1.759     albertel 9746: sub declutter_portfile {
                   9747:     my ($file) = @_;
1.833     albertel 9748:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9749:     return $file;
                   9750: }
                   9751: 
1.559     banghart 9752: # ------------------------------------------------------------- Mark as Read Only
                   9753: 
                   9754: sub mark_as_readonly {
                   9755:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9756:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9757:     my ($tmp)=keys(%current_permissions);
                   9758:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9759:     foreach my $file (@{$files}) {
1.759     albertel 9760: 	$file = &declutter_portfile($file);
1.561     banghart 9761:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9762:     }
1.613     albertel 9763:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9764:     return;
                   9765: }
                   9766: 
1.572     banghart 9767: # ------------------------------------------------------------Save Selected Files
                   9768: 
                   9769: sub save_selected_files {
                   9770:     my ($user, $path, @files) = @_;
                   9771:     my $filename = $user."savedfiles";
1.573     banghart 9772:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9773:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9774:     foreach my $file (@files) {
1.620     albertel 9775:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9776:     }
                   9777:     foreach my $file (@other_files) {
1.574     banghart 9778:         print (OUT $file."\n");
1.572     banghart 9779:     }
1.574     banghart 9780:     close (OUT);
1.572     banghart 9781:     return 'ok';
                   9782: }
                   9783: 
1.574     banghart 9784: sub clear_selected_files {
                   9785:     my ($user) = @_;
                   9786:     my $filename = $user."savedfiles";
1.1117    foxr     9787:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9788:     print (OUT undef);
                   9789:     close (OUT);
                   9790:     return ("ok");    
                   9791: }
                   9792: 
1.572     banghart 9793: sub files_in_path {
                   9794:     my ($user, $path) = @_;
                   9795:     my $filename = $user."savedfiles";
                   9796:     my %return_files;
1.1117    foxr     9797:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9798:     while (my $line_in = <IN>) {
1.574     banghart 9799:         chomp ($line_in);
                   9800:         my @paths_and_file = split (m!/!, $line_in);
                   9801:         my $file_part = pop (@paths_and_file);
                   9802:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9803:         $path_part.='/';
                   9804:         my $path_and_file = $path_part.$file_part;
                   9805:         if ($path_part eq $path) {
                   9806:             $return_files{$file_part}= 'selected';
                   9807:         }
                   9808:     }
1.574     banghart 9809:     close (IN);
                   9810:     return (\%return_files);
1.572     banghart 9811: }
                   9812: 
                   9813: # called in portfolio select mode, to show files selected NOT in current directory
                   9814: sub files_not_in_path {
                   9815:     my ($user, $path) = @_;
                   9816:     my $filename = $user."savedfiles";
                   9817:     my @return_files;
                   9818:     my $path_part;
1.1117    foxr     9819:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9820:     while (my $line = <IN>) {
1.572     banghart 9821:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9822:         my @paths_and_file = split(m|/|, $line);
                   9823:         my $file_part = pop(@paths_and_file);
                   9824:         chomp($file_part);
                   9825:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9826:         $path_part .= '/';
                   9827:         my $path_and_file = $path_part.$file_part;
                   9828:         if ($path_part ne $path) {
1.800     albertel 9829:             push(@return_files, ($path_and_file));
1.572     banghart 9830:         }
                   9831:     }
1.800     albertel 9832:     close(OUT);
1.574     banghart 9833:     return (@return_files);
1.572     banghart 9834: }
                   9835: 
1.745     raeburn  9836: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9837: 
1.745     raeburn  9838: sub get_portfile_permissions {
                   9839:     my ($domain,$user) = @_;
1.613     albertel 9840:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9841:     my ($tmp)=keys(%current_permissions);
                   9842:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9843:     return \%current_permissions;
                   9844: }
                   9845: 
                   9846: #---------------------------------------------Get portfolio file access controls
                   9847: 
1.749     raeburn  9848: sub get_access_controls {
1.745     raeburn  9849:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9850:     my %access;
                   9851:     my $real_file = $file;
                   9852:     $file =~ s/\.meta$//;
1.745     raeburn  9853:     if (defined($file)) {
1.749     raeburn  9854:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9855:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9856:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9857:             }
                   9858:         }
1.745     raeburn  9859:     } else {
1.749     raeburn  9860:         foreach my $key (keys(%{$current_permissions})) {
                   9861:             if ($key =~ /\0accesscontrol$/) {
                   9862:                 if (defined($group)) {
                   9863:                     if ($key !~ m-^\Q$group\E/-) {
                   9864:                         next;
                   9865:                     }
                   9866:                 }
                   9867:                 my ($fullpath) = split(/\0/,$key);
                   9868:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9869:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9870:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9871:                     }
                   9872:                 }
                   9873:             }
                   9874:         }
                   9875:     }
                   9876:     return %access;
                   9877: }
                   9878: 
                   9879: sub modify_access_controls {
                   9880:     my ($file_name,$changes,$domain,$user)=@_;
                   9881:     my ($outcome,$deloutcome);
                   9882:     my %store_permissions;
                   9883:     my %new_values;
                   9884:     my %new_control;
                   9885:     my %translation;
                   9886:     my @deletions = ();
                   9887:     my $now = time;
                   9888:     if (exists($$changes{'activate'})) {
                   9889:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9890:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9891:             my $numnew = scalar(@newitems);
                   9892:             for (my $i=0; $i<$numnew; $i++) {
                   9893:                 my $newkey = $newitems[$i];
                   9894:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9895:                 if ($newkey =~ /^\d+:/) { 
                   9896:                     $newkey =~ s/^(\d+)/$newid/;
                   9897:                     $translation{$1} = $newid;
                   9898:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9899:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9900:                     $translation{$1} = $newid;
                   9901:                 }
1.749     raeburn  9902:                 $new_values{$file_name."\0".$newkey} = 
                   9903:                                           $$changes{'activate'}{$newitems[$i]};
                   9904:                 $new_control{$newkey} = $now;
                   9905:             }
                   9906:         }
                   9907:     }
                   9908:     my %todelete;
                   9909:     my %changed_items;
                   9910:     foreach my $action ('delete','update') {
                   9911:         if (exists($$changes{$action})) {
                   9912:             if (ref($$changes{$action}) eq 'HASH') {
                   9913:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9914:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9915:                     if ($action eq 'delete') { 
                   9916:                         $todelete{$itemnum} = 1;
                   9917:                     } else {
                   9918:                         $changed_items{$itemnum} = $key;
                   9919:                     }
                   9920:                 }
1.745     raeburn  9921:             }
                   9922:         }
1.749     raeburn  9923:     }
                   9924:     # get lock on access controls for file.
                   9925:     my $lockhash = {
                   9926:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9927:                                                        ':'.$env{'user.domain'},
                   9928:                    }; 
                   9929:     my $tries = 0;
                   9930:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9931:    
1.1172.2.79  raeburn  9932:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9933:         $tries ++;
1.1172.2.79  raeburn  9934:         sleep(0.1);
1.749     raeburn  9935:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9936:     }
                   9937:     if ($gotlock eq 'ok') {
                   9938:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9939:         my ($tmp)=keys(%curr_permissions);
                   9940:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9941:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9942:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9943:             if (ref($curr_controls) eq 'HASH') {
                   9944:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9945:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9946:                     if (defined($todelete{$itemnum})) {
                   9947:                         push(@deletions,$file_name."\0".$control_item);
                   9948:                     } else {
                   9949:                         if (defined($changed_items{$itemnum})) {
                   9950:                             $new_control{$changed_items{$itemnum}} = $now;
                   9951:                             push(@deletions,$file_name."\0".$control_item);
                   9952:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9953:                         } else {
                   9954:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9955:                         }
                   9956:                     }
1.745     raeburn  9957:                 }
                   9958:             }
                   9959:         }
1.970     raeburn  9960:         my ($group);
                   9961:         if (&is_course($domain,$user)) {
                   9962:             ($group,my $file) = split(/\//,$file_name,2);
                   9963:         }
1.749     raeburn  9964:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9965:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9966:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9967:         #  remove lock
                   9968:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9969:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9970:         my $sqlresult =
1.970     raeburn  9971:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9972:                                     $group);
1.749     raeburn  9973:     } else {
                   9974:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9975:     }
1.749     raeburn  9976:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9977: }
                   9978: 
1.827     raeburn  9979: sub make_public_indefinitely {
                   9980:     my ($requrl) = @_;
                   9981:     my $now = time;
                   9982:     my $action = 'activate';
                   9983:     my $aclnum = 0;
                   9984:     if (&is_portfolio_url($requrl)) {
                   9985:         my (undef,$udom,$unum,$file_name,$group) =
                   9986:             &parse_portfolio_url($requrl);
                   9987:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   9988:         my %access_controls = &get_access_controls($current_perms,
                   9989:                                                    $group,$file_name);
                   9990:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9991:             my ($num,$scope,$end,$start) = 
                   9992:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   9993:             if ($scope eq 'public') {
                   9994:                 if ($start <= $now && $end == 0) {
                   9995:                     $action = 'none';
                   9996:                 } else {
                   9997:                     $action = 'update';
                   9998:                     $aclnum = $num;
                   9999:                 }
                   10000:                 last;
                   10001:             }
                   10002:         }
                   10003:         if ($action eq 'none') {
                   10004:              return 'ok';
                   10005:         } else {
                   10006:             my %changes;
                   10007:             my $newend = 0;
                   10008:             my $newstart = $now;
                   10009:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10010:             $changes{$action}{$newkey} = {
                   10011:                 type => 'public',
                   10012:                 time => {
                   10013:                     start => $newstart,
                   10014:                     end   => $newend,
                   10015:                 },
                   10016:             };
                   10017:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10018:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10019:             return $outcome;
                   10020:         }
                   10021:     } else {
                   10022:         return 'invalid';
                   10023:     }
                   10024: }
                   10025: 
1.745     raeburn  10026: #------------------------------------------------------Get Marked as Read Only
                   10027: 
                   10028: sub get_marked_as_readonly {
                   10029:     my ($domain,$user,$what,$group) = @_;
                   10030:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10031:     my @readonly_files;
1.629     banghart 10032:     my $cmp1=$what;
                   10033:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10034:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10035:         if (defined($group)) {
                   10036:             if ($file_name !~ m-^\Q$group\E/-) {
                   10037:                 next;
                   10038:             }
                   10039:         }
1.561     banghart 10040:         if (ref($value) eq "ARRAY"){
                   10041:             foreach my $stored_what (@{$value}) {
1.629     banghart 10042:                 my $cmp2=$stored_what;
1.759     albertel 10043:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10044:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10045:                 }
1.629     banghart 10046:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10047:                     push(@readonly_files, $file_name);
1.745     raeburn  10048:                     last;
1.563     banghart 10049:                 } elsif (!defined($what)) {
                   10050:                     push(@readonly_files, $file_name);
1.745     raeburn  10051:                     last;
1.561     banghart 10052:                 }
                   10053:             }
1.745     raeburn  10054:         }
1.561     banghart 10055:     }
                   10056:     return @readonly_files;
                   10057: }
1.577     banghart 10058: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10059: 
1.577     banghart 10060: sub get_marked_as_readonly_hash {
1.745     raeburn  10061:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10062:     my %readonly_files;
1.745     raeburn  10063:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10064:         if (defined($group)) {
                   10065:             if ($file_name !~ m-^\Q$group\E/-) {
                   10066:                 next;
                   10067:             }
                   10068:         }
1.577     banghart 10069:         if (ref($value) eq "ARRAY"){
                   10070:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10071:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10072:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10073:                         if ($lock_descriptor eq 'graded') {
                   10074:                             $readonly_files{$file_name} = 'graded';
                   10075:                         } elsif ($lock_descriptor eq 'handback') {
                   10076:                             $readonly_files{$file_name} = 'handback';
                   10077:                         } else {
                   10078:                             if (!exists($readonly_files{$file_name})) {
                   10079:                                 $readonly_files{$file_name} = 'locked';
                   10080:                             }
                   10081:                         }
1.745     raeburn  10082:                     }
1.750     banghart 10083:                 } 
1.577     banghart 10084:             }
                   10085:         } 
                   10086:     }
                   10087:     return %readonly_files;
                   10088: }
1.559     banghart 10089: # ------------------------------------------------------------ Unmark as Read Only
                   10090: 
                   10091: sub unmark_as_readonly {
1.629     banghart 10092:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10093:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10094:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10095:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10096:     my $symb_crs = $what;
                   10097:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10098:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10099:     my ($tmp)=keys(%current_permissions);
                   10100:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10101:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10102:     foreach my $file (@readonly_files) {
1.759     albertel 10103: 	my $clean_file = &declutter_portfile($file);
                   10104: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10105: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10106:         my @new_locks;
                   10107:         my @del_keys;
                   10108:         if (ref($current_locks) eq "ARRAY"){
                   10109:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10110:                 my $compare=$locker;
1.749     raeburn  10111:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10112:                     $compare=join('',@{$locker});
1.746     raeburn  10113:                     if ($compare ne $symb_crs) {
                   10114:                         push(@new_locks, $locker);
                   10115:                     }
1.563     banghart 10116:                 }
                   10117:             }
1.650     albertel 10118:             if (scalar(@new_locks) > 0) {
1.563     banghart 10119:                 $current_permissions{$file} = \@new_locks;
                   10120:             } else {
                   10121:                 push(@del_keys, $file);
1.613     albertel 10122:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10123:                 delete($current_permissions{$file});
1.563     banghart 10124:             }
                   10125:         }
1.561     banghart 10126:     }
1.613     albertel 10127:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10128:     return;
                   10129: }
1.512     banghart 10130: 
1.17      www      10131: # ------------------------------------------------------------ Directory lister
                   10132: 
                   10133: sub dirlist {
1.955     raeburn  10134:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10135:     $uri=~s/^\///;
                   10136:     $uri=~s/\/$//;
1.253     stredwic 10137:     my ($udom, $uname);
1.955     raeburn  10138:     if ($getuserdir) {
1.253     stredwic 10139:         $udom = $userdomain;
                   10140:         $uname = $username;
1.955     raeburn  10141:     } else {
                   10142:         (undef,$udom,$uname)=split(/\//,$uri);
                   10143:         if(defined($userdomain)) {
                   10144:             $udom = $userdomain;
                   10145:         }
                   10146:         if(defined($username)) {
                   10147:             $uname = $username;
                   10148:         }
1.253     stredwic 10149:     }
1.955     raeburn  10150:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10151: 
1.955     raeburn  10152:     $dirRoot = $perlvar{'lonDocRoot'};
                   10153:     if (defined($getpropath)) {
                   10154:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10155:         $dirRoot =~ s/\/$//;
1.955     raeburn  10156:     } elsif (defined($getuserdir)) {
                   10157:         my $subdir=$uname.'__';
                   10158:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10159:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10160:                    ."/$udom/$subdir/$uname";
                   10161:     } elsif (defined($alternateRoot)) {
                   10162:         $dirRoot = $alternateRoot;
1.751     banghart 10163:     }
1.253     stredwic 10164: 
                   10165:     if($udom) {
                   10166:         if($uname) {
1.1135    raeburn  10167:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10168:             if ($uhome eq 'no_host') {
                   10169:                 return ([],'no_host');
                   10170:             }
1.955     raeburn  10171:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10172:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10173:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10174:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10175:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10176:             } else {
                   10177:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10178:             }
1.605     matthew  10179:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10180:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10181:                 @listing_results = split(/:/,$listing);
                   10182:             } else {
                   10183:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10184:             }
1.1135    raeburn  10185:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10186:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10187:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10188:                 return ([],$listing);
                   10189:             } else {
                   10190:                 return (\@listing_results);
1.1135    raeburn  10191:             }
1.955     raeburn  10192:         } elsif(!$alternateRoot) {
1.1136    raeburn  10193:             my (%allusers,%listerror);
1.841     albertel 10194: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10195:  	    foreach my $tryserver (keys(%servers)) {
                   10196:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10197:                                   &escape($udom),$tryserver);
                   10198:                 if ($listing eq 'unknown_cmd') {
                   10199: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10200: 				      $udom, $tryserver);
                   10201:                 } else {
                   10202:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10203:                 }
1.841     albertel 10204: 		if ($listing eq 'unknown_cmd') {
                   10205: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10206: 				      $udom, $tryserver);
                   10207: 		    @listing_results = split(/:/,$listing);
                   10208: 		} else {
                   10209: 		    @listing_results =
                   10210: 			map { &unescape($_); } split(/:/,$listing);
                   10211: 		}
1.1136    raeburn  10212:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10213:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10214:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10215:                     $listerror{$tryserver} = $listing;
                   10216:                 } else {
1.841     albertel 10217: 		    foreach my $line (@listing_results) {
                   10218: 			my ($entry) = split(/&/,$line,2);
                   10219: 			$allusers{$entry} = 1;
                   10220: 		    }
                   10221: 		}
1.253     stredwic 10222:             }
1.1136    raeburn  10223:             my @alluserslist=();
1.800     albertel 10224:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10225:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10226:             }
1.1172.2.80  raeburn  10227:             if (!%listerror) {
                   10228:                 # no errors
                   10229:                 return (\@alluserslist);
                   10230:             } elsif (scalar(keys(%servers)) == 1) {
                   10231:                 # one library server, one error
                   10232:                 my ($key) = keys(%listerror);
                   10233:                 return (\@alluserslist, $listerror{$key});
                   10234:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10235:                 # con_lost indicates that we might miss data from at least one
                   10236:                 # library server
                   10237:                 return (\@alluserslist, 'con_lost');
                   10238:             } else {
                   10239:                 # multiple library servers and no con_lost -> data should be
                   10240:                 # complete.
                   10241:                 return (\@alluserslist);
                   10242:             }
                   10243: 
1.253     stredwic 10244:         } else {
1.1136    raeburn  10245:             return ([],'missing username');
1.253     stredwic 10246:         }
1.955     raeburn  10247:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10248:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10249:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10250:         return (\@all_domains);
1.955     raeburn  10251:     } else {
1.1136    raeburn  10252:         return ([],'missing domain');
1.275     stredwic 10253:     }
                   10254: }
                   10255: 
                   10256: # --------------------------------------------- GetFileTimestamp
                   10257: # This function utilizes dirlist and returns the date stamp for
                   10258: # when it was last modified.  It will also return an error of -1
                   10259: # if an error occurs
                   10260: 
                   10261: sub GetFileTimestamp {
1.955     raeburn  10262:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10263:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10264:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10265:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10266:                                     undef,$getuserdir);
                   10267:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10268:         return -1;
                   10269:     }
                   10270:     if (ref($fileref) eq 'ARRAY') {
                   10271:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10272:         # @stats contains first the filename, then the stat output
                   10273:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10274:     } else {
                   10275:         return -1;
1.253     stredwic 10276:     }
1.26      www      10277: }
                   10278: 
1.712     albertel 10279: sub stat_file {
                   10280:     my ($uri) = @_;
1.787     albertel 10281:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10282: 
1.955     raeburn  10283:     my ($udom,$uname,$file);
1.712     albertel 10284:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10285: 	($udom,$uname,$file) =
1.811     albertel 10286: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10287: 	$file = 'userfiles/'.$file;
                   10288:     }
                   10289:     if ($uri =~ m-^/res/-) {
                   10290: 	($udom,$uname) = 
1.807     albertel 10291: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10292: 	$file = $uri;
                   10293:     }
                   10294: 
                   10295:     if (!$udom || !$uname || !$file) {
                   10296: 	# unable to handle the uri
                   10297: 	return ();
                   10298:     }
1.956     raeburn  10299:     my $getpropath;
                   10300:     if ($file =~ /^userfiles\//) {
                   10301:         $getpropath = 1;
                   10302:     }
1.1136    raeburn  10303:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10304:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10305:         return ();
                   10306:     } else {
                   10307:         if (ref($listref) eq 'ARRAY') {
                   10308:             my @stats = split('&',$listref->[0]);
                   10309: 	    shift(@stats); #filename is first
                   10310: 	    return @stats;
                   10311:         }
1.712     albertel 10312:     }
                   10313:     return ();
                   10314: }
                   10315: 
1.26      www      10316: # -------------------------------------------------------- Value of a Condition
                   10317: 
1.713     albertel 10318: # gets the value of a specific preevaluated condition
                   10319: #    stored in the string  $env{user.state.<cid>}
                   10320: # or looks up a condition reference in the bighash and if if hasn't
                   10321: # already been evaluated recurses into docondval to get the value of
                   10322: # the condition, then memoizing it to 
                   10323: #   $env{user.state.<cid>.<condition>}
1.40      www      10324: sub directcondval {
                   10325:     my $number=shift;
1.620     albertel 10326:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10327: 	&Apache::lonuserstate::evalstate();
                   10328:     }
1.713     albertel 10329:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10330: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10331:     } elsif ($number =~ /^_/) {
                   10332: 	my $sub_condition;
                   10333: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10334: 		&GDBM_READER(),0640)) {
                   10335: 	    $sub_condition=$bighash{'conditions'.$number};
                   10336: 	    untie(%bighash);
                   10337: 	}
                   10338: 	my $value = &docondval($sub_condition);
1.949     raeburn  10339: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10340: 	return $value;
                   10341:     }
1.620     albertel 10342:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10343:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10344:     } else {
                   10345:        return 2;
                   10346:     }
                   10347: }
                   10348: 
1.713     albertel 10349: # get the collection of conditions for this resource
1.26      www      10350: sub condval {
                   10351:     my $condidx=shift;
1.54      www      10352:     my $allpathcond='';
1.713     albertel 10353:     foreach my $cond (split(/\|/,$condidx)) {
                   10354: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10355: 	    $allpathcond.=
                   10356: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10357: 	}
1.191     harris41 10358:     }
1.54      www      10359:     $allpathcond=~s/\|$//;
1.713     albertel 10360:     return &docondval($allpathcond);
                   10361: }
                   10362: 
                   10363: #evaluates an expression of conditions
                   10364: sub docondval {
                   10365:     my ($allpathcond) = @_;
                   10366:     my $result=0;
                   10367:     if ($env{'request.course.id'}
                   10368: 	&& defined($allpathcond)) {
                   10369: 	my $operand='|';
                   10370: 	my @stack;
                   10371: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10372: 	    if ($chunk eq '(') {
                   10373: 		push @stack,($operand,$result);
                   10374: 	    } elsif ($chunk eq ')') {
                   10375: 		my $before=pop @stack;
                   10376: 		if (pop @stack eq '&') {
                   10377: 		    $result=$result>$before?$before:$result;
                   10378: 		} else {
                   10379: 		    $result=$result>$before?$result:$before;
                   10380: 		}
                   10381: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10382: 		$operand=$chunk;
                   10383: 	    } else {
                   10384: 		my $new=directcondval($chunk);
                   10385: 		if ($operand eq '&') {
                   10386: 		    $result=$result>$new?$new:$result;
                   10387: 		} else {
                   10388: 		    $result=$result>$new?$result:$new;
                   10389: 		}
                   10390: 	    }
                   10391: 	}
1.26      www      10392:     }
                   10393:     return $result;
1.421     albertel 10394: }
                   10395: 
                   10396: # ---------------------------------------------------- Devalidate courseresdata
                   10397: 
                   10398: sub devalidatecourseresdata {
                   10399:     my ($coursenum,$coursedomain)=@_;
                   10400:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10401:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10402: }
                   10403: 
1.763     www      10404: 
1.200     www      10405: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10406: #
                   10407: #  Parameters:
                   10408: #      $coursenum    - Number of the course.
                   10409: #      $coursedomain - Domain at which the course was created.
                   10410: #  Returns:
                   10411: #     A hash of the course parameters along (I think) with timestamps
                   10412: #     and version info.
1.877     foxr     10413: 
1.624     albertel 10414: sub get_courseresdata {
                   10415:     my ($coursenum,$coursedomain)=@_;
1.200     www      10416:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10417:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10418:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10419:     my %dumpreply;
1.417     albertel 10420:     unless (defined($cached)) {
1.624     albertel 10421: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10422: 	$result=\%dumpreply;
1.251     albertel 10423: 	my ($tmp) = keys(%dumpreply);
                   10424: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10425: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10426: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10427: 	    return $tmp;
1.416     albertel 10428: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10429: 	    $result=undef;
1.599     albertel 10430: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10431: 	}
                   10432:     }
1.624     albertel 10433:     return $result;
                   10434: }
                   10435: 
1.633     albertel 10436: sub devalidateuserresdata {
                   10437:     my ($uname,$udom)=@_;
                   10438:     my $hashid="$udom:$uname";
                   10439:     &devalidate_cache_new('userres',$hashid);
                   10440: }
                   10441: 
1.624     albertel 10442: sub get_userresdata {
                   10443:     my ($uname,$udom)=@_;
                   10444:     #most student don\'t have any data set, check if there is some data
                   10445:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10446: 
                   10447:     my $hashid="$udom:$uname";
                   10448:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10449:     if (!defined($cached)) {
                   10450: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10451: 	$result=\%resourcedata;
                   10452: 	&do_cache_new('userres',$hashid,$result,600);
                   10453:     }
                   10454:     my ($tmp)=keys(%$result);
                   10455:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10456: 	return $result;
                   10457:     }
                   10458:     #error 2 occurs when the .db doesn't exist
                   10459:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  10460:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10461: 	    &logthis("<font color=\"blue\">WARNING:".
                   10462: 		     " Trying to get resource data for ".
                   10463: 		     $uname." at ".$udom.": ".
                   10464: 		     $tmp."</font>");
                   10465:         }
1.624     albertel 10466:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10467: 	#&EXT_cache_set($udom,$uname);
                   10468: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10469: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10470:     }
                   10471:     return $tmp;
                   10472: }
1.879     foxr     10473: #----------------------------------------------- resdata - return resource data
                   10474: #  Purpose:
                   10475: #    Return resource data for either users or for a course.
                   10476: #  Parameters:
                   10477: #     $name      - Course/user name.
                   10478: #     $domain    - Name of the domain the user/course is registered on.
1.1172.2.93.2  1(raebur 10479:7): #     $type      - Type of thing $name is (must be 'course' or 'user')
1.879     foxr     10480: #     @which     - Array of names of resources desired.
                   10481: #  Returns:
                   10482: #     The value of the first reasource in @which that is found in the
                   10483: #     resource hash.
                   10484: #  Exceptional Conditions:
                   10485: #     If the $type passed in is not valid (not the string 'course' or 
                   10486: #     'user', an undefined  reference is returned.
                   10487: #     If none of the resources are found, an undef is returned
1.624     albertel 10488: sub resdata {
                   10489:     my ($name,$domain,$type,@which)=@_;
                   10490:     my $result;
                   10491:     if ($type eq 'course') {
                   10492: 	$result=&get_courseresdata($name,$domain);
                   10493:     } elsif ($type eq 'user') {
                   10494: 	$result=&get_userresdata($name,$domain);
                   10495:     }
                   10496:     if (!ref($result)) { return $result; }    
1.251     albertel 10497:     foreach my $item (@which) {
1.1172.2.93.2  1(raebur 10498:7):         if (ref($item) eq 'ARRAY') {
                   10499:7): 	    if (defined($result->{$item->[0]})) {
                   10500:7): 	        return [$result->{$item->[0]},$item->[1]];
                   10501:7): 	    }
                   10502:7):         }
1.250     albertel 10503:     }
1.291     albertel 10504:     return undef;
1.200     www      10505: }
                   10506: 
1.1172.2.31  raeburn  10507: sub get_numsuppfiles {
                   10508:     my ($cnum,$cdom,$ignorecache)=@_;
                   10509:     my $hashid=$cnum.':'.$cdom;
                   10510:     my ($suppcount,$cached);
                   10511:     unless ($ignorecache) {
                   10512:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10513:     }
                   10514:     unless (defined($cached)) {
                   10515:         my $chome=&homeserver($cnum,$cdom);
                   10516:         unless ($chome eq 'no_host') {
                   10517:             ($suppcount,my $errors) = (0,0);
                   10518:             my $suppmap = 'supplemental.sequence';
                   10519:             ($suppcount,$errors) =
                   10520:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10521:         }
                   10522:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10523:     }
                   10524:     return $suppcount;
                   10525: }
                   10526: 
1.379     matthew  10527: #
                   10528: # EXT resource caching routines
                   10529: #
                   10530: 
                   10531: sub clear_EXT_cache_status {
1.383     albertel 10532:     &delenv('cache.EXT.');
1.379     matthew  10533: }
                   10534: 
                   10535: sub EXT_cache_status {
                   10536:     my ($target_domain,$target_user) = @_;
1.383     albertel 10537:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10538:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10539:         # We know already the user has no data
                   10540:         return 1;
                   10541:     } else {
                   10542:         return 0;
                   10543:     }
                   10544: }
                   10545: 
                   10546: sub EXT_cache_set {
                   10547:     my ($target_domain,$target_user) = @_;
1.383     albertel 10548:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10549:     #&appenv({$cachename => time});
1.379     matthew  10550: }
                   10551: 
1.28      www      10552: # --------------------------------------------------------- Value of a Variable
1.58      www      10553: sub EXT {
1.715     albertel 10554: 
1.1172.2.28  raeburn  10555:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10556:     unless ($varname) { return ''; }
1.218     albertel 10557:     #get real user name/domain, courseid and symb
                   10558:     my $courseid;
1.359     albertel 10559:     my $publicuser;
1.427     www      10560:     if ($symbparm) {
                   10561: 	$symbparm=&get_symb_from_alias($symbparm);
                   10562:     }
1.218     albertel 10563:     if (!($uname && $udom)) {
1.790     albertel 10564:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10565:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10566:     } else {
1.620     albertel 10567: 	$courseid=$env{'request.course.id'};
1.218     albertel 10568:     }
1.48      www      10569:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10570:     my $rest;
1.320     albertel 10571:     if (defined($therest[0])) {
1.48      www      10572:        $rest=join('.',@therest);
                   10573:     } else {
                   10574:        $rest='';
                   10575:     }
1.320     albertel 10576: 
1.57      www      10577:     my $qualifierrest=$qualifier;
                   10578:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10579:     my $spacequalifierrest=$space;
                   10580:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10581:     if ($realm eq 'user') {
1.48      www      10582: # --------------------------------------------------------------- user.resource
                   10583: 	if ($space eq 'resource') {
1.651     albertel 10584: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10585: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10586: 		 &&
1.744     albertel 10587: 		 ($symbparm eq &symbread()) ) {	
                   10588: 		# if we are in the middle of processing the resource the
                   10589: 		# get the value we are planning on committing
                   10590:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10591:                     return $Apache::lonhomework::results{$qualifierrest};
                   10592:                 } else {
                   10593:                     return $Apache::lonhomework::history{$qualifierrest};
                   10594:                 }
1.335     albertel 10595: 	    } else {
1.359     albertel 10596: 		my %restored;
1.620     albertel 10597: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10598: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10599: 		} else {
                   10600: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10601: 		}
1.335     albertel 10602: 		return $restored{$qualifierrest};
                   10603: 	    }
1.48      www      10604: # ----------------------------------------------------------------- user.access
                   10605:         } elsif ($space eq 'access') {
1.218     albertel 10606: 	    # FIXME - not supporting calls for a specific user
1.48      www      10607:             return &allowed($qualifier,$rest);
                   10608: # ------------------------------------------ user.preferences, user.environment
                   10609:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10610: 	    if (($uname eq $env{'user.name'}) &&
                   10611: 		($udom eq $env{'user.domain'})) {
                   10612: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10613: 	    } else {
1.359     albertel 10614: 		my %returnhash;
                   10615: 		if (!$publicuser) {
                   10616: 		    %returnhash=&userenvironment($udom,$uname,
                   10617: 						 $qualifierrest);
                   10618: 		}
1.218     albertel 10619: 		return $returnhash{$qualifierrest};
                   10620: 	    }
1.48      www      10621: # ----------------------------------------------------------------- user.course
                   10622:         } elsif ($space eq 'course') {
1.218     albertel 10623: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10624:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10625: # ------------------------------------------------------------------- user.role
                   10626:         } elsif ($space eq 'role') {
1.218     albertel 10627: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10628:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10629:             if ($qualifier eq 'value') {
                   10630: 		return $role;
                   10631:             } elsif ($qualifier eq 'extent') {
                   10632:                 return $where;
                   10633:             }
                   10634: # ----------------------------------------------------------------- user.domain
                   10635:         } elsif ($space eq 'domain') {
1.218     albertel 10636:             return $udom;
1.48      www      10637: # ------------------------------------------------------------------- user.name
                   10638:         } elsif ($space eq 'name') {
1.218     albertel 10639:             return $uname;
1.48      www      10640: # ---------------------------------------------------- Any other user namespace
1.29      www      10641:         } else {
1.359     albertel 10642: 	    my %reply;
                   10643: 	    if (!$publicuser) {
                   10644: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10645: 	    }
                   10646: 	    return $reply{$qualifierrest};
1.48      www      10647:         }
1.236     www      10648:     } elsif ($realm eq 'query') {
                   10649: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10650:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10651: 						[$spacequalifierrest]);
1.620     albertel 10652: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10653:    } elsif ($realm eq 'request') {
1.48      www      10654: # ------------------------------------------------------------- request.browser
                   10655:         if ($space eq 'browser') {
1.1145    bisitz   10656:             return $env{'browser.'.$qualifier};
1.57      www      10657: # ------------------------------------------------------------ request.filename
                   10658:         } else {
1.620     albertel 10659:             return $env{'request.'.$spacequalifierrest};
1.29      www      10660:         }
1.28      www      10661:     } elsif ($realm eq 'course') {
1.48      www      10662: # ---------------------------------------------------------- course.description
1.620     albertel 10663:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10664:     } elsif ($realm eq 'resource') {
1.165     www      10665: 
1.620     albertel 10666: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10667: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10668: 	}
1.693     albertel 10669: 
1.1172.2.30  raeburn  10670:         if ($qualifier eq '') {
                   10671: 	    if ($space eq 'title') {
                   10672: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10673: 	        return &gettitle($symbparm);
                   10674: 	    }
1.693     albertel 10675: 	
1.1172.2.30  raeburn  10676: 	    if ($space eq 'map') {
                   10677: 	        my ($map) = &decode_symb($symbparm);
                   10678: 	        return &symbread($map);
                   10679: 	    }
                   10680:             if ($space eq 'maptitle') {
                   10681:                 my ($map) = &decode_symb($symbparm);
                   10682:                 return &gettitle($map);
                   10683:             }
                   10684: 	    if ($space eq 'filename') {
                   10685: 	        if ($symbparm) {
                   10686: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10687: 	        }
                   10688: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10689: 	    }
1.1172.2.30  raeburn  10690: 
                   10691:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10692:                 if ($space eq 'visibleparts') {
                   10693:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10694:                     my $item;
                   10695:                     if (ref($navmap)) {
                   10696:                         my $res = $navmap->getBySymb($symbparm);
                   10697:                         my $parts = $res->parts();
                   10698:                         if (ref($parts) eq 'ARRAY') {
                   10699:                             $item = join(',',@{$parts});
                   10700:                         }
                   10701:                         undef($navmap);
                   10702:                     }
                   10703:                     return $item;
                   10704:                 }
                   10705:             }
                   10706:         }
1.693     albertel 10707: 
                   10708: 	my ($section, $group, @groups);
1.593     albertel 10709: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  10710:         if (($courseid eq '') && ($cid)) {
                   10711:             $courseid = $cid;
                   10712:         }
                   10713: 	if (($symbparm && $courseid) && 
                   10714: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      10715: 
1.218     albertel 10716: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10717: 
1.60      www      10718: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10719: 	    my $symbp=$symbparm;
1.735     albertel 10720: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10721: 
                   10722: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10723: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10724: 
1.620     albertel 10725: 	    if (($env{'user.name'} eq $uname) &&
                   10726: 		($env{'user.domain'} eq $udom)) {
                   10727: 		$section=$env{'request.course.sec'};
1.733     raeburn  10728:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10729:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10730: 	    } else {
1.539     albertel 10731: 		if (! defined($usection)) {
1.551     albertel 10732: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10733: 		} else {
                   10734: 		    $section = $usection;
                   10735: 		}
1.733     raeburn  10736:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10737: 	    }
                   10738: 
                   10739: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10740: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10741: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10742: 
1.593     albertel 10743: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10744: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10745: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10746: 
1.60      www      10747: # ----------------------------------------------------------- first, check user
1.624     albertel 10748: 
                   10749: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10750: 				       ([$courselevelr,'resource'],
                   10751: 					[$courselevelm,'map'     ],
                   10752: 					[$courselevel, 'course'  ]));
1.931     albertel 10753: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10754: 
1.594     albertel 10755: # ------------------------------------------------ second, check some of course
1.684     raeburn  10756:             my $coursereply;
1.691     raeburn  10757:             if (@groups > 0) {
                   10758:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10759:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10760:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10761:             }
1.96      www      10762: 
1.684     raeburn  10763: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10764: 				  $env{'course.'.$courseid.'.domain'},
                   10765: 				  'course',
                   10766: 				  ([$seclevelr,   'resource'],
                   10767: 				   [$seclevelm,   'map'     ],
                   10768: 				   [$seclevel,    'course'  ],
                   10769: 				   [$courselevelr,'resource']));
                   10770: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10771: 
1.60      www      10772: # ------------------------------------------------------ third, check map parms
1.218     albertel 10773: 	    my %parmhash=();
                   10774: 	    my $thisparm='';
                   10775: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10776: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10777: 		    &GDBM_READER(),0640)) {
1.218     albertel 10778: 		$thisparm=$parmhash{$symbparm};
                   10779: 		untie(%parmhash);
                   10780: 	    }
1.927     albertel 10781: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10782: 	}
1.594     albertel 10783: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10784: 
1.218     albertel 10785: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10786: 	my $filename;
                   10787: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10788: 	if ($symbparm) {
1.409     www      10789: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10790: 	} else {
1.620     albertel 10791: 	    $filename=$env{'request.filename'};
1.282     albertel 10792: 	}
                   10793: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10794: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10795: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10796: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10797: 
1.927     albertel 10798: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10799: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10800: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10801: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10802: 				     $env{'course.'.$courseid.'.domain'},
                   10803: 				     'course',
1.927     albertel 10804: 				     ([$courselevelm,'map'   ],
                   10805: 				      [$courselevel, 'course']));
                   10806: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10807: 	}
1.145     www      10808: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10809: 	unless ($space eq '0') {
1.336     albertel 10810: 	    my @parts=split(/_/,$space);
                   10811: 	    my $id=pop(@parts);
                   10812: 	    my $part=join('_',@parts);
                   10813: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10814: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10815: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10816: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10817: 	}
1.395     albertel 10818: 	if ($recurse) { return undef; }
                   10819: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10820: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10821: # ---------------------------------------------------- Any other user namespace
                   10822:     } elsif ($realm eq 'environment') {
                   10823: # ----------------------------------------------------------------- environment
1.620     albertel 10824: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10825: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10826: 	} else {
1.770     albertel 10827: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10828: 		return '';
                   10829: 	    }
1.219     albertel 10830: 	    my %returnhash=&userenvironment($udom,$uname,
                   10831: 					    $spacequalifierrest);
                   10832: 	    return $returnhash{$spacequalifierrest};
                   10833: 	}
1.28      www      10834:     } elsif ($realm eq 'system') {
1.48      www      10835: # ----------------------------------------------------------------- system.time
                   10836: 	if ($space eq 'time') {
                   10837: 	    return time;
                   10838:         }
1.696     albertel 10839:     } elsif ($realm eq 'server') {
                   10840: # ----------------------------------------------------------------- system.time
                   10841: 	if ($space eq 'name') {
                   10842: 	    return $ENV{'SERVER_NAME'};
                   10843:         }
1.28      www      10844:     }
1.48      www      10845:     return '';
1.61      www      10846: }
                   10847: 
1.927     albertel 10848: sub get_reply {
                   10849:     my ($reply_value) = @_;
1.940     raeburn  10850:     if (ref($reply_value) eq 'ARRAY') {
                   10851:         if (wantarray) {
                   10852: 	    return @$reply_value;
                   10853:         }
                   10854:         return $reply_value->[0];
                   10855:     } else {
                   10856:         return $reply_value;
1.927     albertel 10857:     }
                   10858: }
                   10859: 
1.691     raeburn  10860: sub check_group_parms {
                   10861:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10862:     my @groupitems = ();
                   10863:     my $resultitem;
1.927     albertel 10864:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10865:     foreach my $group (@{$groups}) {
                   10866:         foreach my $level (@levels) {
1.927     albertel 10867:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10868:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10869:         }
                   10870:     }
                   10871:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10872:                             $env{'course.'.$courseid.'.domain'},
                   10873:                                      'course',@groupitems);
                   10874:     return $coursereply;
                   10875: }
                   10876: 
                   10877: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10878:     my ($courseid,@groups) = @_;
                   10879:     @groups = sort(@groups);
1.691     raeburn  10880:     return @groups;
                   10881: }
                   10882: 
1.395     albertel 10883: sub packages_tab_default {
                   10884:     my ($uri,$varname)=@_;
                   10885:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10886: 
                   10887:     my (@extension,@specifics,$do_default);
                   10888:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10889: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10890: 	if ($pack_type eq 'default') {
                   10891: 	    $do_default=1;
                   10892: 	} elsif ($pack_type eq 'extension') {
                   10893: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10894: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10895: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10896: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10897: 	}
                   10898:     }
                   10899:     # first look for a package that matches the requested part id
                   10900:     foreach my $package (@specifics) {
                   10901: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10902: 	next if ($pack_part ne $part);
                   10903: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10904: 	    return $packagetab{"$pack_type&$name&default"};
                   10905: 	}
                   10906:     }
                   10907:     # look for any possible matching non extension_ package
                   10908:     foreach my $package (@specifics) {
                   10909: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10910: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10911: 	    return $packagetab{"$pack_type&$name&default"};
                   10912: 	}
1.585     albertel 10913: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10914: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10915: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10916: 	}
                   10917:     }
1.738     albertel 10918:     # look for any posible extension_ match
                   10919:     foreach my $package (@extension) {
                   10920: 	my ($package,$pack_type)=@{$package};
                   10921: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10922: 	    return $packagetab{"$pack_type&$name&default"};
                   10923: 	}
                   10924: 	if (defined($packagetab{$package."&$name&default"})) {
                   10925: 	    return $packagetab{$package."&$name&default"};
                   10926: 	}
                   10927:     }
                   10928:     # look for a global default setting
                   10929:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10930: 	return $packagetab{"default&$name&default"};
                   10931:     }
1.395     albertel 10932:     return undef;
                   10933: }
                   10934: 
1.334     albertel 10935: sub add_prefix_and_part {
                   10936:     my ($prefix,$part)=@_;
                   10937:     my $keyroot;
                   10938:     if (defined($prefix) && $prefix !~ /^__/) {
                   10939: 	# prefix that has a part already
                   10940: 	$keyroot=$prefix;
                   10941:     } elsif (defined($prefix)) {
                   10942: 	# prefix that is missing a part
                   10943: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10944:     } else {
                   10945: 	# no prefix at all
                   10946: 	if (defined($part)) { $keyroot='_'.$part; }
                   10947:     }
                   10948:     return $keyroot;
                   10949: }
                   10950: 
1.71      www      10951: # ---------------------------------------------------------------- Get metadata
                   10952: 
1.599     albertel 10953: my %metaentry;
1.1070    www      10954: my %importedpartids;
1.71      www      10955: sub metadata {
1.176     www      10956:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10957:     $uri=&declutter($uri);
1.288     albertel 10958:     # if it is a non metadata possible uri return quickly
1.529     albertel 10959:     if (($uri eq '') || 
                   10960: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  10961: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10962:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10963: 	return undef;
                   10964:     }
1.1172.2.49  raeburn  10965:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10966: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10967: 	return undef;
1.288     albertel 10968:     }
1.73      www      10969:     my $filename=$uri;
                   10970:     $uri=~s/\.meta$//;
1.172     www      10971: #
                   10972: # Is the metadata already cached?
1.177     www      10973: # Look at timestamp of caching
1.172     www      10974: # Everything is cached by the main uri, libraries are never directly cached
                   10975: #
1.428     albertel 10976:     if (!defined($liburi)) {
1.599     albertel 10977: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10978: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10979:     }
                   10980:     {
1.1069    www      10981: # Imported parts would go here
1.1070    www      10982:         my %importedids=();
                   10983:         my @origfileimportpartids=();
1.1069    www      10984:         my $importedparts=0;
1.172     www      10985: #
                   10986: # Is this a recursive call for a library?
                   10987: #
1.599     albertel 10988: #	if (! exists($metacache{$uri})) {
                   10989: #	    $metacache{$uri}={};
                   10990: #	}
1.924     albertel 10991: 	my $cachetime = 60*60;
1.171     www      10992:         if ($liburi) {
                   10993: 	    $liburi=&declutter($liburi);
                   10994:             $filename=$liburi;
1.401     bowersj2 10995:         } else {
1.599     albertel 10996: 	    &devalidate_cache_new('meta',$uri);
                   10997: 	    undef(%metaentry);
1.401     bowersj2 10998: 	}
1.140     www      10999:         my %metathesekeys=();
1.73      www      11000:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11001: 	my $metastring;
1.1140    www      11002: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11003: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11004: 	    $metastring = 
1.929     albertel 11005: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11006: 					  ('grade_target' => 'meta'));
                   11007: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11008: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11009:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11010: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11011: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11012: 	    $metastring=&getfile($file);
1.489     albertel 11013: 	}
1.208     albertel 11014:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11015:         my $token;
1.140     www      11016:         undef %metathesekeys;
1.71      www      11017:         while ($token=$parser->get_token) {
1.339     albertel 11018: 	    if ($token->[0] eq 'S') {
                   11019: 		if (defined($token->[2]->{'package'})) {
1.172     www      11020: #
                   11021: # This is a package - get package info
                   11022: #
1.339     albertel 11023: 		    my $package=$token->[2]->{'package'};
                   11024: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11025: 		    if (defined($token->[2]->{'id'})) { 
                   11026: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11027: 		    }
1.599     albertel 11028: 		    if ($metaentry{':packages'}) {
                   11029: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11030: 		    } else {
1.599     albertel 11031: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11032: 		    }
1.736     albertel 11033: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11034: 			my $part=$keyroot;
                   11035: 			$part=~s/^\_//;
1.736     albertel 11036: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11037: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11038: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11039: 			    # ignore package.tab specified default values
                   11040:                             # here &package_tab_default() will fetch those
                   11041: 			    if ($subp eq 'default') { next; }
1.736     albertel 11042: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11043: 			    my $unikey;
                   11044: 			    if ($pack =~ /_0$/) {
                   11045: 				$unikey='parameter_0_'.$name;
                   11046: 				$part=0;
                   11047: 			    } else {
                   11048: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11049: 			    }
1.339     albertel 11050: 			    if ($subp eq 'display') {
                   11051: 				$value.=' [Part: '.$part.']';
                   11052: 			    }
1.599     albertel 11053: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11054: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11055: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11056: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11057: 			    }
1.599     albertel 11058: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11059: 				$metaentry{':'.$unikey}=
                   11060: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11061: 			    }
1.339     albertel 11062: 			}
                   11063: 		    }
                   11064: 		} else {
1.172     www      11065: #
                   11066: # This is not a package - some other kind of start tag
1.339     albertel 11067: #
                   11068: 		    my $entry=$token->[1];
1.1068    www      11069: 		    my $unikey='';
1.175     www      11070: 
1.339     albertel 11071: 		    if ($entry eq 'import') {
1.175     www      11072: #
                   11073: # Importing a library here
1.339     albertel 11074: #
1.1067    www      11075:                         my $location=$parser->get_text('/import');
                   11076:                         my $dir=$filename;
                   11077:                         $dir=~s|[^/]*$||;
                   11078:                         $location=&filelocation($dir,$location);
1.1069    www      11079:                        
1.1068    www      11080:                         my $importmode=$token->[2]->{'importmode'};
                   11081:                         if ($importmode eq 'problem') {
1.1069    www      11082: # Import as problem/response
1.1068    www      11083:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11084:                         } elsif ($importmode eq 'part') {
                   11085: # Import as part(s)
1.1069    www      11086:                            $importedparts=1;
                   11087: # We need to get the original file and the imported file to get the part order correct
                   11088: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11089: # Load and inspect original file
1.1070    www      11090:                            if ($#origfileimportpartids<0) {
                   11091:                               undef(%importedpartids);
                   11092:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11093:                               my $origfile=&getfile($origfilelocation);
                   11094:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11095:                            }
                   11096: 
1.1069    www      11097: # Load and inspect imported file
                   11098:                            my $impfile=&getfile($location);
                   11099:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11100:                            if ($#impfilepartids>=0) {
                   11101: # This problem had parts
1.1070    www      11102:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11103:                            } else {
                   11104: # Importing by turning a single problem into a problem part
                   11105: # It gets the import-tags ID as part-ID
                   11106:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11107:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11108:                            }
1.1068    www      11109:                         } else {
                   11110: # Normal import
                   11111:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11112:                            if (defined($token->[2]->{'id'})) {
                   11113:                               $unikey.='_'.$token->[2]->{'id'};
                   11114:                            }
1.1067    www      11115:                         }
                   11116: 
1.339     albertel 11117: 			if ($depthcount<20) {
1.736     albertel 11118: 			    my $metadata = 
                   11119: 				&metadata($uri,'keys', $location,$unikey,
                   11120: 					  $depthcount+1);
                   11121: 			    foreach my $meta (split(',',$metadata)) {
                   11122: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11123: 				$metathesekeys{$meta}=1;
1.339     albertel 11124: 			    }
1.1068    www      11125: 			
                   11126:                         }
1.1067    www      11127: 		    } else {
                   11128: #
                   11129: # Not importing, some other kind of non-package, non-library start tag
                   11130: # 
                   11131:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11132:                         if (defined($token->[2]->{'id'})) {
                   11133:                             $unikey.='_'.$token->[2]->{'id'};
                   11134:                         }
1.339     albertel 11135: 			if (defined($token->[2]->{'name'})) { 
                   11136: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11137: 			}
                   11138: 			$metathesekeys{$unikey}=1;
1.736     albertel 11139: 			foreach my $param (@{$token->[3]}) {
                   11140: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11141: 				$token->[2]->{$param};
1.339     albertel 11142: 			}
                   11143: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11144: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11145: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11146: 		 # only ws inside the tag, and not in default, so use default
                   11147: 		 # as value
1.599     albertel 11148: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11149: 			} elsif ( $internaltext =~ /\S/ ) {
                   11150: 		  # something interesting inside the tag
                   11151: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11152: 			} else {
1.908     albertel 11153: 		  # no interesting values, don't set a default
1.339     albertel 11154: 			}
1.172     www      11155: # end of not-a-package not-a-library import
1.339     albertel 11156: 		    }
1.172     www      11157: # end of not-a-package start tag
1.339     albertel 11158: 		}
1.172     www      11159: # the next is the end of "start tag"
1.339     albertel 11160: 	    }
                   11161: 	}
1.483     albertel 11162: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11163: 	$extension = lc($extension);
                   11164: 	if ($extension eq 'htm') { $extension='html'; }
                   11165: 
1.737     albertel 11166: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11167: 	    #no specific packages #how's our extension
                   11168: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11169: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11170: 					 \%metathesekeys);
                   11171: 	}
1.883     albertel 11172: 
                   11173: 	if (!exists($metaentry{':packages'})
                   11174: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11175: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11176: 		#no specific packages well let's get default then
                   11177: 		if ($key!~/^default&/) { next; }
1.488     albertel 11178: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11179: 					     \%metathesekeys);
                   11180: 	    }
                   11181: 	}
1.338     www      11182: # are there custom rights to evaluate
1.599     albertel 11183: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11184: 
1.338     www      11185:     #
                   11186:     # Importing a rights file here
1.339     albertel 11187:     #
                   11188: 	    unless ($depthcount) {
1.599     albertel 11189: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11190: 		my $dir=$filename;
                   11191: 		$dir=~s|[^/]*$||;
                   11192: 		$location=&filelocation($dir,$location);
1.736     albertel 11193: 		my $rights_metadata =
                   11194: 		    &metadata($uri,'keys',$location,'_rights',
                   11195: 			      $depthcount+1);
                   11196: 		foreach my $rights (split(',',$rights_metadata)) {
                   11197: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11198: 		    $metathesekeys{$rights}=1;
1.339     albertel 11199: 		}
                   11200: 	    }
                   11201: 	}
1.737     albertel 11202: 	# uniqifiy package listing
                   11203: 	my %seen;
                   11204: 	my @uniq_packages =
                   11205: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11206: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11207: 
1.1070    www      11208:         if ($importedparts) {
                   11209: # We had imported parts and need to rebuild partorder
                   11210:            $metaentry{':partorder'}='';
                   11211:            $metathesekeys{'partorder'}=1;
                   11212:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11213:                if ($origfileimportpartids[$index] eq 'part') {
                   11214: # original part, part of the problem
                   11215:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11216:                } else {
                   11217: # we have imported parts at this position
                   11218:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11219:                }
                   11220:            }
                   11221:            $metaentry{':partorder'}=~s/^\,//;
                   11222:         }
                   11223: 
1.737     albertel 11224: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11225: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  11226: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11227: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11228: # this is the end of "was not already recently cached
1.71      www      11229:     }
1.599     albertel 11230:     return $metaentry{':'.$what};
1.261     albertel 11231: }
                   11232: 
1.488     albertel 11233: sub metadata_create_package_def {
1.483     albertel 11234:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11235:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11236:     if ($subp eq 'default') { next; }
                   11237:     
1.599     albertel 11238:     if (defined($metaentry{':packages'})) {
                   11239: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11240:     } else {
1.599     albertel 11241: 	$metaentry{':packages'}=$package;
1.483     albertel 11242:     }
                   11243:     my $value=$packagetab{$key};
                   11244:     my $unikey;
                   11245:     $unikey='parameter_0_'.$name;
1.599     albertel 11246:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11247:     $$metathesekeys{$unikey}=1;
1.599     albertel 11248:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11249: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11250:     }
1.599     albertel 11251:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11252: 	$metaentry{':'.$unikey}=
                   11253: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11254:     }
                   11255: }
                   11256: 
1.261     albertel 11257: sub metadata_generate_part0 {
                   11258:     my ($metadata,$metacache,$uri) = @_;
                   11259:     my %allnames;
1.737     albertel 11260:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11261: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11262: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11263: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11264: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11265: 	    $allnames{$name}=$part;
                   11266: 	  }
                   11267: 	}
                   11268:     }
                   11269:     foreach my $name (keys(%allnames)) {
                   11270:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11271:       my $key=":parameter_0_$name";
1.261     albertel 11272:       $$metacache{"$key.part"}='0';
                   11273:       $$metacache{"$key.name"}=$name;
1.428     albertel 11274:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11275: 					   $allnames{$name}.'_'.$name.
                   11276: 					   '.type'};
1.428     albertel 11277:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11278: 			     '.display'};
1.644     www      11279:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11280:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11281:       $$metacache{"$key.display"}=$olddis;
                   11282:     }
1.71      www      11283: }
                   11284: 
1.764     albertel 11285: # ------------------------------------------------------ Devalidate title cache
                   11286: 
                   11287: sub devalidate_title_cache {
                   11288:     my ($url)=@_;
                   11289:     if (!$env{'request.course.id'}) { return; }
                   11290:     my $symb=&symbread($url);
                   11291:     if (!$symb) { return; }
                   11292:     my $key=$env{'request.course.id'}."\0".$symb;
                   11293:     &devalidate_cache_new('title',$key);
                   11294: }
                   11295: 
1.1014    droeschl 11296: # ------------------------------------------------- Get the title of a course
                   11297: 
                   11298: sub current_course_title {
                   11299:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11300: }
1.301     www      11301: # ------------------------------------------------- Get the title of a resource
                   11302: 
                   11303: sub gettitle {
                   11304:     my $urlsymb=shift;
                   11305:     my $symb=&symbread($urlsymb);
1.534     albertel 11306:     if ($symb) {
1.620     albertel 11307: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11308: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11309: 	if (defined($cached)) { 
                   11310: 	    return $result;
                   11311: 	}
1.534     albertel 11312: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11313: 	my $title='';
1.907     albertel 11314: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11315: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11316: 	} else {
                   11317: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11318: 		    &GDBM_READER(),0640)) {
                   11319: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11320: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11321: 		untie(%bighash);
                   11322: 	    }
1.534     albertel 11323: 	}
                   11324: 	$title=~s/\&colon\;/\:/gs;
                   11325: 	if ($title) {
1.1159    www      11326: # Remember both $symb and $title for dynamic metadata
                   11327:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11328:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11329: # Cache this title and then return it
1.599     albertel 11330: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11331: 	}
                   11332: 	$urlsymb=$url;
                   11333:     }
                   11334:     my $title=&metadata($urlsymb,'title');
                   11335:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11336:     return $title;
1.301     www      11337: }
1.613     albertel 11338: 
1.614     albertel 11339: sub get_slot {
                   11340:     my ($which,$cnum,$cdom)=@_;
                   11341:     if (!$cnum || !$cdom) {
1.790     albertel 11342: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11343: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11344: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11345:     }
1.703     albertel 11346:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11347:     my %slotinfo;
                   11348:     if (exists($remembered{$key})) {
                   11349: 	$slotinfo{$which} = $remembered{$key};
                   11350:     } else {
                   11351: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11352: 	&Apache::lonhomework::showhash(%slotinfo);
                   11353: 	my ($tmp)=keys(%slotinfo);
                   11354: 	if ($tmp=~/^error:/) { return (); }
                   11355: 	$remembered{$key} = $slotinfo{$which};
                   11356:     }
1.616     albertel 11357:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11358: 	return %{$slotinfo{$which}};
                   11359:     }
                   11360:     return $slotinfo{$which};
1.614     albertel 11361: }
1.1150    raeburn  11362: 
                   11363: sub get_reservable_slots {
                   11364:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11365:     my $now = time;
                   11366:     my $reservable_info;
                   11367:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11368:     if (exists($remembered{$key})) {
                   11369:         $reservable_info = $remembered{$key};
                   11370:     } else {
                   11371:         my %resv;
                   11372:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11373:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11374:         $reservable_info = \%resv;
                   11375:         $remembered{$key} = $reservable_info;
                   11376:     }
                   11377:     return $reservable_info;
                   11378: }
                   11379: 
                   11380: sub get_course_slots {
                   11381:     my ($cnum,$cdom) = @_;
                   11382:     my $hashid=$cnum.':'.$cdom;
                   11383:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11384:     if (defined($cached)) {
                   11385:         if (ref($result) eq 'HASH') {
                   11386:             return %{$result};
                   11387:         }
                   11388:     } else {
                   11389:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11390:         my ($tmp) = keys(%slots);
                   11391:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  11392:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11393:             return %slots;
                   11394:         }
                   11395:     }
                   11396:     return;
                   11397: }
                   11398: 
                   11399: sub devalidate_slots_cache {
                   11400:     my ($cnum,$cdom)=@_;
                   11401:     my $hashid=$cnum.':'.$cdom;
                   11402:     &devalidate_cache_new('allslots',$hashid);
                   11403: }
                   11404: 
1.1172.2.8  raeburn  11405: sub get_coursechange {
                   11406:     my ($cdom,$cnum) = @_;
                   11407:     if ($cdom eq '' || $cnum eq '') {
                   11408:         return unless ($env{'request.course.id'});
                   11409:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11410:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11411:     }
                   11412:     my $hashid=$cdom.'_'.$cnum;
                   11413:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11414:     if ((defined($cached)) && ($change ne '')) {
                   11415:         return $change;
                   11416:     } else {
                   11417:         my %crshash;
                   11418:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11419:         if ($crshash{'internal.contentchange'} eq '') {
                   11420:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11421:             if ($change eq '') {
                   11422:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11423:                 $change = $crshash{'internal.created'};
                   11424:             }
                   11425:         } else {
                   11426:             $change = $crshash{'internal.contentchange'};
                   11427:         }
                   11428:         my $cachetime = 600;
                   11429:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11430:     }
                   11431:     return $change;
                   11432: }
                   11433: 
                   11434: sub devalidate_coursechange_cache {
                   11435:     my ($cnum,$cdom)=@_;
                   11436:     my $hashid=$cnum.':'.$cdom;
                   11437:     &devalidate_cache_new('crschange',$hashid);
                   11438: }
                   11439: 
1.31      www      11440: # ------------------------------------------------- Update symbolic store links
                   11441: 
                   11442: sub symblist {
                   11443:     my ($mapname,%newhash)=@_;
1.438     www      11444:     $mapname=&deversion(&declutter($mapname));
1.31      www      11445:     my %hash;
1.620     albertel 11446:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11447:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11448:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11449: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11450: 		next if ($url eq 'last_known'
                   11451: 			 && $env{'form.no_update_last_known'});
                   11452: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11453: 						    $newhash{$url}->[1],
                   11454: 						    $newhash{$url}->[0]);
1.191     harris41 11455:             }
1.31      www      11456:             if (untie(%hash)) {
                   11457: 		return 'ok';
                   11458:             }
                   11459:         }
                   11460:     }
                   11461:     return 'error';
1.212     www      11462: }
                   11463: 
                   11464: # --------------------------------------------------------------- Verify a symb
                   11465: 
                   11466: sub symbverify {
1.1172.2.11  raeburn  11467:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11468:     my $thisfn=$thisurl;
1.439     www      11469:     $thisfn=&declutter($thisfn);
1.215     www      11470: # direct jump to resource in page or to a sequence - will construct own symbs
                   11471:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11472: # check URL part
1.409     www      11473:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11474: 
1.431     www      11475:     unless ($url eq $thisfn) { return 0; }
1.213     www      11476: 
1.216     www      11477:     $symb=&symbclean($symb);
1.510     www      11478:     $thisurl=&deversion($thisurl);
1.439     www      11479:     $thisfn=&deversion($thisfn);
1.213     www      11480: 
                   11481:     my %bighash;
                   11482:     my $okay=0;
1.431     www      11483: 
1.620     albertel 11484:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11485:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  11486:         my $noclutter;
1.1032    raeburn  11487:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11488:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  11489:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11490:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11491:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11492:                 $noclutter = 1;
                   11493:             }
                   11494:         }
                   11495:         my $ids;
                   11496:         if ($noclutter) {
                   11497:             $ids=$bighash{'ids_'.$thisurl};
                   11498:         } else {
                   11499:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11500:         }
1.1102    raeburn  11501:         unless ($ids) {
1.1172.2.13  raeburn  11502:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  11503:             $ids=$bighash{$idkey};
1.216     www      11504:         }
                   11505:         if ($ids) {
                   11506: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  11507:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   11508:                 $symb =~ s/\?.+$//;
                   11509:             }
1.800     albertel 11510: 	    foreach my $id (split(/\,/,$ids)) {
                   11511: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11512:                if (
                   11513:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  11514:    eq $symb) {
1.1172.2.11  raeburn  11515:                    if (ref($encstate)) {
                   11516:                        $$encstate = $bighash{'encrypted_'.$id};
                   11517:                    }
1.1172.2.13  raeburn  11518:                    if (($env{'request.role.adv'}) ||
                   11519:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  11520:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  11521:                        $okay=1;
                   11522:                        last;
                   11523:                    }
                   11524:                }
                   11525:            }
1.216     www      11526:         }
1.213     www      11527: 	untie(%bighash);
                   11528:     }
                   11529:     return $okay;
1.31      www      11530: }
                   11531: 
1.210     www      11532: # --------------------------------------------------------------- Clean-up symb
                   11533: 
                   11534: sub symbclean {
                   11535:     my $symb=shift;
1.568     albertel 11536:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11537: # remove version from map
                   11538:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11539: 
1.210     www      11540: # remove version from URL
                   11541:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11542: 
1.507     www      11543: # remove wrapper
                   11544: 
1.510     www      11545:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11546:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11547:     return $symb;
1.409     www      11548: }
                   11549: 
                   11550: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11551: 
                   11552: sub encode_symb {
                   11553:     my ($map,$resid,$url)=@_;
                   11554:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11555: }
1.409     www      11556: 
                   11557: sub decode_symb {
1.568     albertel 11558:     my $symb=shift;
                   11559:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11560:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11561:     return (&fixversion($map),$resid,&fixversion($url));
                   11562: }
                   11563: 
                   11564: sub fixversion {
                   11565:     my $fn=shift;
1.609     banghart 11566:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11567:     my %bighash;
                   11568:     my $uri=&clutter($fn);
1.620     albertel 11569:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11570: # is this cached?
1.599     albertel 11571:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11572:     if (defined($cached)) { return $result; }
                   11573: # unfortunately not cached, or expired
1.620     albertel 11574:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11575: 	    &GDBM_READER(),0640)) {
                   11576:  	if ($bighash{'version_'.$uri}) {
                   11577:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11578:  	    unless (($version eq 'mostrecent') || 
                   11579: 		    ($version==&getversion($uri))) {
1.440     www      11580:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11581:  	    }
                   11582:  	}
                   11583:  	untie %bighash;
1.413     www      11584:     }
1.599     albertel 11585:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11586: }
                   11587: 
                   11588: sub deversion {
                   11589:     my $url=shift;
                   11590:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11591:     return $url;
1.210     www      11592: }
                   11593: 
1.31      www      11594: # ------------------------------------------------------ Return symb list entry
                   11595: 
                   11596: sub symbread {
1.1172.2.66  raeburn  11597:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  11598:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  11599:     if (defined($env{$cache_str})) {
                   11600:         if ($ignorecachednull) {
                   11601:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11602:         } else {
                   11603:             return $env{$cache_str};
                   11604:         }
                   11605:     }
1.242     www      11606: # no filename provided? try from environment
1.1172.2.54  raeburn  11607:     unless ($thisfn) {
1.620     albertel 11608:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  11609:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   11610:         }
                   11611:         $thisfn=$env{'request.filename'};
1.44      www      11612:     }
1.569     albertel 11613:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11614: # is that filename actually a symb? Verify, clean, and return
                   11615:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11616: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11617: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11618: 	}
1.242     www      11619:     }
1.44      www      11620:     $thisfn=declutter($thisfn);
1.31      www      11621:     my %hash;
1.37      www      11622:     my %bighash;
                   11623:     my $syval='';
1.620     albertel 11624:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11625:         my $targetfn = $thisfn;
1.609     banghart 11626:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11627:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11628:         }
1.687     albertel 11629: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11630: 	    $targetfn=$1;
                   11631: 	}
1.620     albertel 11632:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11633:                       &GDBM_READER(),0640)) {
1.481     raeburn  11634: 	    $syval=$hash{$targetfn};
1.37      www      11635:             untie(%hash);
                   11636:         }
                   11637: # ---------------------------------------------------------- There was an entry
                   11638:         if ($syval) {
1.601     albertel 11639: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11640: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11641: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11642: 		    #return $env{$cache_str}='';
1.601     albertel 11643: 		#}    
                   11644: 		#$syval.=$1;
                   11645: 	    #}
1.37      www      11646:         } else {
                   11647: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11648:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11649:                             &GDBM_READER(),0640)) {
1.37      www      11650: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11651:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11652:               unless ($ids) { 
                   11653:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11654:               }
                   11655:               unless ($ids) {
                   11656: # alias?
                   11657: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11658:               }
1.37      www      11659:               if ($ids) {
                   11660: # ------------------------------------------------------------------- Has ID(s)
                   11661:                  my @possibilities=split(/\,/,$ids);
1.39      www      11662:                  if ($#possibilities==0) {
                   11663: # ----------------------------------------------- There is only one possibility
1.37      www      11664: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11665: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11666: 						    $resid,$thisfn);
1.1172.2.66  raeburn  11667:                      if (ref($possibles) eq 'HASH') {
                   11668:                          $possibles->{$syval} = 1;
                   11669:                      }
                   11670:                      if ($checkforblock) {
                   11671:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11672:                          if (@blockers) {
                   11673:                              $syval = '';
                   11674:                              return;
                   11675:                          }
                   11676:                      }
                   11677:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      11678: # ------------------------------------------ There is more than one possibility
                   11679:                      my $realpossible=0;
1.800     albertel 11680:                      foreach my $id (@possibilities) {
                   11681: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  11682:                          my $canaccess;
                   11683:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11684:                              $canaccess = 1;
                   11685:                          } else {
                   11686:                              $canaccess = &allowed('bre',$file);
                   11687:                          }
                   11688:                          if ($canaccess) {
                   11689:          		     my ($mapid,$resid)=split(/\./,$id);
                   11690:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11691:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11692:                                                              $resid,$thisfn);
                   11693:                                  if (ref($possibles) eq 'HASH') {
                   11694:                                      $possibles->{$syval} = 1;
                   11695:                                  }
                   11696:                                  if ($checkforblock) {
                   11697:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11698:                                      unless (@blockers > 0) {
                   11699:                                          $syval = $poss_syval;
                   11700:                                          $realpossible++;
                   11701:                                      }
                   11702:                                  } else {
                   11703:                                      $syval = $poss_syval;
                   11704:                                      $realpossible++;
                   11705:                                  }
                   11706:                              }
1.39      www      11707: 			 }
1.191     harris41 11708:                      }
1.39      www      11709: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11710:                  } else {
                   11711:                      $syval='';
1.37      www      11712:                  }
                   11713: 	      }
1.1172.2.66  raeburn  11714:               untie(%bighash);
1.481     raeburn  11715:            }
1.31      www      11716:         }
1.62      www      11717:         if ($syval) {
1.620     albertel 11718: 	    return $env{$cache_str}=$syval;
1.62      www      11719:         }
1.31      www      11720:     }
1.949     raeburn  11721:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11722:     return $env{$cache_str}='';
1.31      www      11723: }
                   11724: 
                   11725: # ---------------------------------------------------------- Return random seed
                   11726: 
1.32      www      11727: sub numval {
                   11728:     my $txt=shift;
                   11729:     $txt=~tr/A-J/0-9/;
                   11730:     $txt=~tr/a-j/0-9/;
                   11731:     $txt=~tr/K-T/0-9/;
                   11732:     $txt=~tr/k-t/0-9/;
                   11733:     $txt=~tr/U-Z/0-5/;
                   11734:     $txt=~tr/u-z/0-5/;
                   11735:     $txt=~s/\D//g;
1.564     albertel 11736:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11737:     return int($txt);
1.368     albertel 11738: }
                   11739: 
1.484     albertel 11740: sub numval2 {
                   11741:     my $txt=shift;
                   11742:     $txt=~tr/A-J/0-9/;
                   11743:     $txt=~tr/a-j/0-9/;
                   11744:     $txt=~tr/K-T/0-9/;
                   11745:     $txt=~tr/k-t/0-9/;
                   11746:     $txt=~tr/U-Z/0-5/;
                   11747:     $txt=~tr/u-z/0-5/;
                   11748:     $txt=~s/\D//g;
                   11749:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11750:     my $total;
                   11751:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11752:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11753:     return int($total);
                   11754: }
                   11755: 
1.575     albertel 11756: sub numval3 {
                   11757:     use integer;
                   11758:     my $txt=shift;
                   11759:     $txt=~tr/A-J/0-9/;
                   11760:     $txt=~tr/a-j/0-9/;
                   11761:     $txt=~tr/K-T/0-9/;
                   11762:     $txt=~tr/k-t/0-9/;
                   11763:     $txt=~tr/U-Z/0-5/;
                   11764:     $txt=~tr/u-z/0-5/;
                   11765:     $txt=~s/\D//g;
                   11766:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11767:     my $total;
                   11768:     foreach my $val (@txts) { $total+=$val; }
                   11769:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11770:     return $total;
                   11771: }
                   11772: 
1.675     albertel 11773: sub digest {
                   11774:     my ($data)=@_;
                   11775:     my $digest=&Digest::MD5::md5($data);
                   11776:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11777:     my ($e,$f);
                   11778:     {
                   11779:         use integer;
                   11780:         $e=($a+$b);
                   11781:         $f=($c+$d);
                   11782:         if ($_64bit) {
                   11783:             $e=(($e<<32)>>32);
                   11784:             $f=(($f<<32)>>32);
                   11785:         }
                   11786:     }
                   11787:     if (wantarray) {
                   11788: 	return ($e,$f);
                   11789:     } else {
                   11790: 	my $g;
                   11791: 	{
                   11792: 	    use integer;
                   11793: 	    $g=($e+$f);
                   11794: 	    if ($_64bit) {
                   11795: 		$g=(($g<<32)>>32);
                   11796: 	    }
                   11797: 	}
                   11798: 	return $g;
                   11799:     }
                   11800: }
                   11801: 
1.368     albertel 11802: sub latest_rnd_algorithm_id {
1.675     albertel 11803:     return '64bit5';
1.366     albertel 11804: }
1.32      www      11805: 
1.503     albertel 11806: sub get_rand_alg {
                   11807:     my ($courseid)=@_;
1.790     albertel 11808:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11809:     if ($courseid) {
1.620     albertel 11810: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11811:     }
                   11812:     return &latest_rnd_algorithm_id();
                   11813: }
                   11814: 
1.562     albertel 11815: sub validCODE {
                   11816:     my ($CODE)=@_;
                   11817:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11818:     return 0;
                   11819: }
                   11820: 
1.491     albertel 11821: sub getCODE {
1.620     albertel 11822:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11823:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11824: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11825: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11826: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11827:     }
                   11828:     return undef;
                   11829: }
1.1133    foxr     11830: #
                   11831: #  Determines the random seed for a specific context:
                   11832: #
                   11833: # parameters:
                   11834: #   symb      - in course context the symb for the seed.
                   11835: #   course_id - The course id of the form domain_coursenum.
                   11836: #   domain    - Domain for the user.
                   11837: #   course    - Course for the user.
                   11838: #   cenv      - environment of the course.
                   11839: #
                   11840: # NOTE:
                   11841: #   All parameters are picked out of the environment if missing
                   11842: #   or not defined.
                   11843: #   If a symb cannot be determined the current time is used instead.
                   11844: #
                   11845: #  For a given well defined symb, courside, domain, username,
                   11846: #  and course environment, the seed is reproducible.
                   11847: #
1.31      www      11848: sub rndseed {
1.1133    foxr     11849:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11850:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11851:     if (!defined($symb)) {
1.366     albertel 11852: 	unless ($symb=$wsymb) { return time; }
                   11853:     }
1.1146    foxr     11854:     if (!defined $courseid) { 
                   11855: 	$courseid=$wcourseid; 
                   11856:     }
                   11857:     if (!defined $domain) { $domain=$wdomain; }
                   11858:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11859: 
                   11860:     my $which;
                   11861:     if (defined($cenv->{'rndseed'})) {
                   11862: 	$which = $cenv->{'rndseed'};
                   11863:     } else {
                   11864: 	$which =&get_rand_alg($courseid);
                   11865:     }
1.491     albertel 11866:     if (defined(&getCODE())) {
1.675     albertel 11867: 	if ($which eq '64bit5') {
                   11868: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11869: 	} elsif ($which eq '64bit4') {
1.575     albertel 11870: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11871: 	} else {
                   11872: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11873: 	}
1.675     albertel 11874:     } elsif ($which eq '64bit5') {
                   11875: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11876:     } elsif ($which eq '64bit4') {
                   11877: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11878:     } elsif ($which eq '64bit3') {
                   11879: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11880:     } elsif ($which eq '64bit2') {
                   11881: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11882:     } elsif ($which eq '64bit') {
                   11883: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11884:     }
                   11885:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11886: }
                   11887: 
                   11888: sub rndseed_32bit {
                   11889:     my ($symb,$courseid,$domain,$username)=@_;
                   11890:     {
                   11891: 	use integer;
                   11892: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11893: 	my $symbseed=numval($symb) << 22;
                   11894: 	my $namechck=unpack("%32C*",$username) << 17;
                   11895: 	my $nameseed=numval($username) << 12;
                   11896: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11897: 	my $courseseed=unpack("%32C*",$courseid);
                   11898: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11899: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11900: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11901: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11902: 	return $num;
                   11903:     }
                   11904: }
                   11905: 
                   11906: sub rndseed_64bit {
                   11907:     my ($symb,$courseid,$domain,$username)=@_;
                   11908:     {
                   11909: 	use integer;
                   11910: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11911: 	my $symbseed=numval($symb) << 10;
                   11912: 	my $namechck=unpack("%32S*",$username);
                   11913: 	
                   11914: 	my $nameseed=numval($username) << 21;
                   11915: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11916: 	my $courseseed=unpack("%32S*",$courseid);
                   11917: 	
                   11918: 	my $num1=$symbchck+$symbseed+$namechck;
                   11919: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11920: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11921: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11922: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11923: 	return "$num1,$num2";
1.155     albertel 11924:     }
1.366     albertel 11925: }
                   11926: 
1.443     albertel 11927: sub rndseed_64bit2 {
                   11928:     my ($symb,$courseid,$domain,$username)=@_;
                   11929:     {
                   11930: 	use integer;
                   11931: 	# strings need to be an even # of cahracters long, it it is odd the
                   11932:         # last characters gets thrown away
                   11933: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11934: 	my $symbseed=numval($symb) << 10;
                   11935: 	my $namechck=unpack("%32S*",$username.' ');
                   11936: 	
                   11937: 	my $nameseed=numval($username) << 21;
1.501     albertel 11938: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11939: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11940: 	
                   11941: 	my $num1=$symbchck+$symbseed+$namechck;
                   11942: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11943: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11944: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11945: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11946: 	return "$num1,$num2";
                   11947:     }
                   11948: }
                   11949: 
                   11950: sub rndseed_64bit3 {
                   11951:     my ($symb,$courseid,$domain,$username)=@_;
                   11952:     {
                   11953: 	use integer;
                   11954: 	# strings need to be an even # of cahracters long, it it is odd the
                   11955:         # last characters gets thrown away
                   11956: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11957: 	my $symbseed=numval2($symb) << 10;
                   11958: 	my $namechck=unpack("%32S*",$username.' ');
                   11959: 	
                   11960: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11961: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11962: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11963: 	
                   11964: 	my $num1=$symbchck+$symbseed+$namechck;
                   11965: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11966: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11967: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11968: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11969: 	
1.503     albertel 11970: 	return "$num1:$num2";
1.443     albertel 11971:     }
                   11972: }
                   11973: 
1.575     albertel 11974: sub rndseed_64bit4 {
                   11975:     my ($symb,$courseid,$domain,$username)=@_;
                   11976:     {
                   11977: 	use integer;
                   11978: 	# strings need to be an even # of cahracters long, it it is odd the
                   11979:         # last characters gets thrown away
                   11980: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11981: 	my $symbseed=numval3($symb) << 10;
                   11982: 	my $namechck=unpack("%32S*",$username.' ');
                   11983: 	
                   11984: 	my $nameseed=numval3($username) << 21;
                   11985: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11986: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11987: 	
                   11988: 	my $num1=$symbchck+$symbseed+$namechck;
                   11989: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11990: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11991: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11992: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11993: 	
1.575     albertel 11994: 	return "$num1:$num2";
                   11995:     }
                   11996: }
                   11997: 
1.675     albertel 11998: sub rndseed_64bit5 {
                   11999:     my ($symb,$courseid,$domain,$username)=@_;
                   12000:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12001:     return "$num1:$num2";
                   12002: }
                   12003: 
1.366     albertel 12004: sub rndseed_CODE_64bit {
                   12005:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12006:     {
1.366     albertel 12007: 	use integer;
1.443     albertel 12008: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12009: 	my $symbseed=numval2($symb);
1.491     albertel 12010: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12011: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12012: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12013: 	my $num1=$symbseed+$CODEchck;
                   12014: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12015: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12016: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12017: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12018: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12019: 	return "$num1:$num2";
1.366     albertel 12020:     }
                   12021: }
                   12022: 
1.575     albertel 12023: sub rndseed_CODE_64bit4 {
                   12024:     my ($symb,$courseid,$domain,$username)=@_;
                   12025:     {
                   12026: 	use integer;
                   12027: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12028: 	my $symbseed=numval3($symb);
                   12029: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12030: 	my $CODEseed=numval3(&getCODE());
                   12031: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12032: 	my $num1=$symbseed+$CODEchck;
                   12033: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12034: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12035: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12036: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12037: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12038: 	return "$num1:$num2";
                   12039:     }
                   12040: }
                   12041: 
1.675     albertel 12042: sub rndseed_CODE_64bit5 {
                   12043:     my ($symb,$courseid,$domain,$username)=@_;
                   12044:     my $code = &getCODE();
                   12045:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12046:     return "$num1:$num2";
                   12047: }
                   12048: 
1.366     albertel 12049: sub setup_random_from_rndseed {
                   12050:     my ($rndseed)=@_;
1.503     albertel 12051:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12052: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12053:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12054:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12055:         } else {
                   12056:             &Math::Random::random_set_seed($num1,$num2);
                   12057:         }
1.366     albertel 12058:     } else {
                   12059: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12060:     }
1.36      albertel 12061: }
                   12062: 
1.474     albertel 12063: sub latest_receipt_algorithm_id {
1.835     albertel 12064:     return 'receipt3';
1.474     albertel 12065: }
                   12066: 
1.480     www      12067: sub recunique {
                   12068:     my $fucourseid=shift;
                   12069:     my $unique;
1.835     albertel 12070:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12071: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12072: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12073:     } else {
                   12074: 	$unique=$perlvar{'lonReceipt'};
                   12075:     }
                   12076:     return unpack("%32C*",$unique);
                   12077: }
                   12078: 
                   12079: sub recprefix {
                   12080:     my $fucourseid=shift;
                   12081:     my $prefix;
1.835     albertel 12082:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12083: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12084: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12085:     } else {
                   12086: 	$prefix=$perlvar{'lonHostID'};
                   12087:     }
                   12088:     return unpack("%32C*",$prefix);
                   12089: }
                   12090: 
1.76      www      12091: sub ireceipt {
1.474     albertel 12092:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12093: 
                   12094:     my $return =&recprefix($fucourseid).'-';
                   12095: 
                   12096:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12097: 	$env{'request.state'} eq 'construct') {
                   12098: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12099: 	return $return;
                   12100:     }
                   12101: 
1.76      www      12102:     my $cuname=unpack("%32C*",$funame);
                   12103:     my $cudom=unpack("%32C*",$fudom);
                   12104:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12105:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12106:     my $cunique=&recunique($fucourseid);
1.474     albertel 12107:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12108:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12109: 
1.790     albertel 12110: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12111: 			       
                   12112: 	$return.= ($cunique%$cuname+
                   12113: 		   $cunique%$cudom+
                   12114: 		   $cusymb%$cuname+
                   12115: 		   $cusymb%$cudom+
                   12116: 		   $cucourseid%$cuname+
                   12117: 		   $cucourseid%$cudom+
                   12118: 		   $cpart%$cuname+
                   12119: 		   $cpart%$cudom);
                   12120:     } else {
                   12121: 	$return.= ($cunique%$cuname+
                   12122: 		   $cunique%$cudom+
                   12123: 		   $cusymb%$cuname+
                   12124: 		   $cusymb%$cudom+
                   12125: 		   $cucourseid%$cuname+
                   12126: 		   $cucourseid%$cudom);
                   12127:     }
                   12128:     return $return;
1.76      www      12129: }
                   12130: 
                   12131: sub receipt {
1.474     albertel 12132:     my ($part)=@_;
1.790     albertel 12133:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12134:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12135: }
1.260     ng       12136: 
1.790     albertel 12137: sub whichuser {
                   12138:     my ($passedsymb)=@_;
                   12139:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12140:     if (defined($env{'form.grade_symb'})) {
                   12141: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12142: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12143: 	if (!$allowed &&
                   12144: 	    exists($env{'request.course.sec'}) &&
                   12145: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12146: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12147: 			      '/'.$env{'request.course.sec'});
                   12148: 	}
                   12149: 	if ($allowed) {
                   12150: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12151: 	    $courseid=$tmp_courseid;
                   12152: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12153: 	    ($name)=&get_env_multiple('form.grade_username');
                   12154: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12155: 	}
                   12156:     }
                   12157:     if (!$passedsymb) {
                   12158: 	$symb=&symbread();
                   12159:     } else {
                   12160: 	$symb=$passedsymb;
                   12161:     }
                   12162:     $courseid=$env{'request.course.id'};
                   12163:     $domain=$env{'user.domain'};
                   12164:     $name=$env{'user.name'};
                   12165:     if ($name eq 'public' && $domain eq 'public') {
                   12166: 	if (!defined($env{'form.username'})) {
                   12167: 	    $env{'form.username'}.=time.rand(10000000);
                   12168: 	}
                   12169: 	$name.=$env{'form.username'};
                   12170:     }
                   12171:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12172: 
                   12173: }
                   12174: 
1.36      albertel 12175: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12176: # returns either the contents of the file or 
                   12177: # -1 if the file doesn't exist
1.481     raeburn  12178: #
                   12179: # if the target is a file that was uploaded via DOCS, 
                   12180: # a check will be made to see if a current copy exists on the local server,
                   12181: # if it does this will be served, otherwise a copy will be retrieved from
                   12182: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12183: # the local server.   
1.472     albertel 12184: 
1.36      albertel 12185: sub getfile {
1.538     albertel 12186:     my ($file) = @_;
1.609     banghart 12187:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12188:     &repcopy($file);
                   12189:     return &readfile($file);
                   12190: }
                   12191: 
                   12192: sub repcopy_userfile {
                   12193:     my ($file)=@_;
1.1142    raeburn  12194:     my $londocroot = $perlvar{'lonDocRoot'};
                   12195:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12196:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12197:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12198: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12199:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12200:     if (-e "$file") {
1.828     www      12201: # we already have a local copy, check it out
1.538     albertel 12202: 	my @fileinfo = stat($file);
1.828     www      12203: 	my $rtncode;
                   12204: 	my $info;
1.538     albertel 12205: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12206: 	if ($lwpresp ne 'ok') {
1.828     www      12207: # there is no such file anymore, even though we had a local copy
1.482     albertel 12208: 	    if ($rtncode eq '404') {
1.538     albertel 12209: 		unlink($file);
1.482     albertel 12210: 	    }
                   12211: 	    return -1;
                   12212: 	}
                   12213: 	if ($info < $fileinfo[9]) {
1.828     www      12214: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12215: 	    return 'ok';
1.828     www      12216: 	} else {
                   12217: # the file is outdated, get rid of it
                   12218: 	    unlink($file);
1.482     albertel 12219: 	}
1.828     www      12220:     }
                   12221: # one way or the other, at this point, we don't have the file
                   12222: # construct the correct path for the file
                   12223:     my @parts = ($cdom,$cnum); 
                   12224:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12225: 	push @parts, split(/\//,$1);
                   12226:     }
                   12227:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12228:     foreach my $part (@parts) {
                   12229: 	$path .= '/'.$part;
                   12230: 	if (!-e $path) {
                   12231: 	    mkdir($path,0770);
1.482     albertel 12232: 	}
                   12233:     }
1.828     www      12234: # now the path exists for sure
                   12235: # get a user agent
                   12236:     my $ua=new LWP::UserAgent;
                   12237:     my $transferfile=$file.'.in.transfer';
                   12238: # FIXME: this should flock
                   12239:     if (-e $transferfile) { return 'ok'; }
                   12240:     my $request;
                   12241:     $uri=~s/^\///;
1.980     raeburn  12242:     my $homeserver = &homeserver($cnum,$cdom);
                   12243:     my $protocol = $protocol{$homeserver};
                   12244:     $protocol = 'http' if ($protocol ne 'https');
                   12245:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12246:     my $response=$ua->request($request,$transferfile);
                   12247: # did it work?
                   12248:     if ($response->is_error()) {
                   12249: 	unlink($transferfile);
                   12250: 	&logthis("Userfile repcopy failed for $uri");
                   12251: 	return -1;
                   12252:     }
                   12253: # worked, rename the transfer file
                   12254:     rename($transferfile,$file);
1.607     raeburn  12255:     return 'ok';
1.481     raeburn  12256: }
                   12257: 
1.517     albertel 12258: sub tokenwrapper {
                   12259:     my $uri=shift;
1.980     raeburn  12260:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12261:     $uri=~s|^/||;
1.620     albertel 12262:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12263:     my $token=$1;
1.552     albertel 12264:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12265:     if ($udom && $uname && $file) {
                   12266: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12267:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12268:         my $homeserver = &homeserver($uname,$udom);
                   12269:         my $protocol = $protocol{$homeserver};
                   12270:         $protocol = 'http' if ($protocol ne 'https');
                   12271:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12272:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12273:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12274:     } else {
                   12275:         return '/adm/notfound.html';
                   12276:     }
                   12277: }
                   12278: 
1.828     www      12279: # call with reqtype HEAD: get last modification time
                   12280: # call with reqtype GET: get the file contents
                   12281: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12282: #
1.481     raeburn  12283: sub getuploaded {
                   12284:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12285:     $uri=~s/^\///;
1.980     raeburn  12286:     my $homeserver = &homeserver($cnum,$cdom);
                   12287:     my $protocol = $protocol{$homeserver};
                   12288:     $protocol = 'http' if ($protocol ne 'https');
                   12289:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12290:     my $ua=new LWP::UserAgent;
                   12291:     my $request=new HTTP::Request($reqtype,$uri);
                   12292:     my $response=$ua->request($request);
                   12293:     $$rtncode = $response->code;
1.482     albertel 12294:     if (! $response->is_success()) {
                   12295: 	return 'failed';
                   12296:     }      
                   12297:     if ($reqtype eq 'HEAD') {
1.486     www      12298: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12299:     } elsif ($reqtype eq 'GET') {
                   12300: 	$$info = $response->content;
1.472     albertel 12301:     }
1.482     albertel 12302:     return 'ok';
1.36      albertel 12303: }
                   12304: 
1.481     raeburn  12305: sub readfile {
                   12306:     my $file = shift;
                   12307:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12308:     my $fh;
                   12309:     open($fh,"<$file");
                   12310:     my $a='';
1.800     albertel 12311:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12312:     return $a;
                   12313: }
                   12314: 
1.36      albertel 12315: sub filelocation {
1.590     banghart 12316:     my ($dir,$file) = @_;
                   12317:     my $location;
                   12318:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12319: 
                   12320:     if ($file =~ m-^/adm/-) {
                   12321: 	$file=~s-^/adm/wrapper/-/-;
                   12322: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12323:     }
1.882     albertel 12324: 
1.1139    www      12325:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12326:         $location = $file;
1.609     banghart 12327:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12328:         my ($udom,$uname,$filename)=
1.811     albertel 12329:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12330:         my $home=&homeserver($uname,$udom);
                   12331:         my $is_me=0;
                   12332:         my @ids=&current_machine_ids();
                   12333:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12334:         if ($is_me) {
1.1117    foxr     12335:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12336:         } else {
                   12337:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12338:   	      $udom.'/'.$uname.'/'.$filename;
                   12339:         }
1.882     albertel 12340:     } elsif ($file =~ m-^/adm/-) {
                   12341: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12342:     } else {
                   12343:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12344:         $file=~s:^/(res|priv)/:/:;
                   12345:         my $space=$1;
1.590     banghart 12346:         if ( !( $file =~ m:^/:) ) {
                   12347:             $location = $dir. '/'.$file;
                   12348:         } else {
1.1142    raeburn  12349:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12350:         }
1.59      albertel 12351:     }
1.590     banghart 12352:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12353:     while ($location=~m{/\.\./}) {
                   12354: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12355: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12356: 	} else {
                   12357: 	    $location=~ s{/\.\./}{/}g;
                   12358: 	}
                   12359:     } #remove dir/..
1.590     banghart 12360:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12361:     return $location;
1.46      www      12362: }
1.36      albertel 12363: 
1.46      www      12364: sub hreflocation {
                   12365:     my ($dir,$file)=@_;
1.980     raeburn  12366:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12367: 	$file=filelocation($dir,$file);
1.700     albertel 12368:     } elsif ($file=~m-^/adm/-) {
                   12369: 	$file=~s-^/adm/wrapper/-/-;
                   12370: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12371:     }
                   12372:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12373: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12374:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12375: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12376: 	        {/uploaded/$1/$2/}x;
1.46      www      12377:     }
1.913     albertel 12378:     if ($file=~ m{^/userfiles/}) {
                   12379: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12380:     }
1.462     albertel 12381:     return $file;
1.465     albertel 12382: }
                   12383: 
1.1139    www      12384: 
                   12385: 
                   12386: 
                   12387: 
1.465     albertel 12388: sub current_machine_domains {
1.853     albertel 12389:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12390: }
                   12391: 
                   12392: sub machine_domains {
                   12393:     my ($hostname) = @_;
1.465     albertel 12394:     my @domains;
1.838     albertel 12395:     my %hostname = &all_hostnames();
1.465     albertel 12396:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12397: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12398: 	if ($hostname eq $name) {
1.844     albertel 12399: 	    push(@domains,&host_domain($id));
1.465     albertel 12400: 	}
                   12401:     }
                   12402:     return @domains;
                   12403: }
                   12404: 
                   12405: sub current_machine_ids {
1.853     albertel 12406:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12407: }
                   12408: 
                   12409: sub machine_ids {
                   12410:     my ($hostname) = @_;
                   12411:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12412:     my @ids;
1.888     albertel 12413:     my %name_to_host = &all_names();
1.889     albertel 12414:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12415: 	return @{ $name_to_host{$hostname} };
                   12416:     }
                   12417:     return;
1.31      www      12418: }
                   12419: 
1.824     raeburn  12420: sub additional_machine_domains {
                   12421:     my @domains;
                   12422:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12423:     while( my $line = <$fh>) {
                   12424:         $line =~ s/\s//g;
                   12425:         push(@domains,$line);
                   12426:     }
                   12427:     return @domains;
                   12428: }
                   12429: 
                   12430: sub default_login_domain {
                   12431:     my $domain = $perlvar{'lonDefDomain'};
                   12432:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12433:     foreach my $posdom (&current_machine_domains(),
                   12434:                         &additional_machine_domains()) {
                   12435:         if (lc($posdom) eq lc($testdomain)) {
                   12436:             $domain=$posdom;
                   12437:             last;
                   12438:         }
                   12439:     }
                   12440:     return $domain;
                   12441: }
                   12442: 
1.31      www      12443: # ------------------------------------------------------------- Declutters URLs
                   12444: 
                   12445: sub declutter {
                   12446:     my $thisfn=shift;
1.569     albertel 12447:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  12448:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12449:         $thisfn=~s{^/home/httpd/html}{};
                   12450:     }
1.31      www      12451:     $thisfn=~s/^\///;
1.697     albertel 12452:     $thisfn=~s|^adm/wrapper/||;
                   12453:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12454:     $thisfn=~s/^res\///;
1.1172    bisitz   12455:     $thisfn=~s/^priv\///;
1.1032    raeburn  12456:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12457:         $thisfn=~s/\?.+$//;
                   12458:     }
1.268     www      12459:     return $thisfn;
                   12460: }
                   12461: 
                   12462: # ------------------------------------------------------------- Clutter up URLs
                   12463: 
                   12464: sub clutter {
                   12465:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12466:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12467: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12468:        $thisfn='/res'.$thisfn; 
                   12469:     }
1.1031    raeburn  12470:     if ($thisfn !~m|^/adm|) {
                   12471: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12472: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12473: 	} else {
                   12474: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12475: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12476: 	    if ($embstyle eq 'ssi'
                   12477: 		|| ($embstyle eq 'hdn')
                   12478: 		|| ($embstyle eq 'rat')
                   12479: 		|| ($embstyle eq 'prv')
                   12480: 		|| ($embstyle eq 'ign')) {
                   12481: 		#do nothing with these
                   12482: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12483: 		|| ($embstyle eq 'emb')
                   12484: 		|| ($embstyle eq 'wrp')) {
                   12485: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12486: 	    } elsif ($embstyle eq 'unk'
                   12487: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12488: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12489: 	    } else {
1.718     www      12490: #		&logthis("Got a blank emb style");
1.695     albertel 12491: 	    }
1.694     albertel 12492: 	}
                   12493:     }
1.31      www      12494:     return $thisfn;
1.12      www      12495: }
                   12496: 
1.787     albertel 12497: sub clutter_with_no_wrapper {
                   12498:     my $uri = &clutter(shift);
                   12499:     if ($uri =~ m-^/adm/-) {
                   12500: 	$uri =~ s-^/adm/wrapper/-/-;
                   12501: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12502:     }
                   12503:     return $uri;
                   12504: }
                   12505: 
1.557     albertel 12506: sub freeze_escape {
                   12507:     my ($value)=@_;
                   12508:     if (ref($value)) {
                   12509: 	$value=&nfreeze($value);
                   12510: 	return '__FROZEN__'.&escape($value);
                   12511:     }
                   12512:     return &escape($value);
                   12513: }
                   12514: 
1.11      www      12515: 
1.557     albertel 12516: sub thaw_unescape {
                   12517:     my ($value)=@_;
                   12518:     if ($value =~ /^__FROZEN__/) {
                   12519: 	substr($value,0,10,undef);
                   12520: 	$value=&unescape($value);
                   12521: 	return &thaw($value);
                   12522:     }
                   12523:     return &unescape($value);
                   12524: }
                   12525: 
1.436     albertel 12526: sub correct_line_ends {
                   12527:     my ($result)=@_;
                   12528:     $$result =~s/\r\n/\n/mg;
                   12529:     $$result =~s/\r/\n/mg;
1.415     albertel 12530: }
1.1       albertel 12531: # ================================================================ Main Program
                   12532: 
1.184     www      12533: sub goodbye {
1.204     albertel 12534:    &logthis("Starting Shut down");
1.443     albertel 12535: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12536:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12537: #converted
1.599     albertel 12538: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12539:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12540: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12541: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12542: #1.1 only
1.870     albertel 12543: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12544: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12545: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12546: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12547:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12548:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12549:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12550:    &flushcourselogs();
                   12551:    &logthis("Shutting down");
                   12552: }
                   12553: 
1.852     albertel 12554: sub get_dns {
1.1172.2.17  raeburn  12555:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12556:     if (!$ignore_cache) {
                   12557: 	my ($content,$cached)=
                   12558: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12559: 	if ($cached) {
1.1172.2.17  raeburn  12560: 	    &$func($content,$hashref);
1.869     albertel 12561: 	    return;
                   12562: 	}
                   12563:     }
                   12564: 
                   12565:     my %alldns;
1.852     albertel 12566:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12567:     foreach my $dns (<$config>) {
                   12568: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12569:         my $line = $1;
                   12570:         my ($host,$protocol) = split(/:/,$line);
                   12571:         if ($protocol ne 'https') {
                   12572:             $protocol = 'http';
                   12573:         }
                   12574: 	$alldns{$host} = $protocol;
1.869     albertel 12575:     }
                   12576:     while (%alldns) {
1.1172.2.52  raeburn  12577: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12578: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12579:         $ua->timeout(30);
1.979     raeburn  12580: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12581: 	my $response=$ua->request($request);
1.979     raeburn  12582:         delete($alldns{$dns});
1.852     albertel 12583: 	next if ($response->is_error());
                   12584: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  12585:         unless ($nocache) {
1.1172.2.23  raeburn  12586: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  12587:         }
                   12588: 	&$func(\@content,$hashref);
1.869     albertel 12589: 	return;
1.852     albertel 12590:     }
                   12591:     close($config);
1.871     albertel 12592:     my $which = (split('/',$url))[3];
                   12593:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12594:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12595:     my @content = <$config>;
1.1172.2.17  raeburn  12596:     &$func(\@content,$hashref);
                   12597:     return;
                   12598: }
                   12599: 
                   12600: # ------------------------------------------------------Get DNS checksums file
                   12601: sub parse_dns_checksums_tab {
                   12602:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  12603:     my $lonhost = $perlvar{'lonHostID'};
                   12604:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  12605:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  12606:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12607:     my $webconfdir = '/etc/httpd/conf';
                   12608:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12609:         $webconfdir = '/etc/apache2';
                   12610:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12611:         if ($1 >= 10) {
                   12612:             $webconfdir = '/etc/apache2';
                   12613:         }
                   12614:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12615:         if ($1 >= 10.0) {
                   12616:             $webconfdir = '/etc/apache2';
                   12617:         }
                   12618:     }
1.1172.2.17  raeburn  12619:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12620:     my (%chksum,%revnum);
                   12621:     if (ref($lines) eq 'ARRAY') {
                   12622:         chomp(@{$lines});
1.1172.2.34  raeburn  12623:         my $version = shift(@{$lines});
                   12624:         if ($version eq $release) {
1.1172.2.17  raeburn  12625:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  12626:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  12627:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12628:                     if ($webconfdir eq '/etc/apache2') {
                   12629:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12630:                     }
                   12631:                 }
1.1172.2.34  raeburn  12632:                 $chksum{$file} = $shasum;
                   12633:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  12634:             }
                   12635:             if (ref($hashref) eq 'HASH') {
                   12636:                 %{$hashref} = (
                   12637:                                 sums     => \%chksum,
                   12638:                                 versions => \%revnum,
                   12639:                               );
                   12640:             }
                   12641:         }
                   12642:     }
1.869     albertel 12643:     return;
1.852     albertel 12644: }
1.1172.2.17  raeburn  12645: 
                   12646: sub fetch_dns_checksums {
                   12647:     my %checksums;
1.1172.2.34  raeburn  12648:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  12649:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  12650:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12651:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  12652:              \%checksums);
                   12653:     return \%checksums;
                   12654: }
                   12655: 
1.327     albertel 12656: # ------------------------------------------------------------ Read domain file
                   12657: {
1.852     albertel 12658:     my $loaded;
1.846     albertel 12659:     my %domain;
                   12660: 
1.852     albertel 12661:     sub parse_domain_tab {
                   12662: 	my ($lines) = @_;
                   12663: 	foreach my $line (@$lines) {
                   12664: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12665: 
1.846     albertel 12666: 	    chomp($line);
1.852     albertel 12667: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12668: 	    my %this_domain;
                   12669: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12670: 			       'lang_def', 'city', 'longi', 'lati',
                   12671: 			       'primary') {
                   12672: 		$this_domain{$field} = shift(@elements);
                   12673: 	    }
                   12674: 	    $domain{$name} = \%this_domain;
1.852     albertel 12675: 	}
                   12676:     }
1.864     albertel 12677: 
                   12678:     sub reset_domain_info {
                   12679: 	undef($loaded);
                   12680: 	undef(%domain);
                   12681:     }
                   12682: 
1.852     albertel 12683:     sub load_domain_tab {
1.1172.2.70  raeburn  12684: 	my ($ignore_cache,$nocache) = @_;
                   12685: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 12686: 	my $fh;
                   12687: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12688: 	    my @lines = <$fh>;
                   12689: 	    &parse_domain_tab(\@lines);
1.448     albertel 12690: 	}
1.852     albertel 12691: 	close($fh);
                   12692: 	$loaded = 1;
1.327     albertel 12693:     }
1.846     albertel 12694: 
                   12695:     sub domain {
1.852     albertel 12696: 	&load_domain_tab() if (!$loaded);
                   12697: 
1.846     albertel 12698: 	my ($name,$what) = @_;
                   12699: 	return if ( !exists($domain{$name}) );
                   12700: 
                   12701: 	if (!$what) {
                   12702: 	    return $domain{$name}{'description'};
                   12703: 	}
                   12704: 	return $domain{$name}{$what};
                   12705:     }
1.974     raeburn  12706: 
                   12707:     sub domain_info {
                   12708:         &load_domain_tab() if (!$loaded);
                   12709:         return %domain;
                   12710:     }
                   12711: 
1.327     albertel 12712: }
                   12713: 
                   12714: 
1.1       albertel 12715: # ------------------------------------------------------------- Read hosts file
                   12716: {
1.838     albertel 12717:     my %hostname;
1.844     albertel 12718:     my %hostdom;
1.845     albertel 12719:     my %libserv;
1.852     albertel 12720:     my $loaded;
1.888     albertel 12721:     my %name_to_host;
1.1074    raeburn  12722:     my %internetdom;
1.1107    raeburn  12723:     my %LC_dns_serv;
1.852     albertel 12724: 
                   12725:     sub parse_hosts_tab {
                   12726: 	my ($file) = @_;
                   12727: 	foreach my $configline (@$file) {
                   12728: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12729:             chomp($configline);
                   12730: 	    if ($configline =~ /^\^/) {
                   12731:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12732:                     $LC_dns_serv{$1} = 1;
                   12733:                 }
                   12734:                 next;
                   12735:             }
1.1074    raeburn  12736: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12737: 	    $name=~s/\s//g;
                   12738: 	    if ($id && $domain && $role && $name) {
                   12739: 		$hostname{$id}=$name;
1.888     albertel 12740: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12741: 		$hostdom{$id}=$domain;
                   12742: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12743:                 if (defined($protocol)) {
                   12744:                     if ($protocol eq 'https') {
                   12745:                         $protocol{$id} = $protocol;
                   12746:                     } else {
                   12747:                         $protocol{$id} = 'http'; 
                   12748:                     }
1.968     raeburn  12749:                 } else {
1.969     raeburn  12750:                     $protocol{$id} = 'http';
1.968     raeburn  12751:                 }
1.1074    raeburn  12752:                 if (defined($intdom)) {
                   12753:                     $internetdom{$id} = $intdom;
                   12754:                 }
1.852     albertel 12755: 	    }
                   12756: 	}
                   12757:     }
1.864     albertel 12758:     
                   12759:     sub reset_hosts_info {
1.897     albertel 12760: 	&purge_remembered();
1.864     albertel 12761: 	&reset_domain_info();
                   12762: 	&reset_hosts_ip_info();
1.892     albertel 12763: 	undef(%name_to_host);
1.864     albertel 12764: 	undef(%hostname);
                   12765: 	undef(%hostdom);
                   12766: 	undef(%libserv);
                   12767: 	undef($loaded);
                   12768:     }
1.1       albertel 12769: 
1.852     albertel 12770:     sub load_hosts_tab {
1.1172.2.70  raeburn  12771: 	my ($ignore_cache,$nocache) = @_;
                   12772: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 12773: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12774: 	my @config = <$config>;
                   12775: 	&parse_hosts_tab(\@config);
                   12776: 	close($config);
                   12777: 	$loaded=1;
1.1       albertel 12778:     }
1.852     albertel 12779: 
1.838     albertel 12780:     sub hostname {
1.852     albertel 12781: 	&load_hosts_tab() if (!$loaded);
                   12782: 
1.838     albertel 12783: 	my ($lonid) = @_;
                   12784: 	return $hostname{$lonid};
                   12785:     }
1.845     albertel 12786: 
1.838     albertel 12787:     sub all_hostnames {
1.852     albertel 12788: 	&load_hosts_tab() if (!$loaded);
                   12789: 
1.838     albertel 12790: 	return %hostname;
                   12791:     }
1.845     albertel 12792: 
1.888     albertel 12793:     sub all_names {
1.1172.2.70  raeburn  12794:         my ($ignore_cache,$nocache) = @_;
                   12795: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 12796: 
                   12797: 	return %name_to_host;
                   12798:     }
                   12799: 
1.974     raeburn  12800:     sub all_host_domain {
                   12801:         &load_hosts_tab() if (!$loaded);
                   12802:         return %hostdom;
                   12803:     }
                   12804: 
1.845     albertel 12805:     sub is_library {
1.852     albertel 12806: 	&load_hosts_tab() if (!$loaded);
                   12807: 
1.845     albertel 12808: 	return exists($libserv{$_[0]});
                   12809:     }
                   12810: 
                   12811:     sub all_library {
1.852     albertel 12812: 	&load_hosts_tab() if (!$loaded);
                   12813: 
1.845     albertel 12814: 	return %libserv;
                   12815:     }
                   12816: 
1.1062    droeschl 12817:     sub unique_library {
                   12818: 	#2x reverse removes all hostnames that appear more than once
                   12819:         my %unique = reverse &all_library();
                   12820:         return reverse %unique;
                   12821:     }
                   12822: 
1.841     albertel 12823:     sub get_servers {
1.852     albertel 12824: 	&load_hosts_tab() if (!$loaded);
                   12825: 
1.841     albertel 12826: 	my ($domain,$type) = @_;
                   12827: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12828: 	                                          : %hostname;
                   12829: 	my %result;
1.842     albertel 12830: 	if (ref($domain) eq 'ARRAY') {
                   12831: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12832: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12833: 		    $result{$host} = $hostname;
                   12834: 		}
                   12835: 	    }
                   12836: 	} else {
                   12837: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12838: 		if ($hostdom{$host} eq $domain) {
                   12839: 		    $result{$host} = $hostname;
                   12840: 		}
1.841     albertel 12841: 	    }
                   12842: 	}
                   12843: 	return %result;
                   12844:     }
1.845     albertel 12845: 
1.1062    droeschl 12846:     sub get_unique_servers {
                   12847:         my %unique = reverse &get_servers(@_);
                   12848: 	return reverse %unique;
                   12849:     }
                   12850: 
1.844     albertel 12851:     sub host_domain {
1.852     albertel 12852: 	&load_hosts_tab() if (!$loaded);
                   12853: 
1.844     albertel 12854: 	my ($lonid) = @_;
                   12855: 	return $hostdom{$lonid};
                   12856:     }
                   12857: 
1.841     albertel 12858:     sub all_domains {
1.852     albertel 12859: 	&load_hosts_tab() if (!$loaded);
                   12860: 
1.841     albertel 12861: 	my %seen;
                   12862: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12863: 	return @uniq;
                   12864:     }
1.1074    raeburn  12865: 
                   12866:     sub internet_dom {
                   12867:         &load_hosts_tab() if (!$loaded);
                   12868: 
                   12869:         my ($lonid) = @_;
                   12870:         return $internetdom{$lonid};
                   12871:     }
1.1107    raeburn  12872: 
                   12873:     sub is_LC_dns {
                   12874:         &load_hosts_tab() if (!$loaded);
                   12875: 
                   12876:         my ($hostname) = @_;
                   12877:         return exists($LC_dns_serv{$hostname});
                   12878:     }
                   12879: 
1.1       albertel 12880: }
                   12881: 
1.847     albertel 12882: { 
                   12883:     my %iphost;
1.856     albertel 12884:     my %name_to_ip;
                   12885:     my %lonid_to_ip;
1.869     albertel 12886: 
1.847     albertel 12887:     sub get_hosts_from_ip {
                   12888: 	my ($ip) = @_;
                   12889: 	my %iphosts = &get_iphost();
                   12890: 	if (ref($iphosts{$ip})) {
                   12891: 	    return @{$iphosts{$ip}};
                   12892: 	}
                   12893: 	return;
1.839     albertel 12894:     }
1.864     albertel 12895:     
                   12896:     sub reset_hosts_ip_info {
                   12897: 	undef(%iphost);
                   12898: 	undef(%name_to_ip);
                   12899: 	undef(%lonid_to_ip);
                   12900:     }
1.856     albertel 12901: 
                   12902:     sub get_host_ip {
                   12903: 	my ($lonid) = @_;
                   12904: 	if (exists($lonid_to_ip{$lonid})) {
                   12905: 	    return $lonid_to_ip{$lonid};
                   12906: 	}
                   12907: 	my $name=&hostname($lonid);
                   12908:    	my $ip = gethostbyname($name);
                   12909: 	return if (!$ip || length($ip) ne 4);
                   12910: 	$ip=inet_ntoa($ip);
                   12911: 	$name_to_ip{$name}   = $ip;
                   12912: 	$lonid_to_ip{$lonid} = $ip;
                   12913: 	return $ip;
                   12914:     }
1.847     albertel 12915:     
                   12916:     sub get_iphost {
1.1172.2.70  raeburn  12917: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 12918: 
1.869     albertel 12919: 	if (!$ignore_cache) {
                   12920: 	    if (%iphost) {
                   12921: 		return %iphost;
                   12922: 	    }
                   12923: 	    my ($ip_info,$cached)=
                   12924: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12925: 	    if ($cached) {
                   12926: 		%iphost      = %{$ip_info->[0]};
                   12927: 		%name_to_ip  = %{$ip_info->[1]};
                   12928: 		%lonid_to_ip = %{$ip_info->[2]};
                   12929: 		return %iphost;
                   12930: 	    }
                   12931: 	}
1.894     albertel 12932: 
                   12933: 	# get yesterday's info for fallback
                   12934: 	my %old_name_to_ip;
                   12935: 	my ($ip_info,$cached)=
                   12936: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12937: 	if ($cached) {
                   12938: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12939: 	}
                   12940: 
1.1172.2.70  raeburn  12941: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 12942: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12943: 	    my $ip;
                   12944: 	    if (!exists($name_to_ip{$name})) {
                   12945: 		$ip = gethostbyname($name);
                   12946: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12947: 		    if (defined($old_name_to_ip{$name})) {
                   12948: 			$ip = $old_name_to_ip{$name};
                   12949: 			&logthis("Can't find $name defaulting to old $ip");
                   12950: 		    } else {
                   12951: 			&logthis("Name $name no IP found");
                   12952: 			next;
                   12953: 		    }
                   12954: 		} else {
                   12955: 		    $ip=inet_ntoa($ip);
1.847     albertel 12956: 		}
                   12957: 		$name_to_ip{$name} = $ip;
                   12958: 	    } else {
                   12959: 		$ip = $name_to_ip{$name};
1.653     albertel 12960: 	    }
1.888     albertel 12961: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12962: 		$lonid_to_ip{$id} = $ip;
                   12963: 	    }
                   12964: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12965: 	}
1.1172.2.70  raeburn  12966:         unless ($nocache) {
                   12967: 	    &do_cache_new('iphost','iphost',
                   12968: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12969: 		          48*60*60);
                   12970:         }
1.869     albertel 12971: 
1.847     albertel 12972: 	return %iphost;
1.598     albertel 12973:     }
                   12974: 
1.992     raeburn  12975:     #
                   12976:     #  Given a DNS returns the loncapa host name for that DNS 
                   12977:     # 
                   12978:     sub host_from_dns {
                   12979:         my ($dns) = @_;
                   12980:         my @hosts;
                   12981:         my $ip;
                   12982: 
1.993     raeburn  12983:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12984:             $ip = $name_to_ip{$dns};
                   12985:         }
                   12986:         if (!$ip) {
                   12987:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12988:             if (length($ip) == 4) { 
                   12989: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12990:             }
                   12991:         }
                   12992:         if ($ip) {
                   12993: 	    @hosts = get_hosts_from_ip($ip);
                   12994: 	    return $hosts[0];
                   12995:         }
                   12996:         return undef;
1.986     foxr     12997:     }
1.992     raeburn  12998: 
1.1074    raeburn  12999:     sub get_internet_names {
                   13000:         my ($lonid) = @_;
                   13001:         return if ($lonid eq '');
                   13002:         my ($idnref,$cached)=
                   13003:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13004:         if ($cached) {
                   13005:             return $idnref;
                   13006:         }
                   13007:         my $ip = &get_host_ip($lonid);
                   13008:         my @hosts = &get_hosts_from_ip($ip);
                   13009:         my %iphost = &get_iphost();
                   13010:         my (@idns,%seen);
                   13011:         foreach my $id (@hosts) {
                   13012:             my $dom = &host_domain($id);
                   13013:             my $prim_id = &domain($dom,'primary');
                   13014:             my $prim_ip = &get_host_ip($prim_id);
                   13015:             next if ($seen{$prim_ip});
                   13016:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13017:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13018:                     my $intdom = &internet_dom($id);
                   13019:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13020:                         push(@idns,$intdom);
                   13021:                     }
                   13022:                 }
                   13023:             }
                   13024:             $seen{$prim_ip} = 1;
                   13025:         }
1.1172.2.23  raeburn  13026:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13027:     }
                   13028: 
1.986     foxr     13029: }
                   13030: 
1.1079    raeburn  13031: sub all_loncaparevs {
1.1172.2.39  raeburn  13032:     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  13033: }
                   13034: 
1.1172.2.27  raeburn  13035: # ------------------------------------------------------- Read loncaparev table
                   13036: {
                   13037:     sub load_loncaparevs {
                   13038:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   13039:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   13040:                 while (my $configline=<$config>) {
                   13041:                     chomp($configline);
                   13042:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13043:                     $loncaparevs{$hostid}=$loncaparev;
                   13044:                 }
                   13045:                 close($config);
                   13046:             }
                   13047:         }
                   13048:     }
                   13049: }
                   13050: 
                   13051: # ----------------------------------------------------- Read serverhostID table
                   13052: {
                   13053:     sub load_serverhomeIDs {
                   13054:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   13055:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   13056:                 while (my $configline=<$config>) {
                   13057:                     chomp($configline);
                   13058:                     my ($name,$id)=split(/:/,$configline);
                   13059:                     $serverhomeIDs{$name}=$id;
                   13060:                 }
                   13061:                 close($config);
                   13062:             }
                   13063:         }
                   13064:     }
                   13065: }
                   13066: 
                   13067: 
1.862     albertel 13068: BEGIN {
                   13069: 
                   13070: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13071:     unless ($readit) {
                   13072: {
                   13073:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13074:     %perlvar = (%perlvar,%{$configvars});
                   13075: }
                   13076: 
                   13077: 
1.1       albertel 13078: # ------------------------------------------------------ Read spare server file
                   13079: {
1.448     albertel 13080:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13081: 
                   13082:     while (my $configline=<$config>) {
                   13083:        chomp($configline);
1.284     matthew  13084:        if ($configline) {
1.784     albertel 13085: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13086: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13087: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13088:        }
                   13089:     }
1.448     albertel 13090:     close($config);
1.1       albertel 13091: }
1.11      www      13092: # ------------------------------------------------------------ Read permissions
                   13093: {
1.448     albertel 13094:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13095: 
                   13096:     while (my $configline=<$config>) {
1.448     albertel 13097: 	chomp($configline);
                   13098: 	if ($configline) {
                   13099: 	    my ($role,$perm)=split(/ /,$configline);
                   13100: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13101: 	}
1.11      www      13102:     }
1.448     albertel 13103:     close($config);
1.11      www      13104: }
                   13105: 
                   13106: # -------------------------------------------- Read plain texts for permissions
                   13107: {
1.448     albertel 13108:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13109: 
                   13110:     while (my $configline=<$config>) {
1.448     albertel 13111: 	chomp($configline);
                   13112: 	if ($configline) {
1.742     raeburn  13113: 	    my ($short,@plain)=split(/:/,$configline);
                   13114:             %{$prp{$short}} = ();
                   13115: 	    if (@plain > 0) {
                   13116:                 $prp{$short}{'std'} = $plain[0];
                   13117:                 for (my $i=1; $i<@plain; $i++) {
                   13118:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13119:                 }
                   13120:             }
1.448     albertel 13121: 	}
1.135     www      13122:     }
1.448     albertel 13123:     close($config);
1.135     www      13124: }
                   13125: 
                   13126: # ---------------------------------------------------------- Read package table
                   13127: {
1.448     albertel 13128:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13129: 
                   13130:     while (my $configline=<$config>) {
1.483     albertel 13131: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13132: 	chomp($configline);
                   13133: 	my ($short,$plain)=split(/:/,$configline);
                   13134: 	my ($pack,$name)=split(/\&/,$short);
                   13135: 	if ($plain ne '') {
                   13136: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13137: 	    $packagetab{$short}=$plain; 
                   13138: 	}
1.11      www      13139:     }
1.448     albertel 13140:     close($config);
1.329     matthew  13141: }
                   13142: 
1.1172.2.27  raeburn  13143: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13144: 
1.1172.2.27  raeburn  13145: &load_loncaparevs();
                   13146: 
                   13147: # ------------------------------------------------------- Read serverhostID table
                   13148: 
                   13149: &load_serverhomeIDs();
1.1074    raeburn  13150: 
1.1172.2.27  raeburn  13151: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13152: {
                   13153:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13154:     if (-e $file) {
                   13155:         my $parser = HTML::LCParser->new($file);
                   13156:         while (my $token = $parser->get_token()) {
                   13157:             if ($token->[0] eq 'S') {
                   13158:                 my $item = $token->[1];
                   13159:                 my $name = $token->[2]{'name'};
                   13160:                 my $value = $token->[2]{'value'};
                   13161:                 if ($item ne '' && $name ne '' && $value ne '') {
                   13162:                     my $release = $parser->get_text();
                   13163:                     $release =~ s/(^\s*|\s*$ )//gx;
                   13164:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   13165:                 }
                   13166:             }
                   13167:         }
                   13168:     }
1.1073    raeburn  13169: }
                   13170: 
1.1138    raeburn  13171: # ---------------------------------------------------------- Read managers table
                   13172: {
                   13173:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13174:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13175:             while (my $configline=<$config>) {
                   13176:                 chomp($configline);
                   13177:                 next if ($configline =~ /^\#/);
                   13178:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13179:                     $managerstab{$configline} = 1;
                   13180:                 }
                   13181:             }
                   13182:             close($config);
                   13183:         }
                   13184:     }
                   13185: }
                   13186: 
1.329     matthew  13187: # ------------- set up temporary directory
                   13188: {
1.1117    foxr     13189:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13190: 
1.11      www      13191: }
                   13192: 
1.794     albertel 13193: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13194: 				'compress_threshold'=> 20_000,
                   13195:  			        });
1.185     www      13196: 
1.281     www      13197: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13198: $dumpcount=0;
1.958     www      13199: $locknum=0;
1.22      www      13200: 
1.163     harris41 13201: &logtouch();
1.672     albertel 13202: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13203: $readit=1;
1.564     albertel 13204:     {
                   13205: 	use integer;
                   13206: 	my $test=(2**32)+1;
1.568     albertel 13207: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13208: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13209:     }
1.195     www      13210: }
1.1       albertel 13211: }
1.179     www      13212: 
1.1       albertel 13213: 1;
1.191     harris41 13214: __END__
                   13215: 
1.243     albertel 13216: =pod
                   13217: 
1.191     harris41 13218: =head1 NAME
                   13219: 
1.243     albertel 13220: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13221: 
                   13222: =head1 SYNOPSIS
                   13223: 
1.243     albertel 13224: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13225: 
                   13226:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13227: 
1.243     albertel 13228: Common parameters:
                   13229: 
                   13230: =over 4
                   13231: 
                   13232: =item *
                   13233: 
                   13234: $uname : an internal username (if $cname expecting a course Id specifically)
                   13235: 
                   13236: =item *
                   13237: 
                   13238: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13239: 
                   13240: =item *
                   13241: 
                   13242: $symb : a resource instance identifier
                   13243: 
                   13244: =item *
                   13245: 
                   13246: $namespace : the name of a .db file that contains the data needed or
                   13247: being set.
                   13248: 
                   13249: =back
                   13250: 
1.394     bowersj2 13251: =head1 OVERVIEW
1.191     harris41 13252: 
1.394     bowersj2 13253: lonnet provides subroutines which interact with the
                   13254: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13255: about classes, users, and resources.
1.243     albertel 13256: 
                   13257: For many of these objects you can also use this to store data about
                   13258: them or modify them in various ways.
1.191     harris41 13259: 
1.394     bowersj2 13260: =head2 Symbs
1.191     harris41 13261: 
1.394     bowersj2 13262: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13263: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13264: map, the resource number of the resource in the map, and the URL of
                   13265: the resource itself. The latter is somewhat redundant, but might help
                   13266: if maps change.
                   13267: 
                   13268: An example is
                   13269: 
                   13270:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13271: 
                   13272: The respective map entry is
                   13273: 
                   13274:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13275:   title="Problem 2">
                   13276:  </resource>
                   13277: 
                   13278: Symbs are used by the random number generator, as well as to store and
                   13279: restore data specific to a certain instance of for example a problem.
                   13280: 
                   13281: =head2 Storing And Retrieving Data
                   13282: 
                   13283: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13284: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13285: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13286: is is the non-critical message twin of cstore. These functions are for
                   13287: handlers to store a perl hash to a user's permanent data space in an
                   13288: easy manner, and to retrieve it again on another call. It is expected
                   13289: that a handler would use this once at the beginning to retrieve data,
                   13290: and then again once at the end to send only the new data back.
                   13291: 
                   13292: The data is stored in the user's data directory on the user's
                   13293: homeserver under the ID of the course.
                   13294: 
                   13295: The hash that is returned by restore will have all of the previous
                   13296: value for all of the elements of the hash.
                   13297: 
                   13298: Example:
                   13299: 
                   13300:  #creating a hash
                   13301:  my %hash;
                   13302:  $hash{'foo'}='bar';
                   13303: 
                   13304:  #storing it
                   13305:  &Apache::lonnet::cstore(\%hash);
                   13306: 
                   13307:  #changing a value
                   13308:  $hash{'foo'}='notbar';
                   13309: 
                   13310:  #adding a new value
                   13311:  $hash{'bar'}='foo';
                   13312:  &Apache::lonnet::cstore(\%hash);
                   13313: 
                   13314:  #retrieving the hash
                   13315:  my %history=&Apache::lonnet::restore();
                   13316: 
                   13317:  #print the hash
                   13318:  foreach my $key (sort(keys(%history))) {
                   13319:    print("\%history{$key} = $history{$key}");
                   13320:  }
                   13321: 
                   13322: Will print out:
1.191     harris41 13323: 
1.394     bowersj2 13324:  %history{1:foo} = bar
                   13325:  %history{1:keys} = foo:timestamp
                   13326:  %history{1:timestamp} = 990455579
                   13327:  %history{2:bar} = foo
                   13328:  %history{2:foo} = notbar
                   13329:  %history{2:keys} = foo:bar:timestamp
                   13330:  %history{2:timestamp} = 990455580
                   13331:  %history{bar} = foo
                   13332:  %history{foo} = notbar
                   13333:  %history{timestamp} = 990455580
                   13334:  %history{version} = 2
                   13335: 
                   13336: Note that the special hash entries C<keys>, C<version> and
                   13337: C<timestamp> were added to the hash. C<version> will be equal to the
                   13338: total number of versions of the data that have been stored. The
                   13339: C<timestamp> attribute will be the UNIX time the hash was
                   13340: stored. C<keys> is available in every historical section to list which
                   13341: keys were added or changed at a specific historical revision of a
                   13342: hash.
                   13343: 
                   13344: B<Warning>: do not store the hash that restore returns directly. This
                   13345: will cause a mess since it will restore the historical keys as if the
                   13346: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13347: 
1.394     bowersj2 13348: Calling convention:
1.191     harris41 13349: 
1.1172.2.27  raeburn  13350:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  13351:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13352: 
1.394     bowersj2 13353: For more detailed information, see lonnet specific documentation.
1.191     harris41 13354: 
1.394     bowersj2 13355: =head1 RETURN MESSAGES
1.191     harris41 13356: 
1.394     bowersj2 13357: =over 4
1.191     harris41 13358: 
1.394     bowersj2 13359: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13360: 
1.394     bowersj2 13361: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13362: when the connection is brought back up
1.191     harris41 13363: 
1.394     bowersj2 13364: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13365: for later delivery
1.191     harris41 13366: 
1.967     bisitz   13367: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13368: 
1.394     bowersj2 13369: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13370: that was requested
1.191     harris41 13371: 
1.243     albertel 13372: =back
1.191     harris41 13373: 
1.243     albertel 13374: =head1 PUBLIC SUBROUTINES
1.191     harris41 13375: 
1.243     albertel 13376: =head2 Session Environment Functions
1.191     harris41 13377: 
1.243     albertel 13378: =over 4
1.191     harris41 13379: 
1.394     bowersj2 13380: =item * 
                   13381: X<appenv()>
1.949     raeburn  13382: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13383: the user envirnoment file, and will be restored for each access this
1.620     albertel 13384: user makes during this session, also modifies the %env for the current
1.949     raeburn  13385: process. Optional rolesarrayref - if defined contains a reference to an array
                   13386: of roles which are exempt from the restriction on modifying user.role entries 
                   13387: in the user's environment.db and in %env.    
1.191     harris41 13388: 
                   13389: =item *
1.394     bowersj2 13390: X<delenv()>
1.987     raeburn  13391: B<delenv($delthis,$regexp)>: removes all items from the session
                   13392: environment file that begin with $delthis. If the 
                   13393: optional second arg - $regexp - is true, $delthis is treated as a 
                   13394: regular expression, otherwise \Q$delthis\E is used. 
                   13395: The values are also deleted from the current processes %env.
1.191     harris41 13396: 
1.795     albertel 13397: =item * get_env_multiple($name) 
                   13398: 
                   13399: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13400: values may be defined and end up as an array ref.
                   13401: 
                   13402: returns an array of values
                   13403: 
1.243     albertel 13404: =back
                   13405: 
                   13406: =head2 User Information
1.191     harris41 13407: 
1.243     albertel 13408: =over 4
1.191     harris41 13409: 
                   13410: =item *
1.394     bowersj2 13411: X<queryauthenticate()>
                   13412: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13413: authentication scheme
                   13414: 
                   13415: =item *
1.394     bowersj2 13416: X<authenticate()>
1.1073    raeburn  13417: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13418: authenticate user from domain's lib servers (first use the current
                   13419: one). C<$upass> should be the users password.
1.1073    raeburn  13420: $checkdefauth is optional (value is 1 if a check should be made to
                   13421:    authenticate user using default authentication method, and allow
                   13422:    account creation if username does not have account in the domain).
                   13423: $clientcancheckhost is optional (value is 1 if checking whether the
                   13424:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13425: 
                   13426: =item *
1.394     bowersj2 13427: X<homeserver()>
                   13428: B<homeserver($uname,$udom)>: find the server which has
                   13429: the user's directory and files (there must be only one), this caches
                   13430: the answer, and also caches if there is a borken connection.
1.191     harris41 13431: 
                   13432: =item *
1.394     bowersj2 13433: X<idget()>
                   13434: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13435: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13436: username, and only 1 username per ID in a specific domain) (returns
                   13437: hash: id=>name,id=>name)
1.191     harris41 13438: 
                   13439: =item *
1.394     bowersj2 13440: X<idrget()>
                   13441: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13442: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13443: 
                   13444: =item *
1.394     bowersj2 13445: X<idput()>
                   13446: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13447: 
                   13448: =item *
1.394     bowersj2 13449: X<rolesinit()>
1.1169    droeschl 13450: B<rolesinit($udom,$username)>: get user privileges.
                   13451: returns user role, first access and timer interval hashes
1.243     albertel 13452: 
                   13453: =item *
1.1171    droeschl 13454: X<privileged()>
                   13455: B<privileged($username,$domain)>: returns a true if user has a
                   13456: privileged and active role (i.e. su or dc), false otherwise.
                   13457: 
                   13458: =item *
1.551     albertel 13459: X<getsection()>
                   13460: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13461: course $cname, return section name/number or '' for "not in course"
                   13462: and '-1' for "no section"
                   13463: 
                   13464: =item *
1.394     bowersj2 13465: X<userenvironment()>
                   13466: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13467: passed in @what from the requested user's environment, returns a hash
                   13468: 
1.858     raeburn  13469: =item * 
                   13470: X<userlog_query()>
1.859     albertel 13471: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13472: activity.log file. %filters defines filters applied when parsing the
                   13473: log file. These can be start or end timestamps, or the type of action
                   13474: - log to look for Login or Logout events, check for Checkin or
                   13475: Checkout, role for role selection. The response is in the form
                   13476: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13477: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13478: 
1.243     albertel 13479: =back
                   13480: 
                   13481: =head2 User Roles
                   13482: 
                   13483: =over 4
                   13484: 
                   13485: =item *
                   13486: 
1.1172.2.65  raeburn  13487: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13488: returns codes for allowed actions.
                   13489: 
                   13490: The first argument is required, all others are optional.
                   13491: 
                   13492: $priv is the privilege being checked.
                   13493: $uri contains additional information about what is being checked for access (e.g.,
                   13494: URL, course ID etc.).
                   13495: $symb is the unique resource instance identifier in a course; if needed,
                   13496: but not provided, it will be retrieved via a call to &symbread().
                   13497: $role is the role for which a priv is being checked (only used if priv is evb).
                   13498: $clientip is the user's IP address (only used when checking for access to portfolio
                   13499: files).
                   13500: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   13501: prevents recursive calls to &allowed.
                   13502: 
1.243     albertel 13503:  F: full access
                   13504:  U,I,K: authentication modes (cxx only)
                   13505:  '': forbidden
                   13506:  1: user needs to choose course
                   13507:  2: browse allowed
1.766     albertel 13508:  A: passphrase authentication needed
1.1172.2.65  raeburn  13509:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13510: 
                   13511: =item *
                   13512: 
1.1172.2.13  raeburn  13513: constructaccess($url,$setpriv) : check for access to construction space URL
                   13514: 
                   13515: See if the owner domain and name in the URL match those in the
                   13516: expected environment.  If so, return three element list
                   13517: ($ownername,$ownerdomain,$ownerhome).
                   13518: 
                   13519: Otherwise return the null string.
                   13520: 
                   13521: If second argument 'setpriv' is true, it assigns the privileges,
                   13522: and returns the same three element list, unless the owner has
                   13523: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13524: in which case the null string is returned.
                   13525: 
                   13526: =item *
                   13527: 
1.1172.2.84  raeburn  13528: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   13529: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   13530: for system, domain, and course level. $uname and $udom are optional (current
                   13531: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 13532: 
                   13533: =item *
                   13534: 
1.988     raeburn  13535: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13536: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13537: $type is Course (default) or Community.
1.988     raeburn  13538: If $forcedefault evaluates to true, text returned will be default 
                   13539: text for $type. Otherwise, if this is a course, the text returned 
                   13540: will be a custom name for the role (if defined in the course's 
                   13541: environment).  If no custom name is defined the default is returned.
                   13542:    
1.832     raeburn  13543: =item *
                   13544: 
1.1172.2.23  raeburn  13545: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13546: All arguments are optional. Returns a hash of a roles, either for
                   13547: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13548: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13549: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13550: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13551: For each key, value is set to colon-separated start and end times for
                   13552: the role.  If no username and domain are specified, will default to
1.934     raeburn  13553: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13554: of role statuses (active, future or previous), roles 
                   13555: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13556: to restrict the list of roles reported. If no array ref is 
                   13557: provided for types, will default to return only active roles.
1.834     albertel 13558: 
1.1172.2.13  raeburn  13559: =item *
                   13560: 
                   13561: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   13562: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   13563: 
                   13564: Additional optional arguments are: $type (if role checking is to be restricted
                   13565: to certain user status types -- previous (expired roles), active (currently
                   13566: available roles) or future (roles available in the future), and
                   13567: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  13568: have active Domain Coordinator role in course's domain or in additional
                   13569: domains (specified in 'Domains to check for privileged users' in course
                   13570: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13571: 
                   13572: =item *
                   13573: 
                   13574: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13575: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13576: $possdomains and $possroles are optional array refs -- to domains to check and
                   13577: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13578: users' roles.db to check for a dc or su role in any domain. This can be
                   13579: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13580: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13581: this then allows &privileged_by_domain() to be used, which caches the identity
                   13582: of privileged users, eliminating the need for repeated calls to &dump().
                   13583: 
                   13584: =item *
                   13585: 
                   13586: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13587: where the outer hash keys are domains specified in the $possdomains array ref,
                   13588: next inner hash keys are privileged roles specified in the $roles array ref,
                   13589: and the innermost hash contains key = value pairs for username:domain = end:start
                   13590: for active or future "privileged" users with that role in that domain. To avoid
                   13591: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13592: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  13593: 
1.243     albertel 13594: =back
                   13595: 
                   13596: =head2 User Modification
                   13597: 
                   13598: =over 4
                   13599: 
                   13600: =item *
                   13601: 
1.957     raeburn  13602: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13603: user for the level given by URL.  Optional start and end dates (leave empty
                   13604: string or zero for "no date")
1.191     harris41 13605: 
                   13606: =item *
                   13607: 
1.243     albertel 13608: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13609: change a users, password, possible return values are: ok,
                   13610: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13611: refused
1.191     harris41 13612: 
                   13613: =item *
                   13614: 
1.243     albertel 13615: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13616: 
                   13617: =item *
                   13618: 
1.1058    raeburn  13619: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13620:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13621: 
                   13622: will update user information (firstname,middlename,lastname,generation,
                   13623: permanentemail), and if forceid is true, student/employee ID also.
                   13624: A user's institutional affiliation(s) can also be updated.
                   13625: User information fields will not be overwritten with empty entries 
                   13626: unless the field is included in the $candelete array reference.
                   13627: This array is included when a single user is modified via "Manage Users",
                   13628: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13629: 
                   13630: =item *
                   13631: 
1.286     matthew  13632: modifystudent
                   13633: 
1.957     raeburn  13634: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  13635: The course id is resolved based on the current user's environment.  
                   13636: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13637: associated with a course.
                   13638: 
1.297     matthew  13639: This call is essentially a wrapper for lonnet::modifyuser and
                   13640: lonnet::modify_student_enrollment
1.286     matthew  13641: 
                   13642: Inputs: 
                   13643: 
                   13644: =over 4
                   13645: 
1.957     raeburn  13646: =item B<$udom> Student's loncapa domain
1.286     matthew  13647: 
1.957     raeburn  13648: =item B<$uname> Student's loncapa login name
1.286     matthew  13649: 
1.964     bisitz   13650: =item B<$uid> Student/Employee ID
1.286     matthew  13651: 
1.957     raeburn  13652: =item B<$umode> Student's authentication mode
1.286     matthew  13653: 
1.957     raeburn  13654: =item B<$upass> Student's password
1.286     matthew  13655: 
1.957     raeburn  13656: =item B<$first> Student's first name
1.286     matthew  13657: 
1.957     raeburn  13658: =item B<$middle> Student's middle name
1.286     matthew  13659: 
1.957     raeburn  13660: =item B<$last> Student's last name
1.286     matthew  13661: 
1.957     raeburn  13662: =item B<$gene> Student's generation
1.286     matthew  13663: 
1.957     raeburn  13664: =item B<$usec> Student's section in course
1.286     matthew  13665: 
                   13666: =item B<$end> Unix time of the roles expiration
                   13667: 
                   13668: =item B<$start> Unix time of the roles start date
                   13669: 
                   13670: =item B<$forceid> If defined, allow $uid to be changed
                   13671: 
                   13672: =item B<$desiredhome> server to use as home server for student
                   13673: 
1.957     raeburn  13674: =item B<$email> Student's permanent e-mail address
                   13675: 
                   13676: =item B<$type> Type of enrollment (auto or manual)
                   13677: 
1.963     raeburn  13678: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13679: 
                   13680: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13681: 
1.963     raeburn  13682: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13683: 
1.963     raeburn  13684: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13685: 
1.1172.2.19  raeburn  13686: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13687: 
                   13688: =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  13689: 
1.286     matthew  13690: =back
1.297     matthew  13691: 
                   13692: =item *
                   13693: 
                   13694: modify_student_enrollment
                   13695: 
1.1172.2.31  raeburn  13696: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13697: 'role.request.course' must be defined for this function to proceed.
                   13698: 
                   13699: Inputs:
                   13700: 
                   13701: =over 4
                   13702: 
1.1172.2.31  raeburn  13703: =item $udom, student's domain
1.297     matthew  13704: 
1.1172.2.31  raeburn  13705: =item $uname, student's name
1.297     matthew  13706: 
1.1172.2.31  raeburn  13707: =item $uid, student's user id
1.297     matthew  13708: 
1.1172.2.31  raeburn  13709: =item $first, student's first name
1.297     matthew  13710: 
                   13711: =item $middle
                   13712: 
                   13713: =item $last
                   13714: 
                   13715: =item $gene
                   13716: 
                   13717: =item $usec
                   13718: 
                   13719: =item $end
                   13720: 
                   13721: =item $start
                   13722: 
1.957     raeburn  13723: =item $type
                   13724: 
                   13725: =item $locktype
                   13726: 
                   13727: =item $cid
                   13728: 
                   13729: =item $selfenroll
                   13730: 
                   13731: =item $context
                   13732: 
1.1172.2.19  raeburn  13733: =item $credits, number of credits student will earn from this class
                   13734: 
1.1172.2.76  raeburn  13735: =item $instsec, institutional course section code for student
                   13736: 
1.297     matthew  13737: =back
                   13738: 
1.191     harris41 13739: 
                   13740: =item *
                   13741: 
1.243     albertel 13742: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13743: custom role; give a custom role to a user for the level given by URL.  Specify
                   13744: name and domain of role author, and role name
1.191     harris41 13745: 
                   13746: =item *
                   13747: 
1.243     albertel 13748: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13749: 
                   13750: =item *
                   13751: 
1.243     albertel 13752: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13753: 
                   13754: =back
                   13755: 
                   13756: =head2 Course Infomation
                   13757: 
                   13758: =over 4
1.191     harris41 13759: 
                   13760: =item *
                   13761: 
1.1118    foxr     13762: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13763: specified course id, including all environment settings for the
                   13764: course, the description of the course will be in the hash under the
                   13765: key 'description'
1.191     harris41 13766: 
1.1118    foxr     13767: $options is an optional parameter that if supplied is a hash reference that controls
                   13768: what how this function works.  It has the following key/values:
                   13769: 
                   13770: =over 4
                   13771: 
                   13772: =item freshen_cache
                   13773: 
                   13774: If defined, and the environment cache for the course is valid, it is 
                   13775: returned in the returned hash.
                   13776: 
                   13777: =item one_time
                   13778: 
                   13779: If defined, the last cache time is set to _now_
                   13780: 
                   13781: =item user
                   13782: 
                   13783: If defined, the supplied username is used instead of the current user.
                   13784: 
                   13785: 
                   13786: =back
                   13787: 
1.191     harris41 13788: =item *
                   13789: 
1.624     albertel 13790: resdata($name,$domain,$type,@which) : request for current parameter
                   13791: setting for a specific $type, where $type is either 'course' or 'user',
                   13792: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  13793: answers for 10 minutes.
1.243     albertel 13794: 
1.877     foxr     13795: =item *
                   13796: 
                   13797: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13798: data base, returning a hash that is keyed by the resource name and has
                   13799: values that are the resource value.  I believe that the timestamps and
                   13800: versions are also returned.
                   13801: 
1.1172.2.31  raeburn  13802: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13803: supplemental content area. This routine caches the number of files for
                   13804: 10 minutes.
                   13805: 
1.243     albertel 13806: =back
                   13807: 
                   13808: =head2 Course Modification
                   13809: 
                   13810: =over 4
1.191     harris41 13811: 
                   13812: =item *
                   13813: 
1.243     albertel 13814: writecoursepref($courseid,%prefs) : write preferences (environment
                   13815: database) for a course
1.191     harris41 13816: 
                   13817: =item *
                   13818: 
1.1011    raeburn  13819: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13820: 
                   13821: =item *
                   13822: 
1.1038    raeburn  13823: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13824: 
1.1167    droeschl 13825: =item *
                   13826: 
                   13827: is_course($courseid), is_course($cdom, $cnum)
                   13828: 
                   13829: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13830: two component version $cdom, $cnum. It checks if the specified course exists.
                   13831: 
                   13832: Returns:
                   13833:     undef if the course doesn't exist, otherwise
                   13834:     in scalar context the combined courseid.
                   13835:     in list context the two components of the course identifier, domain and 
                   13836:     courseid.    
                   13837: 
1.243     albertel 13838: =back
                   13839: 
                   13840: =head2 Resource Subroutines
                   13841: 
                   13842: =over 4
1.191     harris41 13843: 
                   13844: =item *
                   13845: 
1.243     albertel 13846: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13847: 
                   13848: =item *
                   13849: 
1.243     albertel 13850: repcopy($filename) : subscribes to the requested file, and attempts to
                   13851: replicate from the owning library server, Might return
1.607     raeburn  13852: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13853: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13854: resource. Expects the local filesystem pathname
                   13855: (/home/httpd/html/res/....)
                   13856: 
                   13857: =back
                   13858: 
                   13859: =head2 Resource Information
                   13860: 
                   13861: =over 4
1.191     harris41 13862: 
                   13863: =item *
                   13864: 
1.1172.2.28  raeburn  13865: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13866: and returns the value of a variety of different possible values,
                   13867: $varname should be a request string, and the other parameters can be
                   13868: used to specify who and what one is asking about. Ordinarily, $cid 
                   13869: does not need to be specified, as it is retrived from 
                   13870: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13871: within lonuserstate::loadmap() when initializing a course, before
                   13872: $env{'request.course.id'} has been set, so it needs to be provided
                   13873: in that one case.
1.243     albertel 13874: 
                   13875: Possible values for $varname are environment.lastname (or other item
                   13876: from the envirnment hash), user.name (or someother aspect about the
                   13877: user), resource.0.maxtries (or some other part and parameter of a
                   13878: resource)
1.204     albertel 13879: 
                   13880: =item *
                   13881: 
1.243     albertel 13882: directcondval($number) : get current value of a condition; reads from a state
                   13883: string
1.204     albertel 13884: 
                   13885: =item *
                   13886: 
1.243     albertel 13887: condval($condidx) : value of condition index based on state
1.204     albertel 13888: 
                   13889: =item *
                   13890: 
1.243     albertel 13891: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13892: resource's metadata, $what should be either a specific key, or either
                   13893: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13894: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13895: 
                   13896: this function automatically caches all requests
1.191     harris41 13897: 
                   13898: =item *
                   13899: 
1.243     albertel 13900: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13901: network of library servers; returns file handle of where SQL and regex results
                   13902: will be stored for query
1.191     harris41 13903: 
                   13904: =item *
                   13905: 
1.1172.2.66  raeburn  13906: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   13907: return symbolic list entry (all arguments optional).
                   13908: 
                   13909: Args: filename is the filename (including path) for the file for which a symb
                   13910: is required; donotrecurse, if true will prevent calls to allowed() being made
                   13911: to check access status if more than one resource was found in the bighash
                   13912: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   13913: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   13914: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   13915: cause possible symbs to be checked to determine if they are subject to content
                   13916: blocking, if so they will not be included as possible symbs; possibles is a
                   13917: ref to a hash, which, as a side effect, will be populated with all possible
                   13918: symbs (content blocking not tested).
                   13919: 
1.243     albertel 13920: returns the data handle
1.191     harris41 13921: 
                   13922: =item *
                   13923: 
1.1172.2.17  raeburn  13924: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  13925: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13926: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  13927: on failure, user must be in a course, as it assumes the existence of
                   13928: the course initial hash, and uses $env('request.course.id'}.  The third
                   13929: arg is an optional reference to a scalar.  If this arg is passed in the
                   13930: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13931: encrypted; otherwise it will be null.
1.243     albertel 13932: 
1.191     harris41 13933: =item *
                   13934: 
1.243     albertel 13935: symbclean($symb) : removes versions numbers from a symb, returns the
                   13936: cleaned symb
1.191     harris41 13937: 
                   13938: =item *
                   13939: 
1.243     albertel 13940: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13941: course map, user must be in a course for it to work.
1.191     harris41 13942: 
                   13943: =item *
                   13944: 
1.243     albertel 13945: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13946: 
                   13947: =item *
                   13948: 
1.243     albertel 13949: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13950: a random seed, all arguments are optional, if they aren't sent it uses the
                   13951: environment to derive them. Note: if symb isn't sent and it can't get one
                   13952: from &symbread it will use the current time as its return value
1.191     harris41 13953: 
                   13954: =item *
                   13955: 
1.243     albertel 13956: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13957: unfakeable, receipt
1.191     harris41 13958: 
                   13959: =item *
                   13960: 
1.620     albertel 13961: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13962: 
                   13963: =item *
                   13964: 
1.243     albertel 13965: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13966: 
                   13967: =item *
                   13968: 
1.243     albertel 13969: 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 13970: 
                   13971: =item *
                   13972: 
1.243     albertel 13973: 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 13974: 
                   13975: =item *
                   13976: 
1.243     albertel 13977: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13978: 
                   13979: =item *
                   13980: 
1.243     albertel 13981: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13982: forcing spreadsheet to reevaluate the resource scores next time.
                   13983: 
1.1172.2.13  raeburn  13984: =item *
                   13985: 
                   13986: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13987: when viewing in course context.
                   13988: 
                   13989:  input: six args -- filename (decluttered), course number, course domain,
                   13990:                     url, symb (if registered) and group (if this is a
                   13991:                     group item -- e.g., bulletin board, group page etc.).
                   13992: 
                   13993:  output: array of five scalars --
                   13994:          $cfile -- url for file editing if editable on current server
                   13995:          $home -- homeserver of resource (i.e., for author if published,
                   13996:                                           or course if uploaded.).
                   13997:          $switchserver --  1 if server switch will be needed.
                   13998:          $forceedit -- 1 if icon/link should be to go to edit mode
                   13999:          $forceview -- 1 if icon/link should be to go to view mode
                   14000: 
                   14001: =item *
                   14002: 
                   14003: is_course_upload($file,$cnum,$cdom)
                   14004: 
                   14005: Used in course context to determine if current file was uploaded to
                   14006: the course (i.e., would be found in /userfiles/docs on the course's
                   14007: homeserver.
                   14008: 
                   14009:   input: 3 args -- filename (decluttered), course number and course domain.
                   14010:   output: boolean -- 1 if file was uploaded.
                   14011: 
1.243     albertel 14012: =back
                   14013: 
                   14014: =head2 Storing/Retreiving Data
                   14015: 
                   14016: =over 4
1.191     harris41 14017: 
                   14018: =item *
                   14019: 
1.1172.2.64  raeburn  14020: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14021: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14022: the remaining args aren't required and if they aren't passed or are '' they will
                   14023: be derived from the env (with the exception of $laststore, which is an
                   14024: optional arg used when a user's submission is stored in grading).
                   14025: $laststore is $version=$timestamp, where $version is the most recent version
                   14026: number retrieved for the corresponding $symb in the $namespace db file, and
                   14027: $timestamp is the timestamp for that transaction (UNIX time).
                   14028: $laststore is currently only passed when cstore() is called by
                   14029: structuretags::finalize_storage().
1.191     harris41 14030: 
                   14031: =item *
                   14032: 
1.1172.2.64  raeburn  14033: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14034: but uses critical subroutine
1.191     harris41 14035: 
                   14036: =item *
                   14037: 
1.243     albertel 14038: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14039: all args are optional
1.191     harris41 14040: 
                   14041: =item *
                   14042: 
1.717     albertel 14043: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14044: dumps the complete (or key matching regexp) namespace into a hash
                   14045: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14046: normally &store()ed into
                   14047: 
                   14048: $range should be either an integer '100' (give me the first 100
                   14049:                                            matching records)
                   14050:               or be  two integers sperated by a - with no spaces
                   14051:                  '30-50' (give me the 30th through the 50th matching
                   14052:                           records)
                   14053: 
                   14054: 
                   14055: =item *
                   14056: 
1.1172.2.59  raeburn  14057: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14058: replaces a &store() version of data with a replacement set of data
                   14059: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  14060: reference. If $tolog is true, the transaction is logged in the courselog
                   14061: with an action=PUTSTORE.
1.717     albertel 14062: 
                   14063: =item *
                   14064: 
1.243     albertel 14065: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14066: works very similar to store/cstore, but all data is stored in a
                   14067: temporary location and can be reset using tmpreset, $storehash should
                   14068: be a hash reference, returns nothing on success
1.191     harris41 14069: 
                   14070: =item *
                   14071: 
1.243     albertel 14072: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14073: similar to restore, but all data is stored in a temporary location and
                   14074: can be reset using tmpreset. Returns a hash of values on success,
                   14075: error string otherwise.
1.191     harris41 14076: 
                   14077: =item *
                   14078: 
1.243     albertel 14079: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14080: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14081: 
                   14082: =item *
                   14083: 
1.243     albertel 14084: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14085: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14086: 
                   14087: =item *
                   14088: 
1.243     albertel 14089: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14090: namesp ($udom and $uname are optional)
1.191     harris41 14091: 
                   14092: =item *
                   14093: 
1.702     albertel 14094: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14095: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14096: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14097: 
1.702     albertel 14098: $range should be either an integer '100' (give me the first 100
                   14099:                                            matching records)
                   14100:               or be  two integers sperated by a - with no spaces
                   14101:                  '30-50' (give me the 30th through the 50th matching
                   14102:                           records)
1.449     matthew  14103: =item *
                   14104: 
                   14105: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14106: $store can be a scalar, an array reference, or if the amount to be 
                   14107: incremented is > 1, a hash reference.
                   14108: 
                   14109: ($udom and $uname are optional)
1.191     harris41 14110: 
                   14111: =item *
                   14112: 
1.243     albertel 14113: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14114: ($udom and $uname are optional)
1.191     harris41 14115: 
                   14116: =item *
                   14117: 
1.243     albertel 14118: cput($namespace,$storehash,$udom,$uname) : critical put
                   14119: ($udom and $uname are optional)
1.191     harris41 14120: 
                   14121: =item *
                   14122: 
1.748     albertel 14123: newput($namespace,$storehash,$udom,$uname) :
                   14124: 
                   14125: Attempts to store the items in the $storehash, but only if they don't
                   14126: currently exist, if this succeeds you can be certain that you have 
                   14127: successfully created a new key value pair in the $namespace db.
                   14128: 
                   14129: 
                   14130: Args:
                   14131:  $namespace: name of database to store values to
                   14132:  $storehash: hashref to store to the db
                   14133:  $udom: (optional) domain of user containing the db
                   14134:  $uname: (optional) name of user caontaining the db
                   14135: 
                   14136: Returns:
                   14137:  'ok' -> succeeded in storing all keys of $storehash
                   14138:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14139:                         least <key> already existed in the db (other
                   14140:                         requested keys may also already exist)
1.967     bisitz   14141:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14142:  'con_lost' -> unable to contact request server
                   14143:  'refused' -> action was not allowed by remote machine
                   14144: 
                   14145: 
                   14146: =item *
                   14147: 
1.243     albertel 14148: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14149: reference filled in from namesp (encrypts the return communication)
                   14150: ($udom and $uname are optional)
1.191     harris41 14151: 
                   14152: =item *
                   14153: 
1.243     albertel 14154: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14155: critical subroutine
                   14156: 
1.806     raeburn  14157: =item *
                   14158: 
1.860     raeburn  14159: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14160: array reference filled in from namespace found in domain level on either
                   14161: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14162: 
                   14163: =item *
                   14164: 
1.860     raeburn  14165: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14166: domain level either on specified domain server ($uhome) or primary domain 
                   14167: server ($udom and $uhome are optional)
1.806     raeburn  14168: 
1.943     raeburn  14169: =item * 
                   14170: 
1.1172.2.35  raeburn  14171: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   14172: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14173: the target domain.
                   14174: 
                   14175: May also include additional key => value pairs for the following groups:
                   14176: 
                   14177: =over
                   14178: 
                   14179: =item
                   14180: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14181: 
                   14182: =over
                   14183: 
                   14184: =item defaultquota, authorquota
                   14185: 
                   14186: =back
                   14187: 
                   14188: =item
                   14189: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14190: portfolio for users).
                   14191: 
                   14192: =over
                   14193: 
                   14194: =item
                   14195: aboutme, blog, webdav, portfolio
                   14196: 
                   14197: =back
                   14198: 
                   14199: =item
                   14200: requestcourses: ability to request courses, and how requests are processed.
                   14201: 
                   14202: =over
                   14203: 
                   14204: =item
1.1172.2.37  raeburn  14205: official, unofficial, community, textbook
1.1172.2.35  raeburn  14206: 
                   14207: =back
                   14208: 
                   14209: =item
                   14210: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14211: 
                   14212: =over
                   14213: 
                   14214: =item
1.1172.2.44  raeburn  14215: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  14216: 
                   14217: =back
                   14218: 
                   14219: =item
                   14220: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14221: for course's uploaded content.
                   14222: 
                   14223: =over
                   14224: 
                   14225: =item
1.1172.2.68  raeburn  14226: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   14227: communityquota, textbookquota
1.1172.2.35  raeburn  14228: 
                   14229: =back
                   14230: 
                   14231: =item
                   14232: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14233: on your servers.
                   14234: 
                   14235: =over
                   14236: 
                   14237: =item
                   14238: remotesessions, hostedsessions
                   14239: 
                   14240: =back
                   14241: 
                   14242: =back
                   14243: 
                   14244: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14245: utility to create a configuration.db file on a domain's primary library server
                   14246: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14247: -- corresponding values are authentication type (internal, krb4, krb5,
                   14248: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   14249: will be available. Values are retrieved from cache (if current), unless the
                   14250: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14251: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14252: 
                   14253: Typical usage:
1.943     raeburn  14254: 
1.1172.2.35  raeburn  14255: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14256: 
1.243     albertel 14257: =back
                   14258: 
                   14259: =head2 Network Status Functions
                   14260: 
                   14261: =over 4
1.191     harris41 14262: 
                   14263: =item *
                   14264: 
1.1137    raeburn  14265: dirlist() : return directory list based on URI (first arg).
                   14266: 
                   14267: Inputs: 1 required, 5 optional.
                   14268: 
                   14269: =over
                   14270: 
                   14271: =item 
                   14272: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14273: 
                   14274: =item
                   14275: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14276: 
                   14277: =item
                   14278: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14279: 
                   14280: =item
                   14281: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14282: 
                   14283: =item
                   14284: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14285: 
                   14286: =item 
                   14287: $alternateRoot - path to prepend in place of path from $uri.
                   14288: 
                   14289: =back
                   14290: 
                   14291: Returns: Array of up to two items.
                   14292: 
                   14293: =over
                   14294: 
                   14295: a reference to an array of files/subdirectories
                   14296: 
                   14297: =over
                   14298: 
                   14299: Each element in the array of files/subdirectories is a & separated list of
                   14300: item name and the result of running stat on the item.  If dirlist was requested
                   14301: for a file instead of a directory, the item name will be ''. For a directory 
                   14302: listing, if the item is a metadata file, the element will end &N&M 
                   14303: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14304: default copyright set (1).  
                   14305: 
                   14306: =back
                   14307: 
                   14308: a scalar containing error condition (if encountered).
                   14309: 
                   14310: =over
                   14311: 
                   14312: =item 
                   14313: no_host (no homeserver identified for $username:$domain).
                   14314: 
                   14315: =item 
                   14316: no_such_host (server contacted for listing not identified as valid host).
                   14317: 
                   14318: =item 
                   14319: con_lost (connection to remote server failed).
                   14320: 
                   14321: =item 
                   14322: refused (invalid $username:$domain received on lond side).
                   14323: 
                   14324: =item 
                   14325: no_such_dir (directory at specified path on lond side does not exist). 
                   14326: 
                   14327: =item 
                   14328: empty (directory at specified path on lond side is empty).
                   14329: 
                   14330: =over
                   14331: 
                   14332: This is currently not encountered because the &ls3, &ls2, 
                   14333: &ls (_handler) routines on the lond side do not filter out
                   14334: . and .. from a directory listing. 
                   14335: 
                   14336: =back
                   14337: 
                   14338: =back
                   14339: 
                   14340: =back
1.191     harris41 14341: 
                   14342: =item *
                   14343: 
1.243     albertel 14344: spareserver() : find server with least workload from spare.tab
                   14345: 
1.986     foxr     14346: 
                   14347: =item *
                   14348: 
                   14349: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14350: if there is no corresponding loncapa host.
                   14351: 
1.243     albertel 14352: =back
                   14353: 
1.986     foxr     14354: 
1.243     albertel 14355: =head2 Apache Request
                   14356: 
                   14357: =over 4
1.191     harris41 14358: 
                   14359: =item *
                   14360: 
1.243     albertel 14361: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14362: localhost, posts hash
                   14363: 
                   14364: =back
                   14365: 
                   14366: =head2 Data to String to Data
                   14367: 
                   14368: =over 4
1.191     harris41 14369: 
                   14370: =item *
                   14371: 
1.243     albertel 14372: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14373: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14374: 
                   14375: =item *
                   14376: 
1.243     albertel 14377: hashref2str($hashref) : convert a hashref into a string complete with
                   14378: escaping and '=' and '&' separators, supports elements that are
                   14379: arrayrefs and hashrefs
1.191     harris41 14380: 
                   14381: =item *
                   14382: 
1.243     albertel 14383: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14384: with escaping and '&' separators, supports elements that are arrayrefs
                   14385: and hashrefs
1.191     harris41 14386: 
                   14387: =item *
                   14388: 
1.243     albertel 14389: str2hash($string) : convert string to hash using unescaping and
                   14390: splitting on '=' and '&', supports elements that are arrayrefs and
                   14391: hashrefs
1.191     harris41 14392: 
                   14393: =item *
                   14394: 
1.243     albertel 14395: str2array($string) : convert string to hash using unescaping and
                   14396: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14397: 
                   14398: =back
                   14399: 
                   14400: =head2 Logging Routines
                   14401: 
                   14402: 
                   14403: These routines allow one to make log messages in the lonnet.log and
                   14404: lonnet.perm logfiles.
1.191     harris41 14405: 
1.1119    foxr     14406: =over 4
                   14407: 
1.191     harris41 14408: =item *
                   14409: 
1.243     albertel 14410: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14411: 
                   14412: =item *
                   14413: 
1.243     albertel 14414: logthis() : append message to the normal lonnet.log file, it gets
                   14415: preiodically rolled over and deleted.
1.191     harris41 14416: 
                   14417: =item *
                   14418: 
1.243     albertel 14419: logperm() : append a permanent message to lonnet.perm.log, this log
                   14420: file never gets deleted by any automated portion of the system, only
                   14421: messages of critical importance should go in here.
                   14422: 
1.1119    foxr     14423: 
1.243     albertel 14424: =back
                   14425: 
                   14426: =head2 General File Helper Routines
                   14427: 
                   14428: =over 4
1.191     harris41 14429: 
                   14430: =item *
                   14431: 
1.481     raeburn  14432: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14433: (a) files in /uploaded
                   14434:   (i) If a local copy of the file exists - 
                   14435:       compares modification date of local copy with last-modified date for 
                   14436:       definitive version stored on home server for course. If local copy is 
                   14437:       stale, requests a new version from the home server and stores it. 
                   14438:       If the original has been removed from the home server, then local copy 
                   14439:       is unlinked.
                   14440:   (ii) If local copy does not exist -
                   14441:       requests the file from the home server and stores it. 
                   14442:   
                   14443:   If $caller is 'uploadrep':  
                   14444:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14445:     for request for files originally uploaded via DOCS. 
                   14446:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14447:   
                   14448:   Otherwise:
                   14449:      This indicates a call from the content generation phase of the request.
                   14450:      -  returns the entire contents of the file or -1.
                   14451:      
                   14452: (b) files in /res
                   14453:    - returns the entire contents of a file or -1; 
                   14454:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14455: 
1.712     albertel 14456: 
                   14457: =item *
                   14458: 
                   14459: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14460:                   reference
                   14461: 
                   14462: returns either a stat() list of data about the file or an empty list
                   14463: if the file doesn't exist or couldn't find out about it (connection
                   14464: problems or user unknown)
                   14465: 
1.191     harris41 14466: =item *
                   14467: 
1.243     albertel 14468: filelocation($dir,$file) : returns file system location of a file
                   14469: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14470: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14471: and a file of ../bob will become /a/bob)
1.191     harris41 14472: 
                   14473: =item *
                   14474: 
                   14475: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14476: filelocation except for hrefs
                   14477: 
                   14478: =item *
                   14479: 
1.1172.2.49  raeburn  14480: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14481: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14482: 
1.243     albertel 14483: =back
                   14484: 
1.608     albertel 14485: =head2 Usererfile file routines (/uploaded*)
                   14486: 
                   14487: =over 4
                   14488: 
                   14489: =item *
                   14490: 
                   14491: userfileupload(): main rotine for putting a file in a user or course's
                   14492:                   filespace, arguments are,
                   14493: 
1.620     albertel 14494:  formname - required - this is the name of the element in $env where the
1.608     albertel 14495:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14496:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14497:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14498:  context - if coursedoc, store the file in the course of the active role
                   14499:              of the current user; 
                   14500:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14501:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14502:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14503:          if undefined, it will be placed in "unknown"
                   14504: 
                   14505:  (This routine calls clean_filename() to remove any dangerous
                   14506:  characters from the filename, and then calls finuserfileupload() to
                   14507:  complete the transaction)
                   14508: 
                   14509:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14510:  and /adm/notfound.html if unsuccessful
                   14511: 
                   14512: =item *
                   14513: 
                   14514: clean_filename(): routine for cleaing a filename up for storage in
                   14515:                  userfile space, argument is:
                   14516: 
                   14517:  filename - proposed filename
                   14518: 
                   14519: returns: the new clean filename
                   14520: 
                   14521: =item *
                   14522: 
1.1090    raeburn  14523: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14524: userspace, probably shouldn't be called directly
                   14525: 
                   14526:   docuname: username or courseid of destination for the file
                   14527:   docudom: domain of user/course of destination for the file
                   14528:   formname: same as for userfileupload()
1.1090    raeburn  14529:   fname: filename (including subdirectories) for the file
                   14530:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14531:   allfiles: reference to hash used to store objects found by parser
                   14532:   codebase: reference to hash used for codebases of java objects found by parser
                   14533:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14534:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14535:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14536:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14537:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14538:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14539:   mimetype: reference to scalar to accommodate mime type determined
                   14540:             from File::MMagic if $parser = parse.
1.608     albertel 14541: 
                   14542:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14543:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14544:  was 'overwrite').
                   14545:  
1.608     albertel 14546: 
                   14547: =item *
                   14548: 
                   14549: renameuserfile(): renames an existing userfile to a new name
                   14550: 
                   14551:   Args:
                   14552:    docuname: username or courseid of destination for the file
                   14553:    docudom: domain of user/course of destination for the file
                   14554:    old: current file name (including any subdirs under userfiles)
                   14555:    new: desired file name (including any subdirs under userfiles)
                   14556: 
                   14557: =item *
                   14558: 
                   14559: mkdiruserfile(): creates a directory is a userfiles dir
                   14560: 
                   14561:   Args:
                   14562:    docuname: username or courseid of destination for the file
                   14563:    docudom: domain of user/course of destination for the file
                   14564:    dir: dir to create (including any subdirs under userfiles)
                   14565: 
                   14566: =item *
                   14567: 
                   14568: removeuserfile(): removes a file that exists in userfiles
                   14569: 
                   14570:   Args:
                   14571:    docuname: username or courseid of destination for the file
                   14572:    docudom: domain of user/course of destination for the file
                   14573:    fname: filname to delete (including any subdirs under userfiles)
                   14574: 
                   14575: =item *
                   14576: 
                   14577: removeuploadedurl(): convience function for removeuserfile()
                   14578: 
                   14579:   Args:
                   14580:    url:  a full /uploaded/... url to delete
                   14581: 
1.747     albertel 14582: =item * 
                   14583: 
                   14584: get_portfile_permissions():
                   14585:   Args:
                   14586:     domain: domain of user or course contain the portfolio files
                   14587:     user: name of user or num of course contain the portfolio files
                   14588:   Returns:
                   14589:     hashref of a dump of the proper file_permissions.db
                   14590:    
                   14591: 
                   14592: =item * 
                   14593: 
                   14594: get_access_controls():
                   14595: 
                   14596: Args:
                   14597:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14598:   group: (optional) the group you want the files associated with
                   14599:   file: (optional) the file you want access info on
                   14600: 
                   14601: Returns:
1.749     raeburn  14602:     a hash (keys are file names) of hashes containing
                   14603:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14604:         values are XML containing access control settings (see below) 
1.747     albertel 14605: 
                   14606: Internal notes:
                   14607: 
1.749     raeburn  14608:  access controls are stored in file_permissions.db as key=value pairs.
                   14609:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14610:         where scope -> public,guest,course,group,domains or users.
                   14611:               end -> UNIX time for end of access (0 -> no end date)
                   14612:               start -> UNIX time for start of access
                   14613: 
                   14614:     value -> XML description of access control
                   14615:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14616:             <start></start>
                   14617:             <end></end>
                   14618: 
                   14619:             <password></password>  for scope type = guest
                   14620: 
                   14621:             <domain></domain>     for scope type = course or group
                   14622:             <number></number>
                   14623:             <roles id="">
                   14624:              <role></role>
                   14625:              <access></access>
                   14626:              <section></section>
                   14627:              <group></group>
                   14628:             </roles>
                   14629: 
                   14630:             <dom></dom>         for scope type = domains
                   14631: 
                   14632:             <users>             for scope type = users
                   14633:              <user>
                   14634:               <uname></uname>
                   14635:               <udom></udom>
                   14636:              </user>
                   14637:             </users>
                   14638:            </scope> 
                   14639:               
                   14640:  Access data is also aggregated for each file in an additional key=value pair:
                   14641:  key -> path to file/file_name\0accesscontrol 
                   14642:  value -> reference to hash
                   14643:           hash contains key = value pairs
                   14644:           where key = uniqueID:scope_end_start
                   14645:                 value = UNIX time record was last updated
                   14646: 
                   14647:           Used to improve speed of look-ups of access controls for each file.  
                   14648:  
                   14649:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14650: 
1.1172.2.13  raeburn  14651: =item *
                   14652: 
1.749     raeburn  14653: modify_access_controls():
                   14654: 
                   14655: Modifies access controls for a portfolio file
                   14656: Args
                   14657: 1. file name
                   14658: 2. reference to hash of required changes,
                   14659: 3. domain
                   14660: 4. username
                   14661:   where domain,username are the domain of the portfolio owner 
                   14662:   (either a user or a course) 
                   14663: 
                   14664: Returns:
                   14665: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14666: 2. result of deletions ('ok' or 'error', with error message).
                   14667: 3. reference to hash of any new or updated access controls.
                   14668: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14669:    key = integer (inbound ID)
1.1172.2.13  raeburn  14670:    value = uniqueID
                   14671: 
                   14672: =item *
                   14673: 
                   14674: get_timebased_id():
                   14675: 
                   14676: Attempts to get a unique timestamp-based suffix for use with items added to a
                   14677: course via the Course Editor (e.g., folders, composite pages,
                   14678: group bulletin boards).
                   14679: 
                   14680: Args: (first three required; six others optional)
                   14681: 
                   14682: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14683:    docssequence, or name of group
                   14684: 
                   14685: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14686:    e.g., num, boardids
                   14687: 
                   14688: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   14689:    file will be named nohist_namespace.db
                   14690: 
                   14691: 4. cdom: domain of course; default is current course domain from %env
                   14692: 
                   14693: 5. cnum: course number; default is current course number from %env
                   14694: 
                   14695: 6. idtype: set to concat if an additional digit is to be appended to the
                   14696:    unix timestamp to form the suffix, if the plain timestamp is already
                   14697:    in use.  Default is to not do this, but simply increment the unix
                   14698:    timestamp by 1 until a unique key is obtained.
                   14699: 
                   14700: 7. who: holder of locking key; defaults to user:domain for user.
                   14701: 
                   14702: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   14703:    retrying); default is 3.
                   14704: 
                   14705: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   14706: 
                   14707: Returns:
                   14708: 
                   14709: 1. suffix obtained (numeric)
                   14710: 
                   14711: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14712: 
                   14713: 3. error: contains (localized) error message if an error occurred.
                   14714: 
1.747     albertel 14715: 
1.608     albertel 14716: =back
                   14717: 
1.243     albertel 14718: =head2 HTTP Helper Routines
                   14719: 
                   14720: =over 4
                   14721: 
1.191     harris41 14722: =item *
                   14723: 
                   14724: escape() : unpack non-word characters into CGI-compatible hex codes
                   14725: 
                   14726: =item *
                   14727: 
                   14728: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14729: 
1.243     albertel 14730: =back
                   14731: 
                   14732: =head1 PRIVATE SUBROUTINES
                   14733: 
                   14734: =head2 Underlying communication routines (Shouldn't call)
                   14735: 
                   14736: =over 4
                   14737: 
                   14738: =item *
                   14739: 
                   14740: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14741: 
                   14742: =item *
                   14743: 
                   14744: reply() : uses subreply to send a message to remote machine, logs all failures
                   14745: 
                   14746: =item *
                   14747: 
                   14748: critical() : passes a critical message to another server; if cannot
                   14749: get through then place message in connection buffer directory and
                   14750: returns con_delayed, if incapable of saving message, returns
                   14751: con_failed
                   14752: 
                   14753: =item *
                   14754: 
                   14755: reconlonc() : tries to reconnect lonc client processes.
                   14756: 
                   14757: =back
                   14758: 
                   14759: =head2 Resource Access Logging
                   14760: 
                   14761: =over 4
                   14762: 
                   14763: =item *
                   14764: 
                   14765: flushcourselogs() : flush (save) buffer logs and access logs
                   14766: 
                   14767: =item *
                   14768: 
                   14769: courselog($what) : save message for course in hash
                   14770: 
                   14771: =item *
                   14772: 
                   14773: courseacclog($what) : save message for course using &courselog().  Perform
                   14774: special processing for specific resource types (problems, exams, quizzes, etc).
                   14775: 
1.191     harris41 14776: =item *
                   14777: 
                   14778: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14779: as a PerlChildExitHandler
1.243     albertel 14780: 
                   14781: =back
                   14782: 
                   14783: =head2 Other
                   14784: 
                   14785: =over 4
                   14786: 
                   14787: =item *
                   14788: 
                   14789: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14790: 
                   14791: =back
                   14792: 
                   14793: =cut
1.877     foxr     14794: 

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